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 decode_workflow_entry<T: DeserializeOwned>(
2303    arguments: AvroValue,
2304    workflow_type: &str,
2305) -> Result<T> {
2306    decode_handler_input(arguments, HandlerKind::Workflow, workflow_type).map_err(|_| {
2307        // Serde errors may contain recorded values. The entry refusal exposes
2308        // only the registered workflow and expected Rust type.
2309        handler_type_error::<T>(
2310            HandlerKind::Workflow,
2311            workflow_type,
2312            HandlerValueKind::Input,
2313            "workflow_entry_arguments_mismatch: restore compatible entry code before retrying the original task",
2314        )
2315    })
2316}
2317
2318fn encode_handler_result<T: Serialize>(
2319    result: &T,
2320    handler_kind: HandlerKind,
2321    handler_name: &str,
2322) -> Result<AvroValue> {
2323    AvroValue::from_serialize(result).map_err(|error| {
2324        handler_type_error::<T>(
2325            handler_kind,
2326            handler_name,
2327            HandlerValueKind::Result,
2328            error.to_string(),
2329        )
2330    })
2331}
2332
2333fn decode_handler_result<T: DeserializeOwned>(
2334    result: AvroValue,
2335    handler_kind: HandlerKind,
2336    handler_name: &str,
2337) -> Result<T> {
2338    result.deserialize().map_err(|error| {
2339        handler_type_error::<T>(
2340            handler_kind,
2341            handler_name,
2342            HandlerValueKind::Result,
2343            error.to_string(),
2344        )
2345    })
2346}
2347
2348#[cfg(test)]
2349fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2350    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2351}
2352
2353fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2354    validate_payload_codec(fallback_codec)?;
2355
2356    if value.is_null() {
2357        return Ok(Value::Null);
2358    }
2359
2360    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2361        return decode_blob(blob, codec);
2362    }
2363
2364    if let Some(blob) = value.as_str() {
2365        return decode_blob(blob, fallback_codec);
2366    }
2367
2368    Err(untagged_payload_value())
2369}
2370
2371fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2372    let envelope = match codec {
2373        DEFAULT_CODEC => encode_avro_value(value)?,
2374        other => return Err(unsupported_payload_codec(other)),
2375    };
2376    Ok(serde_json::to_value(envelope)?)
2377}
2378
2379fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2380    validate_payload_codec(fallback_codec)?;
2381
2382    if value.is_null() {
2383        return Ok(AvroValue::Null);
2384    }
2385
2386    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2387        validate_payload_codec(codec)?;
2388        return decode_avro_value_blob(blob);
2389    }
2390
2391    if let Some(blob) = value.as_str() {
2392        return match fallback_codec {
2393            DEFAULT_CODEC => decode_avro_value_blob(blob),
2394            other => Err(unsupported_payload_codec(other)),
2395        };
2396    }
2397
2398    Err(untagged_payload_value())
2399}
2400
2401fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2402    match value {
2403        AvroValue::Null => AvroValue::Array(Vec::new()),
2404        AvroValue::Array(_) => value,
2405        other => AvroValue::Array(vec![other]),
2406    }
2407}
2408
2409fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2410    match codec {
2411        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2412        other => Err(unsupported_payload_codec(other)),
2413    }
2414}
2415
2416fn validate_payload_codec(codec: &str) -> Result<()> {
2417    match codec {
2418        DEFAULT_CODEC => Ok(()),
2419        MISSING_TASK_PAYLOAD_CODEC => {
2420            Err(invalid_task_payload_codec("task payload_codec is missing"))
2421        }
2422        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2423        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2424            "task payload_codec must be a string",
2425        )),
2426        other => Err(unsupported_payload_codec(other)),
2427    }
2428}
2429
2430fn invalid_task_payload_codec(reason: &str) -> Error {
2431    Error::Codec(format!(
2432        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2433    ))
2434}
2435
2436fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2437    let Some(object) = value.as_object() else {
2438        return Ok(None);
2439    };
2440    if !object.contains_key("codec") && !object.contains_key("blob") {
2441        return Ok(None);
2442    }
2443
2444    let codec = object
2445        .get("codec")
2446        .and_then(Value::as_str)
2447        .ok_or_else(invalid_payload_envelope)?;
2448    validate_payload_codec(codec)?;
2449    let blob = object
2450        .get("blob")
2451        .and_then(Value::as_str)
2452        .ok_or_else(invalid_payload_envelope)?;
2453    Ok(Some((codec, blob)))
2454}
2455
2456fn invalid_payload_envelope() -> Error {
2457    Error::Codec(
2458        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2459            .to_string(),
2460    )
2461}
2462
2463fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2464    for command in commands {
2465        let Some(command) = command.as_object() else {
2466            continue;
2467        };
2468        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2469            continue;
2470        };
2471        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2472            continue;
2473        };
2474
2475        if let Some(codec) = command.get("payload_codec") {
2476            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2477            validate_payload_codec(codec)?;
2478        }
2479
2480        let payload = command
2481            .get(payload_field)
2482            .ok_or_else(invalid_payload_envelope)?;
2483        if runtime_payloads::Reference::parse(payload)?.is_none() {
2484            validate_outbound_payload_envelope(payload)?;
2485        }
2486    }
2487    Ok(())
2488}
2489
2490fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2491    if commands.iter().any(|command| {
2492        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2493            && command
2494                .get("condition_wait_occurrence_id")
2495                .and_then(Value::as_str)
2496                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2497    }) {
2498        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2499    } else if commands.iter().any(|command| {
2500        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2501            && command.get("attribute_types").is_some()
2502    }) {
2503        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2504    } else if commands
2505        .iter()
2506        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2507    {
2508        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2509    } else if commands
2510        .iter()
2511        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2512    {
2513        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2514    } else if commands.iter().any(|command| {
2515        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2516    }) {
2517        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2518    } else {
2519        MINIMUM_WORKER_PROTOCOL_VERSION
2520    }
2521}
2522
2523fn workflow_completion_protocol_version_with_message_streams(
2524    commands: &[Value],
2525    has_message_stream_metadata: bool,
2526) -> &'static str {
2527    let command_protocol = workflow_completion_protocol_version(commands);
2528    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2529        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2530    } else {
2531        command_protocol
2532    }
2533}
2534
2535fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2536    match command_type {
2537        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2538        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2539        "start_service_operation" => Some("request_payload"),
2540        "upsert_memo" => Some("entries"),
2541        _ => None,
2542    }
2543}
2544
2545fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2546    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2547        return Err(untagged_payload_value());
2548    };
2549    validate_payload_codec(codec)?;
2550    decode_avro_value_blob(blob)?;
2551    Ok(())
2552}
2553
2554fn unsupported_payload_codec(codec: &str) -> Error {
2555    Error::Codec(format!(
2556        "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"
2557    ))
2558}
2559
2560fn untagged_payload_value() -> Error {
2561    Error::Codec(
2562        "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"
2563            .to_string(),
2564    )
2565}
2566
2567fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2568    let bytes = BASE64.decode(blob).map_err(|err| {
2569        Error::Codec(format!(
2570            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2571        ))
2572    })?;
2573
2574    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2575        return Err(unsupported_payload_codec("json"));
2576    }
2577
2578    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2579        return Err(Error::Codec(
2580            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2581        ));
2582    }
2583
2584    let fingerprint: [u8; 8] = bytes[2..10]
2585        .try_into()
2586        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2587    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2588        return Err(Error::Codec(format!(
2589            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2590            fingerprint
2591                .iter()
2592                .map(|byte| format!("{byte:02x}"))
2593                .collect::<String>()
2594        )));
2595    }
2596
2597    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2598    // The current fingerprint selects the current immutable schema, so reader
2599    // resolution would only re-walk the same recursive union. Future retained
2600    // writer fingerprints supply a distinct reader schema in this branch.
2601    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2602    if datum_reader.truncated {
2603        return Err(Error::Codec(
2604            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2605        ));
2606    }
2607    let datum = datum.map_err(|err| {
2608        Error::Codec(format!(
2609            "invalid_payload_framing: malformed Avro Value datum: {err}"
2610        ))
2611    })?;
2612    if datum_reader.remaining() != 0 {
2613        return Err(Error::Codec(format!(
2614            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2615            datum_reader.remaining()
2616        )));
2617    }
2618    avro_value_from_datum(datum)
2619}
2620
2621struct StrictAvroDatumReader<'a> {
2622    bytes: &'a [u8],
2623    offset: usize,
2624    truncated: bool,
2625}
2626
2627impl<'a> StrictAvroDatumReader<'a> {
2628    fn new(bytes: &'a [u8]) -> Self {
2629        Self {
2630            bytes,
2631            offset: 0,
2632            truncated: false,
2633        }
2634    }
2635
2636    fn remaining(&self) -> usize {
2637        self.bytes.len() - self.offset
2638    }
2639}
2640
2641impl Read for StrictAvroDatumReader<'_> {
2642    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2643        let count = buffer.len().min(self.remaining());
2644        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2645        self.offset += count;
2646        if count < buffer.len() {
2647            self.truncated = true;
2648        }
2649
2650        Ok(count)
2651    }
2652}
2653
2654fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2655    let branch = match value {
2656        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2657        AvroValue::Boolean(value) => AvroDatum::Union(
2658            1,
2659            Box::new(AvroDatum::Record(vec![(
2660                "boolean".to_string(),
2661                AvroDatum::Boolean(*value),
2662            )])),
2663        ),
2664        AvroValue::Long(value) => AvroDatum::Union(
2665            2,
2666            Box::new(AvroDatum::Record(vec![(
2667                "long".to_string(),
2668                AvroDatum::Long(*value),
2669            )])),
2670        ),
2671        AvroValue::Double(value) => {
2672            if !value.is_finite() {
2673                return Err(Error::Codec(
2674                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2675                ));
2676            }
2677            AvroDatum::Union(
2678                3,
2679                Box::new(AvroDatum::Record(vec![(
2680                    "double".to_string(),
2681                    AvroDatum::Double(*value),
2682                )])),
2683            )
2684        }
2685        AvroValue::Bytes(value) => AvroDatum::Union(
2686            4,
2687            Box::new(AvroDatum::Record(vec![(
2688                "bytes".to_string(),
2689                AvroDatum::Bytes(value.clone()),
2690            )])),
2691        ),
2692        AvroValue::String(value) => AvroDatum::Union(
2693            5,
2694            Box::new(AvroDatum::Record(vec![(
2695                "string".to_string(),
2696                AvroDatum::String(value.clone()),
2697            )])),
2698        ),
2699        AvroValue::Array(values) => AvroDatum::Union(
2700            6,
2701            Box::new(AvroDatum::Record(vec![(
2702                "items".to_string(),
2703                AvroDatum::Array(
2704                    values
2705                        .iter()
2706                        .map(avro_value_to_datum)
2707                        .collect::<Result<Vec<_>>>()?,
2708                ),
2709            )])),
2710        ),
2711        AvroValue::Map(values) => AvroDatum::Union(
2712            7,
2713            Box::new(AvroDatum::Record(vec![(
2714                "entries".to_string(),
2715                AvroDatum::Array(
2716                    values
2717                        .iter()
2718                        .map(|(key, value)| {
2719                            Ok(AvroDatum::Record(vec![
2720                                ("key".to_string(), AvroDatum::String(key.clone())),
2721                                ("value".to_string(), avro_value_to_datum(value)?),
2722                            ]))
2723                        })
2724                        .collect::<Result<Vec<_>>>()?,
2725                ),
2726            )])),
2727        ),
2728    };
2729    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2730}
2731
2732fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2733    let AvroDatum::Record(mut outer) = datum else {
2734        return Err(Error::Codec(
2735            "invalid_payload_framing: datum is not a Value record".to_string(),
2736        ));
2737    };
2738    let (_, branch) = outer
2739        .pop()
2740        .filter(|(name, _)| name == "value")
2741        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2742    let AvroDatum::Union(_, branch) = branch else {
2743        return Err(Error::Codec(
2744            "invalid_payload_framing: invalid Value union".to_string(),
2745        ));
2746    };
2747    match *branch {
2748        AvroDatum::Null => Ok(AvroValue::Null),
2749        AvroDatum::Record(mut fields) => {
2750            let (name, value) = fields.pop().ok_or_else(|| {
2751                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2752            })?;
2753            match (name.as_str(), value) {
2754                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2755                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2756                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2757                    Ok(AvroValue::Double(value))
2758                }
2759                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2760                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2761                ("items", AvroDatum::Array(values)) => values
2762                    .into_iter()
2763                    .map(avro_value_from_datum)
2764                    .collect::<Result<Vec<_>>>()
2765                    .map(AvroValue::Array),
2766                ("entries", AvroDatum::Map(values)) => values
2767                    .into_iter()
2768                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2769                    .collect::<Result<BTreeMap<_, _>>>()
2770                    .map(AvroValue::Map),
2771                _ => Err(Error::Codec(
2772                    "invalid_payload_framing: unknown Value branch".to_string(),
2773                )),
2774            }
2775        }
2776        _ => Err(Error::Codec(
2777            "invalid_payload_framing: invalid Value branch".to_string(),
2778        )),
2779    }
2780}
2781
2782fn avro_value_schema() -> Result<&'static Schema> {
2783    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2784        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2785            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2786    }) {
2787        Ok(schema) => Ok(schema),
2788        Err(message) => Err(Error::Codec(message.clone())),
2789    }
2790}
2791
2792fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2793    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2794        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2795        // have the same block representation when each ordered array record
2796        // contains the map key followed by its value, so this encoding-only
2797        // adaptation lets the official encoder retain BTreeMap wire order.
2798        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2799            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2800        let entries_schema = schema
2801            .pointer_mut("/fields/0/type/7/fields/0/type")
2802            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2803        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2804            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2805        }
2806        *entries_schema = json!({
2807            "type": "array",
2808            "items": {
2809                "type": "record",
2810                "name": "MapEntry",
2811                "fields": [
2812                    {"name": "key", "type": "string"},
2813                    {"name": "value", "type": "Value"}
2814                ]
2815            }
2816        });
2817        Schema::parse_str(&schema.to_string())
2818            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2819    }) {
2820        Ok(schema) => Ok(schema),
2821        Err(message) => Err(Error::Codec(message.clone())),
2822    }
2823}
2824
2825#[derive(Clone, Debug)]
2826pub struct Client {
2827    http: reqwest::Client,
2828    hydration_timeout: Duration,
2829    base_url: String,
2830    token: Option<String>,
2831    control_token: Option<String>,
2832    worker_token: Option<String>,
2833    namespace: String,
2834    max_external_payload_bytes: usize,
2835    worker_storage_admission: Option<WorkerStorageAdmission>,
2836    cooperative_worker_protocol: bool,
2837    worker_protocol_version: WorkerProtocolVersion,
2838    local_activities_enabled: bool,
2839    worker_sessions_enabled: bool,
2840    max_concurrent_worker_sessions: usize,
2841    worker_build_id: Option<String>,
2842    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2843    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2844}
2845
2846impl Client {
2847    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2848        Self::builder(base_url).build()
2849    }
2850
2851    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2852        ClientBuilder {
2853            base_url: base_url.into(),
2854            token: None,
2855            control_token: None,
2856            worker_token: None,
2857            namespace: "default".to_string(),
2858            timeout: Duration::from_secs(60),
2859            max_external_payload_bytes: 64 * 1024 * 1024,
2860            worker_protocol_version: WorkerProtocolVersion::default(),
2861        }
2862    }
2863
2864    pub async fn health(&self) -> Result<Value> {
2865        self.request_json(
2866            reqwest::Method::GET,
2867            "/health",
2868            RequestProtocol::ControlPlane,
2869            Option::<&Value>::None,
2870        )
2871        .await
2872    }
2873
2874    pub async fn cluster_info(&self) -> Result<Value> {
2875        self.request_json(
2876            reqwest::Method::GET,
2877            "/cluster/info",
2878            RequestProtocol::ControlPlane,
2879            Option::<&Value>::None,
2880        )
2881        .await
2882    }
2883
2884    pub async fn start_workflow<T: Serialize>(
2885        &self,
2886        workflow_type: &str,
2887        task_queue: &str,
2888        workflow_id: &str,
2889        input: T,
2890    ) -> Result<WorkflowHandle> {
2891        self.start_workflow_with_options(
2892            workflow_type,
2893            task_queue,
2894            workflow_id,
2895            WorkflowStartOptions::default(),
2896            input,
2897        )
2898        .await
2899    }
2900
2901    /// Start a workflow with explicit server-enforced execution and run
2902    /// deadlines.
2903    pub async fn start_workflow_with_options<T: Serialize>(
2904        &self,
2905        workflow_type: &str,
2906        task_queue: &str,
2907        workflow_id: &str,
2908        options: WorkflowStartOptions,
2909        input: T,
2910    ) -> Result<WorkflowHandle> {
2911        options.validate()?;
2912        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2913        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2914        let body = json!({
2915            "workflow_id": workflow_id,
2916            "workflow_type": workflow_type,
2917            "task_queue": task_queue,
2918            "input": input_envelope,
2919            "execution_timeout_seconds": options.execution_timeout_seconds,
2920            "run_timeout_seconds": options.run_timeout_seconds
2921        });
2922
2923        let data: Value = self
2924            .request_json(
2925                reqwest::Method::POST,
2926                "/workflows",
2927                RequestProtocol::ControlPlane,
2928                Some(&body),
2929            )
2930            .await?;
2931
2932        Ok(WorkflowHandle {
2933            client: self.clone(),
2934            workflow_id: data
2935                .get("workflow_id")
2936                .and_then(Value::as_str)
2937                .unwrap_or(workflow_id)
2938                .to_string(),
2939            run_id: data
2940                .get("run_id")
2941                .and_then(Value::as_str)
2942                .map(str::to_string),
2943            workflow_type: data
2944                .get("workflow_type")
2945                .and_then(Value::as_str)
2946                .unwrap_or(workflow_type)
2947                .to_string(),
2948        })
2949    }
2950
2951    pub async fn signal_workflow<T: Serialize>(
2952        &self,
2953        workflow_id: &str,
2954        signal_name: &str,
2955        input: T,
2956    ) -> Result<Value> {
2957        self.signal_workflow_target(workflow_id, None, signal_name, input)
2958            .await
2959    }
2960
2961    /// Append one idempotently identified item to an instance-scoped input stream.
2962    pub async fn append_message_stream<T: Serialize>(
2963        &self,
2964        workflow_id: &str,
2965        stream_name: &str,
2966        message_id: &str,
2967        input: T,
2968    ) -> Result<Value> {
2969        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2970        let body = json!({
2971            "message_id": message_id,
2972            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2973        });
2974        self.request_json(
2975            reqwest::Method::POST,
2976            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2977            RequestProtocol::ControlPlane,
2978            Some(&body),
2979        )
2980        .await
2981    }
2982
2983    /// Signal only if `run_id` is still the current run for this instance.
2984    pub async fn signal_workflow_run<T: Serialize>(
2985        &self,
2986        workflow_id: &str,
2987        run_id: &str,
2988        signal_name: &str,
2989        input: T,
2990    ) -> Result<Value> {
2991        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
2992            .await
2993    }
2994
2995    async fn signal_workflow_target<T: Serialize>(
2996        &self,
2997        workflow_id: &str,
2998        run_id: Option<&str>,
2999        signal_name: &str,
3000        input: T,
3001    ) -> Result<Value> {
3002        validate_user_signal_name(signal_name)?;
3003        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3004        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3005        let body = json!({
3006            "input": input_envelope
3007        });
3008        let path = match run_id {
3009            Some(run_id) => {
3010                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
3011            }
3012            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
3013        };
3014        self.request_json(
3015            reqwest::Method::POST,
3016            &path,
3017            RequestProtocol::ControlPlane,
3018            Some(&body),
3019        )
3020        .await
3021    }
3022
3023    /// Close the current run as cancelled immediately.
3024    ///
3025    /// Server revokes open tasks and timers without resuming workflow code for
3026    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3027    /// request on a supporting runtime and opted-in worker.
3028    pub async fn cancel_workflow(
3029        &self,
3030        workflow_id: &str,
3031        options: WorkflowCommandOptions,
3032    ) -> Result<WorkflowCommandResult> {
3033        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3034            .await
3035    }
3036
3037    /// Close the selected run as cancelled, only if `run_id` is still current.
3038    pub async fn cancel_workflow_run(
3039        &self,
3040        workflow_id: &str,
3041        run_id: &str,
3042        options: WorkflowCommandOptions,
3043    ) -> Result<WorkflowCommandResult> {
3044        self.workflow_command(
3045            workflow_id,
3046            Some(run_id),
3047            WorkflowCommandKind::Cancel,
3048            options,
3049        )
3050        .await
3051    }
3052
3053    /// Forcefully terminate the current run for an instance.
3054    pub async fn terminate_workflow(
3055        &self,
3056        workflow_id: &str,
3057        options: WorkflowCommandOptions,
3058    ) -> Result<WorkflowCommandResult> {
3059        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3060            .await
3061    }
3062
3063    /// Forcefully terminate only if `run_id` is still current.
3064    pub async fn terminate_workflow_run(
3065        &self,
3066        workflow_id: &str,
3067        run_id: &str,
3068        options: WorkflowCommandOptions,
3069    ) -> Result<WorkflowCommandResult> {
3070        self.workflow_command(
3071            workflow_id,
3072            Some(run_id),
3073            WorkflowCommandKind::Terminate,
3074            options,
3075        )
3076        .await
3077    }
3078
3079    /// Continue a failed run from its recorded activity failure boundary.
3080    pub async fn redrive_workflow_run(
3081        &self,
3082        workflow_id: &str,
3083        failed_run_id: &str,
3084        request_id: Option<&str>,
3085    ) -> Result<WorkflowRedriveResult> {
3086        let body = request_id
3087            .map(|id| json!({"request_id": id}))
3088            .unwrap_or_else(|| json!({}));
3089        let data: Value = self
3090            .request_json(
3091                reqwest::Method::POST,
3092                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3093                RequestProtocol::ControlPlane,
3094                Some(&body),
3095            )
3096            .await?;
3097        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3098            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3099        {
3100            return Err(Error::Codec(
3101                "redrive response was not accepted".to_string(),
3102            ));
3103        }
3104        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3105            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3106        {
3107            return Err(Error::Codec(
3108                "redrive response does not match the requested source run".to_string(),
3109            ));
3110        }
3111        let run_id = data
3112            .get("run_id")
3113            .and_then(Value::as_str)
3114            .filter(|id| !id.is_empty() && *id != failed_run_id)
3115            .ok_or_else(|| {
3116                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3117            })?;
3118        let resume_step_sequence = data
3119            .get("resume_step_sequence")
3120            .and_then(Value::as_u64)
3121            .filter(|sequence| *sequence > 0)
3122            .ok_or_else(|| {
3123                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3124            })?;
3125        Ok(WorkflowRedriveResult {
3126            workflow_id: workflow_id.to_string(),
3127            source_run_id: failed_run_id.to_string(),
3128            run_id: run_id.to_string(),
3129            resume_step_sequence,
3130            raw: data,
3131        })
3132    }
3133
3134    async fn workflow_command(
3135        &self,
3136        workflow_id: &str,
3137        run_id: Option<&str>,
3138        command: WorkflowCommandKind,
3139        options: WorkflowCommandOptions,
3140    ) -> Result<WorkflowCommandResult> {
3141        let path = match run_id {
3142            Some(run_id) => format!(
3143                "/workflows/{workflow_id}/runs/{run_id}/{}",
3144                command.as_str()
3145            ),
3146            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3147        };
3148        let data = match self
3149            .request_json(
3150                reqwest::Method::POST,
3151                &path,
3152                RequestProtocol::ControlPlane,
3153                Some(&options),
3154            )
3155            .await
3156        {
3157            Ok(data) => data,
3158            Err(Error::Http { status, body }) => {
3159                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3160                    command,
3161                    status,
3162                    body,
3163                    workflow_id,
3164                    run_id,
3165                )));
3166            }
3167            Err(error) => return Err(error),
3168        };
3169
3170        Ok(workflow_command_result(command, data, workflow_id, run_id))
3171    }
3172
3173    /// Execute a named, read-only query against a running or completed workflow.
3174    ///
3175    /// Arguments and results use the platform payload envelope. Server and
3176    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3177    /// reason, HTTP status, and original response body.
3178    pub async fn query_workflow<T: Serialize>(
3179        &self,
3180        workflow_id: &str,
3181        query_name: &str,
3182        input: T,
3183    ) -> Result<Value> {
3184        self.query_workflow_target(workflow_id, None, query_name, input)
3185            .await
3186    }
3187
3188    /// Query only if `run_id` is still current, preventing accidental retargeting.
3189    pub async fn query_workflow_run<T: Serialize>(
3190        &self,
3191        workflow_id: &str,
3192        run_id: &str,
3193        query_name: &str,
3194        input: T,
3195    ) -> Result<Value> {
3196        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3197            .await
3198    }
3199
3200    /// Query a workflow and return the lossless fixed Avro Value result.
3201    pub async fn query_workflow_avro_value<T: Serialize>(
3202        &self,
3203        workflow_id: &str,
3204        query_name: &str,
3205        input: T,
3206    ) -> Result<AvroValue> {
3207        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3208            .await
3209    }
3210
3211    /// Query a selected run and return the lossless fixed Avro Value result.
3212    pub async fn query_workflow_run_avro_value<T: Serialize>(
3213        &self,
3214        workflow_id: &str,
3215        run_id: &str,
3216        query_name: &str,
3217        input: T,
3218    ) -> Result<AvroValue> {
3219        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3220            .await
3221    }
3222
3223    async fn query_workflow_avro_value_target<T: Serialize>(
3224        &self,
3225        workflow_id: &str,
3226        run_id: Option<&str>,
3227        query_name: &str,
3228        input: T,
3229    ) -> Result<AvroValue> {
3230        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3231        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3232        let path = match run_id {
3233            Some(run_id) => {
3234                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3235            }
3236            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3237        };
3238        let response: Value = match self
3239            .request_json(
3240                reqwest::Method::POST,
3241                &path,
3242                RequestProtocol::ControlPlane,
3243                Some(&body),
3244            )
3245            .await
3246        {
3247            Ok(response) => response,
3248            Err(Error::Http { status, body }) => {
3249                return Err(Error::QueryFailed(query_failure(status, body)));
3250            }
3251            Err(error) => return Err(error),
3252        };
3253
3254        let envelope = response
3255            .get("result_envelope")
3256            .filter(|envelope| !envelope.is_null())
3257            .ok_or_else(|| {
3258                Error::Codec(
3259                    "missing_payload_envelope: typed query result requires result_envelope"
3260                        .to_string(),
3261                )
3262            })?;
3263        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3264    }
3265
3266    async fn query_workflow_target<T: Serialize>(
3267        &self,
3268        workflow_id: &str,
3269        run_id: Option<&str>,
3270        query_name: &str,
3271        input: T,
3272    ) -> Result<Value> {
3273        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3274        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3275        let body = json!({
3276            "input": input_envelope
3277        });
3278        let path = match run_id {
3279            Some(run_id) => {
3280                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3281            }
3282            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3283        };
3284        let response: Value = match self
3285            .request_json(
3286                reqwest::Method::POST,
3287                &path,
3288                RequestProtocol::ControlPlane,
3289                Some(&body),
3290            )
3291            .await
3292        {
3293            Ok(response) => response,
3294            Err(Error::Http { status, body }) => {
3295                return Err(Error::QueryFailed(query_failure(status, body)));
3296            }
3297            Err(error) => return Err(error),
3298        };
3299
3300        if let Some(envelope) = response
3301            .get("result_envelope")
3302            .filter(|envelope| !envelope.is_null())
3303        {
3304            return decode_wire_value(envelope, DEFAULT_CODEC);
3305        }
3306
3307        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3308    }
3309
3310    /// Send a synchronous update using fixed Avro Value arguments.
3311    pub async fn update_workflow<T: Serialize>(
3312        &self,
3313        workflow_id: &str,
3314        update_name: &str,
3315        input: T,
3316        request_id: Option<&str>,
3317    ) -> Result<Value> {
3318        let response = self
3319            .update_workflow_response(workflow_id, update_name, input, request_id)
3320            .await?;
3321        if let Some(envelope) = response
3322            .get("result_envelope")
3323            .filter(|envelope| !envelope.is_null())
3324        {
3325            return decode_wire_value(envelope, DEFAULT_CODEC);
3326        }
3327        Ok(response.get("result").cloned().unwrap_or(response))
3328    }
3329
3330    /// Send a synchronous update and retain a bytes-capable Avro result.
3331    pub async fn update_workflow_avro_value<T: Serialize>(
3332        &self,
3333        workflow_id: &str,
3334        update_name: &str,
3335        input: T,
3336        request_id: Option<&str>,
3337    ) -> Result<AvroValue> {
3338        let response = self
3339            .update_workflow_response(workflow_id, update_name, input, request_id)
3340            .await?;
3341        let envelope = response
3342            .get("result_envelope")
3343            .filter(|envelope| !envelope.is_null())
3344            .ok_or_else(|| {
3345                Error::Codec(
3346                    "missing_payload_envelope: typed update result requires result_envelope"
3347                        .to_string(),
3348                )
3349            })?;
3350        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3351    }
3352
3353    async fn update_workflow_response<T: Serialize>(
3354        &self,
3355        workflow_id: &str,
3356        update_name: &str,
3357        input: T,
3358        request_id: Option<&str>,
3359    ) -> Result<Value> {
3360        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3361        let mut body = json!({
3362            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3363            "wait_for": "completed",
3364        });
3365        if let Some(request_id) = request_id {
3366            body["request_id"] = json!(request_id);
3367        }
3368        self.request_json(
3369            reqwest::Method::POST,
3370            &format!("/workflows/{workflow_id}/update/{update_name}"),
3371            RequestProtocol::ControlPlane,
3372            Some(&body),
3373        )
3374        .await
3375    }
3376
3377    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3378        let path = format!("/workflows/{workflow_id}");
3379        let mut data: WorkflowDescription = self
3380            .request_json(
3381                reqwest::Method::GET,
3382                &path,
3383                RequestProtocol::ControlPlane,
3384                Option::<&Value>::None,
3385            )
3386            .await?;
3387        data.decode_payloads()?;
3388        Ok(data)
3389    }
3390
3391    /// Describe one selected run, including historical terminal runs.
3392    pub async fn describe_workflow_run(
3393        &self,
3394        workflow_id: &str,
3395        run_id: &str,
3396    ) -> Result<WorkflowDescription> {
3397        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3398        let mut data: WorkflowDescription = self
3399            .request_json(
3400                reqwest::Method::GET,
3401                &path,
3402                RequestProtocol::ControlPlane,
3403                Option::<&Value>::None,
3404            )
3405            .await?;
3406        data.decode_payloads()?;
3407        Ok(data)
3408    }
3409
3410    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3411        let mut path = format!(
3412            "/workflows/{}/runs/{}/streams",
3413            percent_encode_path_segment(workflow_id),
3414            percent_encode_path_segment(run_id),
3415        );
3416        if let Some(stream_name) = stream_name {
3417            path.push('/');
3418            path.push_str(&percent_encode_path_segment(stream_name));
3419        }
3420        path
3421    }
3422
3423    /// List the run-scoped output streams already opened by a workflow.
3424    pub async fn list_workflow_streams(
3425        &self,
3426        workflow_id: &str,
3427        run_id: &str,
3428    ) -> Result<Vec<WorkflowStreamDescription>> {
3429        let response: WorkflowStreamListResponse = self
3430            .request_json(
3431                reqwest::Method::GET,
3432                &Self::workflow_stream_path(workflow_id, run_id, None),
3433                RequestProtocol::ControlPlane,
3434                Option::<&Value>::None,
3435            )
3436            .await?;
3437        Ok(response.streams)
3438    }
3439
3440    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3441    pub async fn describe_workflow_stream(
3442        &self,
3443        workflow_id: &str,
3444        run_id: &str,
3445        stream_name: &str,
3446    ) -> Result<WorkflowStreamDescription> {
3447        let response: WorkflowStreamDescriptionResponse = self
3448            .request_json(
3449                reqwest::Method::GET,
3450                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3451                RequestProtocol::ControlPlane,
3452                Option::<&Value>::None,
3453            )
3454            .await?;
3455        Ok(response.stream)
3456    }
3457
3458    /// Read one bounded page beginning at a zero-based offset.
3459    ///
3460    /// Delivery is at least once: persist `next_offset` only after processing
3461    /// the page. The future is cancellation-safe; dropping it cancels the
3462    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3463    /// service contract.
3464    pub async fn subscribe_workflow_stream(
3465        &self,
3466        workflow_id: &str,
3467        run_id: &str,
3468        stream_name: &str,
3469        from_offset: u64,
3470        max_items: usize,
3471        wait: Duration,
3472    ) -> Result<WorkflowStreamPage> {
3473        let max_items = max_items.clamp(1, 500);
3474        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3475        let path = format!(
3476            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3477            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3478        );
3479        let response: WorkflowStreamPageResponse = self
3480            .request_json_with_timeout(
3481                reqwest::Method::GET,
3482                &path,
3483                RequestProtocol::ControlPlane,
3484                Option::<&Value>::None,
3485                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3486            )
3487            .await?;
3488
3489        let items = response
3490            .items
3491            .into_iter()
3492            .map(|raw| {
3493                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3494                let envelope = raw.get("payload").cloned();
3495                let payload = envelope
3496                    .as_ref()
3497                    .filter(|value| value.get("blob").is_some())
3498                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3499                    .transpose()?
3500                    .map(AvroValue::into_json)
3501                    .transpose()?;
3502                Ok(WorkflowStreamItem {
3503                    offset,
3504                    payload,
3505                    payload_envelope: envelope,
3506                    payload_reference: raw
3507                        .get("payload_reference")
3508                        .and_then(Value::as_str)
3509                        .map(str::to_string),
3510                    payload_codec: raw
3511                        .get("payload_codec")
3512                        .and_then(Value::as_str)
3513                        .map(str::to_string),
3514                    idempotency_key: raw
3515                        .get("idempotency_key")
3516                        .and_then(Value::as_str)
3517                        .map(str::to_string),
3518                    item_type: raw
3519                        .get("item_type")
3520                        .and_then(Value::as_str)
3521                        .map(str::to_string),
3522                    content_type: raw
3523                        .get("content_type")
3524                        .and_then(Value::as_str)
3525                        .map(str::to_string),
3526                    origin: raw
3527                        .get("origin")
3528                        .and_then(Value::as_str)
3529                        .map(str::to_string),
3530                    origin_reference: raw
3531                        .get("origin_reference")
3532                        .and_then(Value::as_str)
3533                        .map(str::to_string),
3534                    emitted_at: raw
3535                        .get("emitted_at")
3536                        .and_then(Value::as_str)
3537                        .map(str::to_string),
3538                    raw,
3539                })
3540            })
3541            .collect::<Result<Vec<_>>>()?;
3542        Ok(WorkflowStreamPage {
3543            stream: response.stream,
3544            items,
3545            next_offset: response.next_offset,
3546            terminal: response.terminal,
3547        })
3548    }
3549
3550    /// Append inline Avro envelopes or opaque external payload references.
3551    pub async fn append_workflow_stream(
3552        &self,
3553        workflow_id: &str,
3554        run_id: &str,
3555        stream_name: &str,
3556        items: &[WorkflowStreamAppendItem],
3557        max_pending_items: Option<u64>,
3558    ) -> Result<WorkflowStreamAppendResult> {
3559        if items.is_empty() {
3560            return Err(Error::Codec(
3561                "workflow_stream_items_empty: append requires at least one item".to_string(),
3562            ));
3563        }
3564        let mut body = json!({
3565            "items": items
3566                .iter()
3567                .map(|item| item.wire_value(None))
3568                .collect::<Vec<_>>(),
3569        });
3570        if let Some(max_pending_items) = max_pending_items {
3571            if max_pending_items == 0 {
3572                return Err(Error::Codec(
3573                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3574                        .to_string(),
3575                ));
3576            }
3577            body["max_pending_items"] = json!(max_pending_items);
3578        }
3579        let response: WorkflowStreamAppendResponse = self
3580            .request_json(
3581                reqwest::Method::POST,
3582                &format!(
3583                    "{}/items",
3584                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3585                ),
3586                RequestProtocol::ControlPlane,
3587                Some(&body),
3588            )
3589            .await?;
3590        Ok(WorkflowStreamAppendResult {
3591            stream: response.stream,
3592            accepted_offsets: response.accepted_offsets,
3593            accepted: response.accepted,
3594            deduped: response.deduped,
3595        })
3596    }
3597
3598    /// Close a stream, or mark it errored when `error_reason` is supplied.
3599    pub async fn close_workflow_stream(
3600        &self,
3601        workflow_id: &str,
3602        run_id: &str,
3603        stream_name: &str,
3604        error_reason: Option<&str>,
3605        retention_seconds: Option<u64>,
3606    ) -> Result<WorkflowStreamDescription> {
3607        let mut body = json!({});
3608        if let Some(error_reason) = error_reason {
3609            body["error_reason"] = json!(error_reason);
3610        }
3611        if let Some(retention_seconds) = retention_seconds {
3612            if retention_seconds == 0 {
3613                return Err(Error::Codec(
3614                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3615                        .to_string(),
3616                ));
3617            }
3618            body["retention_seconds"] = json!(retention_seconds);
3619        }
3620        let response: WorkflowStreamDescriptionResponse = self
3621            .request_json(
3622                reqwest::Method::POST,
3623                &format!(
3624                    "{}/close",
3625                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3626                ),
3627                RequestProtocol::ControlPlane,
3628                Some(&body),
3629            )
3630            .await?;
3631        Ok(response.stream)
3632    }
3633
3634    pub async fn register_worker(
3635        &self,
3636        worker_id: &str,
3637        task_queue: &str,
3638        supported_workflow_types: Vec<String>,
3639        supported_activity_types: Vec<String>,
3640        max_concurrent_workflow_tasks: usize,
3641        max_concurrent_activity_tasks: usize,
3642    ) -> Result<RegisterWorkerResponse> {
3643        self.register_worker_with_capabilities(
3644            worker_id,
3645            task_queue,
3646            supported_workflow_types,
3647            supported_activity_types,
3648            max_concurrent_workflow_tasks,
3649            max_concurrent_activity_tasks,
3650            Vec::new(),
3651        )
3652        .await
3653    }
3654
3655    /// Register a worker and explicitly advertise additive worker capabilities.
3656    pub async fn register_worker_with_capabilities(
3657        &self,
3658        worker_id: &str,
3659        task_queue: &str,
3660        supported_workflow_types: Vec<String>,
3661        supported_activity_types: Vec<String>,
3662        max_concurrent_workflow_tasks: usize,
3663        max_concurrent_activity_tasks: usize,
3664        capabilities: Vec<String>,
3665    ) -> Result<RegisterWorkerResponse> {
3666        self.register_worker_with_command_contracts(
3667            worker_id,
3668            task_queue,
3669            supported_workflow_types,
3670            supported_activity_types,
3671            max_concurrent_workflow_tasks,
3672            max_concurrent_activity_tasks,
3673            capabilities,
3674            Value::Object(serde_json::Map::new()),
3675        )
3676        .await
3677    }
3678
3679    /// Register a worker and advertise its named query and update handlers.
3680    ///
3681    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3682    /// so a workflow contract with a non-empty or malformed
3683    /// `update_validators` declaration returns
3684    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3685    #[allow(clippy::too_many_arguments)]
3686    pub async fn register_worker_with_command_contracts(
3687        &self,
3688        worker_id: &str,
3689        task_queue: &str,
3690        supported_workflow_types: Vec<String>,
3691        supported_activity_types: Vec<String>,
3692        max_concurrent_workflow_tasks: usize,
3693        max_concurrent_activity_tasks: usize,
3694        capabilities: Vec<String>,
3695        workflow_command_contracts: Value,
3696    ) -> Result<RegisterWorkerResponse> {
3697        self.register_worker_with_definition_fingerprints(
3698            worker_id,
3699            task_queue,
3700            supported_workflow_types,
3701            supported_activity_types,
3702            max_concurrent_workflow_tasks,
3703            max_concurrent_activity_tasks,
3704            capabilities,
3705            workflow_command_contracts,
3706            None,
3707        )
3708        .await
3709    }
3710
3711    #[allow(clippy::too_many_arguments)]
3712    async fn register_worker_with_definition_fingerprints(
3713        &self,
3714        worker_id: &str,
3715        task_queue: &str,
3716        supported_workflow_types: Vec<String>,
3717        supported_activity_types: Vec<String>,
3718        max_concurrent_workflow_tasks: usize,
3719        max_concurrent_activity_tasks: usize,
3720        capabilities: Vec<String>,
3721        workflow_command_contracts: Value,
3722        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3723    ) -> Result<RegisterWorkerResponse> {
3724        if let Some(contracts) = workflow_command_contracts.as_object() {
3725            for (workflow_type, contract) in contracts {
3726                let Some(update_validators) = contract.get("update_validators") else {
3727                    continue;
3728                };
3729                if !update_validators
3730                    .as_array()
3731                    .is_some_and(|validators| validators.is_empty())
3732                {
3733                    return Err(Error::UnsupportedUpdateValidators {
3734                        workflow_type: workflow_type.clone(),
3735                    });
3736                }
3737            }
3738        }
3739
3740        let mut body = json!({
3741            "worker_id": worker_id,
3742            "task_queue": task_queue,
3743            "runtime": "rust",
3744            "sdk_version": SDK_VERSION,
3745            "supported_workflow_types": supported_workflow_types,
3746            "supported_activity_types": supported_activity_types,
3747            "capabilities": capabilities,
3748            "capability_manifest": portable_worker_affinity_capability_manifest(),
3749            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3750            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3751        });
3752        if let Some(build_id) = &self.worker_build_id {
3753            if build_id.is_empty() || build_id.len() > 255 {
3754                return Err(Error::WorkerLoop(
3755                    "worker build ID must contain 1 to 255 bytes".into(),
3756                ));
3757            }
3758            body["build_id"] = json!(build_id);
3759        }
3760        if self.sticky_cache.is_some() {
3761            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
3762                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
3763                "implementation":"bounded_durable_history_cache"});
3764        }
3765        if self.local_activities_enabled {
3766            body["capability_manifest"]["local_activities"] = json!({"supported":true,
3767                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3768        }
3769        if self.worker_sessions_enabled {
3770            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
3771                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3772            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
3773        }
3774        if workflow_command_contracts
3775            .as_object()
3776            .is_some_and(|contracts| !contracts.is_empty())
3777        {
3778            body["workflow_command_contracts"] = workflow_command_contracts;
3779        }
3780        if let Some(fingerprints) = workflow_definition_fingerprints {
3781            body["workflow_definition_fingerprints"] = json!(fingerprints);
3782        }
3783
3784        let response: Value = self
3785            .request_json(
3786                reqwest::Method::POST,
3787                "/worker/register",
3788                RequestProtocol::DefaultWorker,
3789                Some(&body),
3790            )
3791            .await?;
3792        if self.sticky_cache.is_some() {
3793            self.confirm_sticky_registration(&response, worker_id, task_queue)
3794                .await?;
3795        }
3796        if self.local_activities_enabled || self.worker_sessions_enabled {
3797            let compatible = response["registered"].as_bool() == Some(true)
3798                && response["worker_id"].as_str() == Some(worker_id)
3799                && response["namespace"].as_str() == Some(self.namespace.as_str())
3800                && response["task_queue"].as_str() == Some(task_queue)
3801                && response["protocol_version"]
3802                    .as_str()
3803                    .and_then(|version| version.strip_prefix("1."))
3804                    .and_then(|minor| minor.parse::<u64>().ok())
3805                    .is_some_and(|minor| minor >= 18)
3806                && (!self.local_activities_enabled
3807                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
3808                        == Some(true))
3809                && (!self.worker_sessions_enabled
3810                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
3811                        == Some(true)
3812                        && response["capabilities"].as_array().is_some_and(|accepted| {
3813                            capabilities.iter().all(|capability| {
3814                                accepted
3815                                    .iter()
3816                                    .any(|value| value.as_str() == Some(capability.as_str()))
3817                            })
3818                        })));
3819            if !compatible {
3820                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
3821                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
3822                } else {
3823                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
3824                });
3825                if response["registered"] == true
3826                    && response["worker_id"].as_str() == Some(worker_id)
3827                {
3828                    if let Err(deregistration) =
3829                        self.deregister_worker_registration(worker_id).await
3830                    {
3831                        return Err(Error::WorkerShutdown {
3832                            primary: Box::new(error),
3833                            deregistration: Box::new(deregistration),
3834                        });
3835                    }
3836                }
3837                return Err(error);
3838            }
3839        }
3840        if self.cooperative_worker_protocol {
3841            let compatible = response["registered"].as_bool() == Some(true)
3842                && response["worker_id"].as_str() == Some(worker_id)
3843                && response["namespace"].as_str() == Some(self.namespace.as_str())
3844                && response["task_queue"].as_str() == Some(task_queue)
3845                && response["protocol_version"]
3846                    .as_str()
3847                    .is_some_and(cooperative_cancellation::supports_protocol)
3848                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
3849                    == Some(true)
3850                && response["capabilities"].as_array().is_some_and(|accepted| {
3851                    capabilities.iter().all(|capability| {
3852                        accepted
3853                            .iter()
3854                            .any(|value| value.as_str() == Some(capability.as_str()))
3855                    })
3856                });
3857            if !compatible {
3858                let error = Error::CooperativeCancellationUnavailable(
3859                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3860                );
3861                if response["registered"].as_bool() == Some(true)
3862                    && response["worker_id"].as_str() == Some(worker_id)
3863                {
3864                    if let Err(deregistration) =
3865                        self.deregister_worker_registration(worker_id).await
3866                    {
3867                        return Err(Error::WorkerShutdown {
3868                            primary: Box::new(error),
3869                            deregistration: Box::new(deregistration),
3870                        });
3871                    }
3872                }
3873                return Err(error);
3874            }
3875        }
3876        Ok(serde_json::from_value(response)?)
3877    }
3878
3879    /// Gracefully remove one worker's registration through the worker plane.
3880    ///
3881    /// This operation is separate from operator-facing worker management. It
3882    /// uses worker-protocol authentication and returns the server's lease
3883    /// recovery result.
3884    pub async fn deregister_worker_registration(
3885        &self,
3886        worker_id: &str,
3887    ) -> Result<WorkerDeregistrationEnvelope> {
3888        let path = format!(
3889            "/worker/registrations/{}",
3890            percent_encode_path_segment(worker_id)
3891        );
3892        self.request_json(
3893            reqwest::Method::DELETE,
3894            &path,
3895            RequestProtocol::DefaultWorker,
3896            Option::<&Value>::None,
3897        )
3898        .await
3899    }
3900
3901    /// Long-poll for an ephemeral, read-only workflow query task.
3902    pub async fn poll_query_task(
3903        &self,
3904        worker_id: &str,
3905        task_queue: &str,
3906        timeout: Duration,
3907    ) -> Result<Option<QueryTask>> {
3908        Ok(self
3909            .poll_query_task_response(worker_id, task_queue, timeout)
3910            .await?
3911            .task)
3912    }
3913
3914    /// Poll a query task while preserving server stop and drain metadata.
3915    pub async fn poll_query_task_response(
3916        &self,
3917        worker_id: &str,
3918        task_queue: &str,
3919        timeout: Duration,
3920    ) -> Result<PollQueryTaskResponse> {
3921        let poll_request_id = unique_request_id("rust-query-poll");
3922        self.poll_query_task_response_with_request_id(
3923            worker_id,
3924            task_queue,
3925            timeout,
3926            &poll_request_id,
3927            1,
3928        )
3929        .await
3930    }
3931
3932    async fn poll_query_task_response_with_request_id(
3933        &self,
3934        worker_id: &str,
3935        task_queue: &str,
3936        timeout: Duration,
3937        poll_request_id: &str,
3938        transport_retries: usize,
3939    ) -> Result<PollQueryTaskResponse> {
3940        let timeout_seconds = long_poll_timeout_seconds(timeout);
3941        let body = json!({
3942            "worker_id": worker_id,
3943            "task_queue": task_queue,
3944            "poll_request_id": poll_request_id,
3945            "timeout_seconds": timeout_seconds,
3946        });
3947        self.poll_request_json(
3948            "/worker/query-tasks/poll",
3949            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3950            &body,
3951            timeout + Duration::from_secs(5),
3952            transport_retries,
3953        )
3954        .await
3955    }
3956
3957    /// Complete a query task without appending workflow history.
3958    pub async fn complete_query_task<T: Serialize>(
3959        &self,
3960        query_task_id: &str,
3961        lease_owner: &str,
3962        query_task_attempt: u64,
3963        result: T,
3964        codec: &str,
3965    ) -> Result<Value> {
3966        let typed_result = AvroValue::from_serialize(&result)?;
3967        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3968        self.complete_query_task_with_envelope(
3969            query_task_id,
3970            lease_owner,
3971            query_task_attempt,
3972            typed_result.into_json()?,
3973            result_envelope,
3974        )
3975        .await
3976    }
3977
3978    async fn complete_query_task_with_envelope(
3979        &self,
3980        query_task_id: &str,
3981        lease_owner: &str,
3982        query_task_attempt: u64,
3983        result: Value,
3984        result_envelope: Value,
3985    ) -> Result<Value> {
3986        let body = json!({
3987            "lease_owner": lease_owner,
3988            "query_task_attempt": query_task_attempt,
3989            "result": result,
3990            "result_envelope": result_envelope,
3991        });
3992        let path = format!("/worker/query-tasks/{query_task_id}/complete");
3993        let response = self
3994            .request_json(
3995                reqwest::Method::POST,
3996                &path,
3997                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3998                Some(&body),
3999            )
4000            .await;
4001        query_task_response(response)
4002    }
4003
4004    /// Report a stable machine-readable query-task failure.
4005    pub async fn fail_query_task(
4006        &self,
4007        query_task_id: &str,
4008        lease_owner: &str,
4009        query_task_attempt: u64,
4010        message: impl Into<String>,
4011        reason: impl Into<String>,
4012        failure_type: impl Into<String>,
4013    ) -> Result<Value> {
4014        let body = json!({
4015            "lease_owner": lease_owner,
4016            "query_task_attempt": query_task_attempt,
4017            "failure": {
4018                "message": message.into(),
4019                "reason": reason.into(),
4020                "type": failure_type.into(),
4021            }
4022        });
4023        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4024        let response = self
4025            .request_json(
4026                reqwest::Method::POST,
4027                &path,
4028                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4029                Some(&body),
4030            )
4031            .await;
4032        query_task_response(response)
4033    }
4034
4035    pub async fn heartbeat_worker(
4036        &self,
4037        worker_id: &str,
4038        workflow_available: usize,
4039        activity_available: usize,
4040    ) -> Result<Value> {
4041        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4042            .await
4043    }
4044
4045    async fn heartbeat_worker_with_sessions(
4046        &self,
4047        worker_id: &str,
4048        workflow_available: usize,
4049        activity_available: usize,
4050        session_available: Option<usize>,
4051    ) -> Result<Value> {
4052        let mut body = json!({
4053            "worker_id": worker_id,
4054            "task_slots": {
4055                "workflow_available": workflow_available,
4056                "activity_available": activity_available
4057            },
4058            "process_metrics": {
4059                "process_id": std::process::id(),
4060                "process_uptime_seconds": 0
4061            }
4062        });
4063
4064        if let Some(available) = session_available {
4065            body["task_slots"]["session_available"] = json!(available);
4066        }
4067
4068        self.request_json(
4069            reqwest::Method::POST,
4070            "/worker/heartbeat",
4071            RequestProtocol::DefaultWorker,
4072            Some(&body),
4073        )
4074        .await
4075    }
4076
4077    pub async fn poll_workflow_task(
4078        &self,
4079        worker_id: &str,
4080        task_queue: &str,
4081        timeout: Duration,
4082    ) -> Result<Option<WorkflowTask>> {
4083        Ok(self
4084            .poll_workflow_task_response(worker_id, task_queue, timeout)
4085            .await?
4086            .task)
4087    }
4088
4089    pub async fn poll_workflow_task_response(
4090        &self,
4091        worker_id: &str,
4092        task_queue: &str,
4093        timeout: Duration,
4094    ) -> Result<PollWorkflowTaskResponse> {
4095        let poll_request_id = unique_request_id("rust-workflow-poll");
4096        self.poll_workflow_task_response_with_request_id(
4097            worker_id,
4098            task_queue,
4099            timeout,
4100            &poll_request_id,
4101            1,
4102        )
4103        .await
4104    }
4105
4106    async fn poll_workflow_task_response_with_request_id(
4107        &self,
4108        worker_id: &str,
4109        task_queue: &str,
4110        timeout: Duration,
4111        poll_request_id: &str,
4112        transport_retries: usize,
4113    ) -> Result<PollWorkflowTaskResponse> {
4114        let body = json!({
4115            "worker_id": worker_id,
4116            "task_queue": task_queue,
4117            "poll_request_id": poll_request_id,
4118            "timeout_seconds": long_poll_timeout_seconds(timeout),
4119            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4120        });
4121        let mut wire: Value = self
4122            .poll_request_json_unresolved(
4123                "/worker/workflow-tasks/poll",
4124                RequestProtocol::DefaultWorker,
4125                &body,
4126                timeout + Duration::from_secs(5),
4127                transport_retries,
4128            )
4129            .await?;
4130        let claim =
4131            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4132        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4133            self.resolve_runtime_payloads(
4134                &mut wire,
4135                "/worker/workflow-tasks/poll",
4136                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4137            )
4138            .await?;
4139            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4140            if let Some(task) = data.task.as_mut() {
4141                self.fetch_remaining_workflow_history(worker_id, task)
4142                    .await?;
4143            }
4144            Ok(data)
4145        })
4146        .await?;
4147        Ok(data)
4148    }
4149
4150    async fn fetch_remaining_workflow_history(
4151        &self,
4152        worker_id: &str,
4153        task: &mut WorkflowTask,
4154    ) -> Result<()> {
4155        let mut next_token = task.next_history_page_token.clone();
4156        let mut seen = BTreeSet::new();
4157
4158        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4159            if seen.len() >= 128 || !seen.insert(token.clone()) {
4160                return Err(Error::Codec(
4161                    "workflow history pagination exceeded its page bound or repeated a token"
4162                        .into(),
4163                ));
4164            }
4165            let lease_owner = task
4166                .lease_owner
4167                .clone()
4168                .unwrap_or_else(|| worker_id.to_string());
4169            let page = self
4170                .workflow_task_history_page(
4171                    &task.task_id,
4172                    &lease_owner,
4173                    task.workflow_task_attempt,
4174                    &token,
4175                )
4176                .await?;
4177
4178            task.append_history_page(page);
4179
4180            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4181                return Err(Error::Codec(
4182                    "workflow history pagination returned the same page token".to_string(),
4183                ));
4184            }
4185
4186            next_token = task.next_history_page_token.clone();
4187        }
4188
4189        Ok(())
4190    }
4191
4192    async fn workflow_task_history_page(
4193        &self,
4194        task_id: &str,
4195        lease_owner: &str,
4196        workflow_task_attempt: u64,
4197        next_history_page_token: &str,
4198    ) -> Result<WorkflowTaskHistoryPage> {
4199        let body = json!({
4200            "lease_owner": lease_owner,
4201            "workflow_task_attempt": workflow_task_attempt,
4202            "next_history_page_token": next_history_page_token
4203        });
4204        let path = format!("/worker/workflow-tasks/{task_id}/history");
4205
4206        self.request_json(
4207            reqwest::Method::POST,
4208            &path,
4209            RequestProtocol::DefaultWorker,
4210            Some(&body),
4211        )
4212        .await
4213    }
4214
4215    pub async fn complete_workflow_task(
4216        &self,
4217        task_id: &str,
4218        lease_owner: &str,
4219        workflow_task_attempt: u64,
4220        commands: Vec<Value>,
4221    ) -> Result<Value> {
4222        self.complete_workflow_task_with_message_streams(
4223            task_id,
4224            lease_owner,
4225            workflow_task_attempt,
4226            commands,
4227            Vec::new(),
4228            Vec::new(),
4229            None,
4230        )
4231        .await
4232    }
4233
4234    #[allow(clippy::too_many_arguments)]
4235    async fn complete_workflow_task_with_message_streams(
4236        &self,
4237        task_id: &str,
4238        lease_owner: &str,
4239        workflow_task_attempt: u64,
4240        commands: Vec<Value>,
4241        message_stream_cursors: Vec<Value>,
4242        message_stream_waits: Vec<Value>,
4243        sticky_cache: Option<Value>,
4244    ) -> Result<Value> {
4245        validate_workflow_task_commands(&commands)?;
4246        let has_message_stream_metadata =
4247            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4248        if has_message_stream_metadata
4249            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4250        {
4251            return Err(Error::Codec(
4252                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4253                    .to_string(),
4254            ));
4255        }
4256        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4257            &commands,
4258            has_message_stream_metadata,
4259        );
4260        let protocol_version = if sticky_cache.is_some()
4261            && protocol_version
4262                .strip_prefix("1.")
4263                .and_then(|minor| minor.parse::<u64>().ok())
4264                .is_some_and(|minor| minor < 18)
4265        {
4266            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4267        } else {
4268            protocol_version
4269        };
4270        let mut body = json!({
4271            "lease_owner": lease_owner,
4272            "workflow_task_attempt": workflow_task_attempt,
4273            "commands": commands
4274        });
4275        if !message_stream_cursors.is_empty() {
4276            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4277        }
4278        if !message_stream_waits.is_empty() {
4279            body["message_stream_waits"] = Value::Array(message_stream_waits);
4280        }
4281        if let Some(claim) = sticky_cache {
4282            body["sticky_cache"] = claim;
4283        }
4284        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4285        self.request_json(
4286            reqwest::Method::POST,
4287            &path,
4288            RequestProtocol::Worker(protocol_version),
4289            Some(&body),
4290        )
4291        .await
4292    }
4293
4294    pub async fn fail_workflow_task(
4295        &self,
4296        task_id: &str,
4297        lease_owner: &str,
4298        workflow_task_attempt: u64,
4299        message: impl Into<String>,
4300    ) -> Result<Value> {
4301        self.fail_workflow_task_with_type(
4302            task_id,
4303            lease_owner,
4304            workflow_task_attempt,
4305            message,
4306            "RustWorkflowTaskFailure",
4307        )
4308        .await
4309    }
4310
4311    async fn fail_workflow_task_with_type(
4312        &self,
4313        task_id: &str,
4314        lease_owner: &str,
4315        workflow_task_attempt: u64,
4316        message: impl Into<String>,
4317        failure_type: &str,
4318    ) -> Result<Value> {
4319        self.fail_workflow_task_with_failure(
4320            task_id,
4321            lease_owner,
4322            workflow_task_attempt,
4323            json!({"message": message.into(), "type": failure_type}),
4324        )
4325        .await
4326    }
4327
4328    async fn fail_workflow_task_with_failure(
4329        &self,
4330        task_id: &str,
4331        lease_owner: &str,
4332        workflow_task_attempt: u64,
4333        failure: Value,
4334    ) -> Result<Value> {
4335        let body = json!({
4336            "lease_owner": lease_owner,
4337            "workflow_task_attempt": workflow_task_attempt,
4338            "failure": failure,
4339        });
4340        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4341        self.request_json(
4342            reqwest::Method::POST,
4343            &path,
4344            RequestProtocol::DefaultWorker,
4345            Some(&body),
4346        )
4347        .await
4348    }
4349
4350    pub async fn poll_activity_task(
4351        &self,
4352        worker_id: &str,
4353        task_queue: &str,
4354        timeout: Duration,
4355    ) -> Result<Option<ActivityTask>> {
4356        Ok(self
4357            .poll_activity_task_response(worker_id, task_queue, timeout)
4358            .await?
4359            .task)
4360    }
4361
4362    /// Poll an activity task while preserving server stop and drain metadata.
4363    pub async fn poll_activity_task_response(
4364        &self,
4365        worker_id: &str,
4366        task_queue: &str,
4367        timeout: Duration,
4368    ) -> Result<PollActivityTaskResponse> {
4369        let poll_request_id = unique_request_id("rust-activity-poll");
4370        self.poll_activity_task_response_with_request_id(
4371            worker_id,
4372            task_queue,
4373            timeout,
4374            &poll_request_id,
4375            1,
4376        )
4377        .await
4378        .map(worker_session::SessionPollResponse::ordinary)
4379    }
4380
4381    async fn poll_activity_task_response_with_request_id(
4382        &self,
4383        worker_id: &str,
4384        task_queue: &str,
4385        timeout: Duration,
4386        poll_request_id: &str,
4387        transport_retries: usize,
4388    ) -> Result<worker_session::SessionPollResponse> {
4389        let body = json!({
4390            "worker_id": worker_id,
4391            "task_queue": task_queue,
4392            "poll_request_id": poll_request_id,
4393            "timeout_seconds": long_poll_timeout_seconds(timeout),
4394        });
4395        let mut wire: Value = self
4396            .poll_request_json_unresolved(
4397                "/worker/activity-tasks/poll",
4398                RequestProtocol::DefaultWorker,
4399                &body,
4400                timeout + Duration::from_secs(5),
4401                transport_retries,
4402            )
4403            .await?;
4404        let claim = activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?;
4405        let mut data: worker_session::SessionPollResponse =
4406            activity_hydration::HydrationClaim::protect(claim.as_ref(), self, async {
4407                self.resolve_runtime_payloads(
4408                    &mut wire,
4409                    "/worker/activity-tasks/poll",
4410                    RequestProtocol::DefaultWorker,
4411                )
4412                .await?;
4413                Ok(serde_json::from_value(wire)?)
4414            })
4415            .await?;
4416        if let Some(task) = data.task.as_mut() {
4417            task.hydration_claim = claim;
4418        }
4419        Ok(data)
4420    }
4421
4422    pub async fn complete_activity_task<T: Serialize>(
4423        &self,
4424        task_id: &str,
4425        activity_attempt_id: &str,
4426        lease_owner: &str,
4427        result: T,
4428        codec: &str,
4429    ) -> Result<Value> {
4430        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4431        let body = json!({
4432            "activity_attempt_id": activity_attempt_id,
4433            "lease_owner": lease_owner,
4434            "result": result
4435        });
4436        let path = format!("/worker/activity-tasks/{task_id}/complete");
4437        activity_task_response(
4438            self.request_json(
4439                reqwest::Method::POST,
4440                &path,
4441                RequestProtocol::DefaultWorker,
4442                Some(&body),
4443            )
4444            .await,
4445            "complete",
4446            task_id,
4447            activity_attempt_id,
4448        )
4449    }
4450
4451    pub async fn fail_activity_task(
4452        &self,
4453        task_id: &str,
4454        activity_attempt_id: &str,
4455        lease_owner: &str,
4456        message: impl Into<String>,
4457        non_retryable: bool,
4458    ) -> Result<Value> {
4459        let body = json!({
4460            "activity_attempt_id": activity_attempt_id,
4461            "lease_owner": lease_owner,
4462            "failure": {
4463                "message": message.into(),
4464                "type": "RustActivityFailure",
4465                "non_retryable": non_retryable
4466            }
4467        });
4468        let path = format!("/worker/activity-tasks/{task_id}/fail");
4469        activity_task_response(
4470            self.request_json(
4471                reqwest::Method::POST,
4472                &path,
4473                RequestProtocol::DefaultWorker,
4474                Some(&body),
4475            )
4476            .await,
4477            "fail",
4478            task_id,
4479            activity_attempt_id,
4480        )
4481    }
4482
4483    /// Record a flat map of scalar/null activity progress metadata.
4484    ///
4485    /// Heartbeat details use the Server's bounded JSON progress contract.
4486    /// They are not workflow payload envelopes.
4487    pub async fn heartbeat_activity_task<T: Serialize>(
4488        &self,
4489        task_id: &str,
4490        activity_attempt_id: &str,
4491        lease_owner: &str,
4492        details: T,
4493    ) -> Result<ActivityHeartbeatResponse> {
4494        serde_json::from_value(
4495            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4496                .await?,
4497        )
4498        .map_err(Error::from)
4499    }
4500
4501    async fn heartbeat_activity_task_value<T: Serialize>(
4502        &self,
4503        task_id: &str,
4504        activity_attempt_id: &str,
4505        lease_owner: &str,
4506        details: T,
4507    ) -> Result<Value> {
4508        let details = AvroValue::from_serialize(&details)?.into_json()?;
4509        let body = json!({
4510            "activity_attempt_id": activity_attempt_id,
4511            "lease_owner": lease_owner,
4512            "details": details
4513        });
4514        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4515        activity_task_response(
4516            self.request_json(
4517                reqwest::Method::POST,
4518                &path,
4519                RequestProtocol::DefaultWorker,
4520                Some(&body),
4521            )
4522            .await,
4523            "heartbeat",
4524            task_id,
4525            activity_attempt_id,
4526        )
4527    }
4528
4529    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4530        &self,
4531        method: reqwest::Method,
4532        path: &str,
4533        protocol: RequestProtocol,
4534        body: Option<&B>,
4535    ) -> Result<T> {
4536        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4537            .await
4538    }
4539
4540    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4541        &self,
4542        method: reqwest::Method,
4543        path: &str,
4544        protocol: RequestProtocol,
4545        body: Option<&B>,
4546        timeout: Duration,
4547    ) -> Result<T> {
4548        let mut value: Value = self
4549            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4550            .await?;
4551        let protocol = match protocol {
4552            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4553                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4554            }
4555            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4556        };
4557        self.resolve_runtime_payloads(&mut value, path, protocol)
4558            .await?;
4559        Ok(serde_json::from_value(value)?)
4560    }
4561
4562    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4563        &self,
4564        method: reqwest::Method,
4565        path: &str,
4566        protocol: RequestProtocol,
4567        body: Option<&B>,
4568        timeout: Duration,
4569    ) -> Result<T> {
4570        let protocol = match protocol {
4571            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4572                let selected = self.worker_protocol_version.as_str();
4573                if self.cooperative_worker_protocol
4574                    && !cooperative_cancellation::supports_protocol(selected)
4575                {
4576                    return Err(Error::CooperativeCancellationUnavailable(
4577                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4578                    ));
4579                }
4580                if let RequestProtocol::Worker(minimum) = protocol {
4581                    let supported = minimum
4582                        .strip_prefix("1.")
4583                        .and_then(|minor| minor.parse::<u64>().ok())
4584                        .zip(
4585                            selected
4586                                .strip_prefix("1.")
4587                                .and_then(|minor| minor.parse::<u64>().ok()),
4588                        )
4589                        .is_some_and(|(minimum, selected)| selected >= minimum);
4590                    if !supported {
4591                        return Err(Error::WorkerLoop(format!(
4592                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4593                        )));
4594                    }
4595                }
4596                RequestProtocol::Worker(selected)
4597            }
4598            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4599        };
4600        let auth_token = self.auth_token(protocol)?;
4601        let mut request = self
4602            .http
4603            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4604            .timeout(timeout)
4605            .header(reqwest::header::ACCEPT, "application/json")
4606            .header(reqwest::header::CONTENT_TYPE, "application/json")
4607            .header("X-Namespace", &self.namespace);
4608
4609        match protocol {
4610            RequestProtocol::DefaultWorker => {
4611                request = request.header(
4612                    "X-Durable-Workflow-Protocol-Version",
4613                    self.worker_protocol_version.as_str(),
4614                );
4615            }
4616            RequestProtocol::Worker(version) => {
4617                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4618            }
4619            RequestProtocol::ControlPlane => {
4620                request = request.header(
4621                    "X-Durable-Workflow-Control-Plane-Version",
4622                    CONTROL_PLANE_VERSION,
4623                );
4624            }
4625        }
4626
4627        if let Some(token) = auth_token {
4628            request = request.bearer_auth(token);
4629        }
4630
4631        if let Some(body) = body {
4632            let mut body = serde_json::to_value(body)?;
4633            if matches!(
4634                method,
4635                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4636            ) {
4637                self.externalize_runtime_payloads(&mut body, path, protocol)
4638                    .await?;
4639            }
4640            request = request.json(&body);
4641        }
4642
4643        let request = request.build()?;
4644        let request_body = request
4645            .body()
4646            .and_then(reqwest::Body::as_bytes)
4647            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4648        let poll_request_id = path.ends_with("/poll").then(|| {
4649            request_body
4650                .as_ref()
4651                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4652                .unwrap_or_default()
4653        });
4654        let mut storage_retries = 0_usize;
4655        let mut deferred_workflow_completion = false;
4656
4657        loop {
4658            // Keep the serialized body and lease/poll identity across admission pauses.
4659            let receive = async {
4660                let response = self
4661                    .http
4662                    .execute(request.try_clone().ok_or_else(|| {
4663                        Error::WorkerLoop("worker request body cannot be retried".to_string())
4664                    })?)
4665                    .await?;
4666                let status = response.status();
4667                Ok::<_, Error>((status, response.bytes().await?))
4668            };
4669            let retry_deadline = self
4670                .worker_storage_admission
4671                .as_ref()
4672                .and_then(|admission| admission.workflow_completion_retry_deadline);
4673            if deferred_workflow_completion
4674                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
4675            {
4676                return Err(Error::Timeout);
4677            }
4678            let (status, bytes) = match retry_deadline.filter(|_| deferred_workflow_completion) {
4679                Some(deadline) => tokio::time::timeout_at(deadline, receive)
4680                    .await
4681                    .map_err(|_| Error::Timeout)??,
4682                None => receive.await?,
4683            };
4684
4685            if !status.is_success() {
4686                let body = String::from_utf8_lossy(&bytes).to_string();
4687                if let Some(protocol) = protocol_failure(status, &body) {
4688                    return Err(Error::Protocol(protocol));
4689                }
4690                let error = Error::Http { status, body };
4691                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
4692                    &error,
4693                    path,
4694                    request_body.as_ref(),
4695                )
4696                .is_some();
4697                if self
4698                    .wait_for_storage_admission(
4699                        &error,
4700                        protocol,
4701                        Some(path),
4702                        poll_request_id.as_deref(),
4703                        request_body.as_ref(),
4704                        &mut storage_retries,
4705                    )
4706                    .await
4707                {
4708                    continue;
4709                }
4710                return Err(error);
4711            }
4712
4713            if bytes.is_empty() {
4714                return Ok(serde_json::from_value(Value::Null)?);
4715            }
4716
4717            return Ok(serde_json::from_slice(&bytes)?);
4718        }
4719    }
4720
4721    async fn wait_for_storage_admission(
4722        &self,
4723        error: &Error,
4724        protocol: RequestProtocol,
4725        path: Option<&str>,
4726        poll_request_id: Option<&str>,
4727        request_body: Option<&Value>,
4728        retries: &mut usize,
4729    ) -> bool {
4730        let Some(admission) = self
4731            .worker_storage_admission
4732            .as_ref()
4733            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4734        else {
4735            return false;
4736        };
4737        let completion_deferred = path.and_then(|path| {
4738            worker_deferred_workflow_completion_retry_after(error, path, request_body)
4739        });
4740        let Some(advertised_delay) = completion_deferred
4741            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
4742            .or_else(|| {
4743                path.and_then(|path| {
4744                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4745                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4746                })
4747            })
4748        else {
4749            return false;
4750        };
4751        *retries = retries.saturating_add(1);
4752        let delay = worker_retry_delay(admission.policy, *retries)
4753            .max(advertised_delay)
4754            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4755        let delay = if completion_deferred.is_some() {
4756            delay.max(advertised_delay)
4757        } else {
4758            delay
4759        };
4760        let wait_deadline = tokio::time::Instant::now() + delay;
4761        loop {
4762            if admission.stop.load(Ordering::SeqCst) {
4763                return false;
4764            }
4765            let now = tokio::time::Instant::now();
4766            if admission
4767                .workflow_completion_retry_deadline
4768                .is_some_and(|deadline| now >= deadline)
4769            {
4770                return false;
4771            }
4772            let remaining = wait_deadline.saturating_duration_since(now);
4773            if remaining.is_zero() {
4774                return true;
4775            }
4776            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4777        }
4778    }
4779
4780    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4781        &self,
4782        path: &str,
4783        protocol: RequestProtocol,
4784        body: &B,
4785        timeout: Duration,
4786        max_retries: usize,
4787    ) -> Result<T> {
4788        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
4789            .await
4790    }
4791
4792    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
4793        &self,
4794        path: &str,
4795        protocol: RequestProtocol,
4796        body: &B,
4797        timeout: Duration,
4798        max_retries: usize,
4799    ) -> Result<T> {
4800        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
4801            .await
4802    }
4803
4804    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
4805        &self,
4806        path: &str,
4807        protocol: RequestProtocol,
4808        body: &B,
4809        timeout: Duration,
4810        max_retries: usize,
4811        resolve: bool,
4812    ) -> Result<T> {
4813        let mut retries = 0;
4814
4815        loop {
4816            let response = if resolve {
4817                self.request_json_with_timeout(
4818                    reqwest::Method::POST,
4819                    path,
4820                    protocol,
4821                    Some(body),
4822                    timeout,
4823                )
4824                .await
4825            } else {
4826                self.request_json_unresolved_with_timeout(
4827                    reqwest::Method::POST,
4828                    path,
4829                    protocol,
4830                    Some(body),
4831                    timeout,
4832                )
4833                .await
4834            };
4835
4836            match response {
4837                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4838                response => return worker_poll_response(response),
4839            }
4840        }
4841    }
4842
4843    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4844        match protocol {
4845            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4846                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4847                    return Ok(Some(token));
4848                }
4849                if self.control_token.is_some() {
4850                    return Err(Error::MissingRoleCredentials {
4851                        role: "worker",
4852                        opposite_role: "control",
4853                    });
4854                }
4855                Ok(None)
4856            }
4857            RequestProtocol::ControlPlane => {
4858                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4859                    return Ok(Some(token));
4860                }
4861                if self.worker_token.is_some() {
4862                    return Err(Error::MissingRoleCredentials {
4863                        role: "control",
4864                        opposite_role: "worker",
4865                    });
4866                }
4867                Ok(None)
4868            }
4869        }
4870    }
4871}
4872
4873fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4874    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4875    let reason = body
4876        .get("reason")
4877        .and_then(Value::as_str)
4878        .unwrap_or("query_rejected")
4879        .to_string();
4880    let message = body
4881        .get("message")
4882        .or_else(|| body.get("error"))
4883        .and_then(Value::as_str)
4884        .unwrap_or("workflow query was rejected")
4885        .to_string();
4886
4887    QueryFailure {
4888        status: status.as_u16(),
4889        reason,
4890        message,
4891        body,
4892    }
4893}
4894
4895fn workflow_command_result(
4896    command: WorkflowCommandKind,
4897    data: Value,
4898    workflow_id: &str,
4899    run_id: Option<&str>,
4900) -> WorkflowCommandResult {
4901    WorkflowCommandResult {
4902        command,
4903        workflow_id: data
4904            .get("workflow_id")
4905            .and_then(Value::as_str)
4906            .unwrap_or(workflow_id)
4907            .to_string(),
4908        run_id: data
4909            .get("run_id")
4910            .and_then(Value::as_str)
4911            .or(run_id)
4912            .map(str::to_string),
4913        outcome: data
4914            .get("outcome")
4915            .and_then(Value::as_str)
4916            .map(str::to_string),
4917        reason: data
4918            .get("reason")
4919            .and_then(Value::as_str)
4920            .map(str::to_string),
4921        command_status: data
4922            .get("command_status")
4923            .and_then(Value::as_str)
4924            .map(str::to_string),
4925        raw: data,
4926    }
4927}
4928
4929fn workflow_command_rejection(
4930    command: WorkflowCommandKind,
4931    status: reqwest::StatusCode,
4932    raw_body: String,
4933    workflow_id: &str,
4934    run_id: Option<&str>,
4935) -> WorkflowCommandRejection {
4936    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4937    WorkflowCommandRejection {
4938        command,
4939        status: status.as_u16(),
4940        reason: body
4941            .get("reason")
4942            .and_then(Value::as_str)
4943            .unwrap_or("workflow_command_rejected")
4944            .to_string(),
4945        message: body
4946            .get("message")
4947            .or_else(|| body.get("error"))
4948            .and_then(Value::as_str)
4949            .unwrap_or("workflow lifecycle command was rejected")
4950            .to_string(),
4951        workflow_id: body
4952            .get("workflow_id")
4953            .and_then(Value::as_str)
4954            .unwrap_or(workflow_id)
4955            .to_string(),
4956        run_id: body
4957            .get("run_id")
4958            .and_then(Value::as_str)
4959            .or(run_id)
4960            .map(str::to_string),
4961        target_scope: body
4962            .get("target_scope")
4963            .and_then(Value::as_str)
4964            .map(str::to_string),
4965        body,
4966    }
4967}
4968
4969fn query_task_response(response: Result<Value>) -> Result<Value> {
4970    match response {
4971        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4972        response => response,
4973    }
4974}
4975
4976fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4977    match response {
4978        Err(Error::Http { status, body })
4979            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
4980        {
4981            Ok(serde_json::from_str(&body)?)
4982        }
4983        response => response,
4984    }
4985}
4986
4987fn worker_poll_body_is_stop(body: &str) -> bool {
4988    serde_json::from_str::<Value>(body)
4989        .ok()
4990        .is_some_and(|body| {
4991            worker_poll_is_stop(
4992                body.get("poll_status").and_then(Value::as_str),
4993                body.get("reason").and_then(Value::as_str),
4994            )
4995        })
4996}
4997
4998fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
4999    matches!(poll_status, Some("draining" | "stopped"))
5000        || matches!(reason, Some("worker_draining" | "worker_stopped"))
5001}
5002
5003fn query_task_rejection_is_final(error: &Error) -> bool {
5004    matches!(
5005        error,
5006        Error::QueryFailed(failure)
5007            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
5008    )
5009}
5010
5011fn activity_task_response<T>(
5012    response: Result<T>,
5013    operation: &str,
5014    task_id: &str,
5015    activity_attempt_id: &str,
5016) -> Result<T> {
5017    match response {
5018        Err(Error::Http { status, body }) => {
5019            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
5020            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
5021                operation: operation.to_string(),
5022                status: status.as_u16(),
5023                reason: body
5024                    .get("reason")
5025                    .and_then(Value::as_str)
5026                    .unwrap_or("activity_task_rejected")
5027                    .to_string(),
5028                task_id: body
5029                    .get("task_id")
5030                    .and_then(Value::as_str)
5031                    .unwrap_or(task_id)
5032                    .to_string(),
5033                activity_attempt_id: body
5034                    .get("activity_attempt_id")
5035                    .and_then(Value::as_str)
5036                    .unwrap_or(activity_attempt_id)
5037                    .to_string(),
5038                cancel_requested: body
5039                    .get("cancel_requested")
5040                    .and_then(Value::as_bool)
5041                    .unwrap_or(false),
5042                can_continue: body.get("can_continue").and_then(Value::as_bool),
5043                run_closed_reason: body
5044                    .get("run_closed_reason")
5045                    .and_then(Value::as_str)
5046                    .map(str::to_string),
5047                body,
5048            }))
5049        }
5050        response => response,
5051    }
5052}
5053
5054fn activity_task_rejection_is_final(error: &Error) -> bool {
5055    matches!(
5056        error,
5057        Error::ActivityTaskRejected(rejection)
5058            if matches!(
5059                rejection.reason.as_str(),
5060                "run_cancelled"
5061                    | "run_terminated"
5062                    | "attempt_closed"
5063                    | "stale_attempt"
5064                    | "activity_cancelled"
5065                    | "task_cancelled"
5066                    | "run_closed"
5067                    | "activity_not_running"
5068                    | "attempt_not_found"
5069            )
5070    )
5071}
5072
5073fn workflow_task_completion_is_terminal_timeout(
5074    error: &Error,
5075    task_id: &str,
5076    workflow_task_attempt: u64,
5077    run_id: Option<&str>,
5078) -> bool {
5079    let Error::Http { status, body } = error else {
5080        return false;
5081    };
5082    if *status != reqwest::StatusCode::CONFLICT {
5083        return false;
5084    }
5085
5086    let Some(run_id) = run_id else {
5087        return false;
5088    };
5089    let Ok(body) = serde_json::from_str::<Value>(body) else {
5090        return false;
5091    };
5092
5093    body.get("recorded").and_then(Value::as_bool) == Some(false)
5094        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5095        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5096        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5097        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5098        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5099}
5100
5101fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5102    let body: Value = serde_json::from_str(raw_body).ok()?;
5103    let reason = body.get("reason")?.as_str()?;
5104    if !matches!(
5105        reason,
5106        "missing_protocol_version"
5107            | "unsupported_protocol_version"
5108            | "missing_control_plane_version"
5109            | "unsupported_control_plane_version"
5110    ) {
5111        return None;
5112    }
5113
5114    Some(ProtocolFailure {
5115        status: status.as_u16(),
5116        reason: reason.to_string(),
5117        message: body
5118            .get("message")
5119            .or_else(|| body.get("error"))
5120            .and_then(Value::as_str)
5121            .unwrap_or("protocol version rejected")
5122            .to_string(),
5123        supported_version: body
5124            .get("supported_version")
5125            .and_then(Value::as_str)
5126            .map(str::to_string),
5127        requested_version: body
5128            .get("requested_version")
5129            .and_then(Value::as_str)
5130            .map(str::to_string),
5131        body,
5132    })
5133}
5134
5135fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5136    timeout
5137        .as_secs()
5138        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5139        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5140}
5141
5142fn worker_operation_is_retryable(error: &Error) -> bool {
5143    if worker_poll_capacity_retry_after(error).is_some()
5144        || worker_storage_admission_body(error).is_some()
5145        || worker_backend_unavailable_body(error).is_some()
5146        || worker_operation_is_explicitly_non_retryable(error)
5147    {
5148        return false;
5149    }
5150
5151    match error {
5152        Error::Transport(error) => {
5153            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5154        }
5155        Error::Http { status, .. } => {
5156            matches!(
5157                *status,
5158                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5159            ) || status.is_server_error()
5160        }
5161        _ => false,
5162    }
5163}
5164
5165fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5166    let body: Value = match error {
5167        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5168        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5169        _ => return None,
5170    };
5171    matches!(
5172        body.get("reason").and_then(Value::as_str),
5173        Some("storage_pressure" | "storage_admission_unavailable")
5174    )
5175    .then_some(body)
5176}
5177
5178fn worker_storage_admission_retry_after(
5179    error: &Error,
5180    poll_request_id: Option<&str>,
5181) -> Option<Duration> {
5182    let Error::Http { status, .. } = error else {
5183        return None;
5184    };
5185    let body = worker_storage_admission_body(error)?;
5186    let delay = body.get("retry_after_seconds")?.as_u64()?;
5187    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5188        || delay == 0
5189        || body.get("retryable") != Some(&Value::Bool(true))
5190        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5191        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5192        || body
5193            .get("request_admitted")
5194            .is_some_and(|admitted| admitted != &Value::Bool(false))
5195    {
5196        return None;
5197    }
5198    match poll_request_id {
5199        Some(id) => {
5200            if id.is_empty()
5201                || body.get("task") != Some(&Value::Null)
5202                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5203                || body.get("poll_status") != body.get("reason")
5204                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5205                || body.get("claim_admitted") != Some(&Value::Bool(false))
5206            {
5207                return None;
5208            }
5209        }
5210        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5211        None => {}
5212    }
5213    Some(Duration::from_secs(delay))
5214}
5215
5216fn worker_backend_unavailable_retry_after(
5217    error: &Error,
5218    path: &str,
5219    poll_request_id: Option<&str>,
5220) -> Option<Duration> {
5221    let operation = match path {
5222        "/worker/register" => "register_worker",
5223        "/worker/heartbeat" => "heartbeat_worker",
5224        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5225        "/worker/activity-tasks/poll" => "poll_activity_task",
5226        "/worker/query-tasks/poll" => "poll_query_task",
5227        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5228        _ => return None,
5229    };
5230    let body = worker_backend_unavailable_body(error)?;
5231    let delay = body.get("retry_after_seconds")?.as_u64()?;
5232    if delay == 0
5233        || body.get("operation")?.as_str()? != operation
5234        || body.get("outcome")?.as_str()? != "unknown"
5235        || body.get("retryable") != Some(&Value::Bool(true))
5236        || body.get("worker_id")?.as_str()?.is_empty()
5237    {
5238        return None;
5239    }
5240    if let Some(id) = poll_request_id {
5241        if id.is_empty()
5242            || body.get("task") != Some(&Value::Null)
5243            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5244            || body.get("poll_request_id")?.as_str()? != id
5245            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5246        {
5247            return None;
5248        }
5249    } else if path.ends_with("/poll") {
5250        return None;
5251    }
5252    Some(Duration::from_secs(delay))
5253}
5254
5255fn worker_fenced_completion_retry_after(
5256    error: &Error,
5257    path: &str,
5258    request_body: Option<&Value>,
5259) -> Option<Duration> {
5260    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5261        .strip_prefix("/worker/workflow-tasks/")
5262        .and_then(|tail| tail.strip_suffix("/complete"))
5263    {
5264        ("complete_workflow_task", task_id, "workflow_task_attempt")
5265    } else if let Some(task_id) = path
5266        .strip_prefix("/worker/activity-tasks/")
5267        .and_then(|tail| tail.strip_suffix("/complete"))
5268    {
5269        ("complete_activity_task", task_id, "activity_attempt_id")
5270    } else {
5271        return None;
5272    };
5273    if task_id.is_empty() || task_id.contains('/') {
5274        return None;
5275    }
5276
5277    let request = request_body?.as_object()?;
5278    let lease_owner = request.get("lease_owner")?.as_str()?;
5279    if lease_owner.is_empty() {
5280        return None;
5281    }
5282    let attempt = request.get(attempt_field)?;
5283    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5284        || (attempt_field == "activity_attempt_id"
5285            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5286    {
5287        return None;
5288    }
5289
5290    let body = worker_backend_unavailable_body(error)?;
5291    let delay = body.get("retry_after_seconds")?.as_u64()?;
5292    if delay == 0
5293        || body.get("operation")?.as_str()? != operation
5294        || body.get("outcome")?.as_str()? != "unknown"
5295        || body.get("retryable") != Some(&Value::Bool(true))
5296        || body.get("worker_id")?.as_str()? != lease_owner
5297        || body.get("task_queue") != Some(&Value::Null)
5298        || body.get("task_id")?.as_str()? != task_id
5299        || body.get("lease_owner")?.as_str()? != lease_owner
5300        || body.get(attempt_field) != Some(attempt)
5301    {
5302        return None;
5303    }
5304
5305    Some(Duration::from_secs(delay))
5306}
5307
5308fn worker_deferred_workflow_completion_retry_after(
5309    error: &Error,
5310    path: &str,
5311    request_body: Option<&Value>,
5312) -> Option<Duration> {
5313    let task_id = path
5314        .strip_prefix("/worker/workflow-tasks/")?
5315        .strip_suffix("/complete")?;
5316    if task_id.is_empty() || task_id.contains('/') {
5317        return None;
5318    }
5319    let request = request_body?.as_object()?;
5320    let owner = request.get("lease_owner")?.as_str()?;
5321    let attempt = request.get("workflow_task_attempt")?;
5322    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
5323        return None;
5324    }
5325    let Error::Http { status, body } = error else {
5326        return None;
5327    };
5328    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5329        return None;
5330    }
5331    let body: Value = serde_json::from_str(body).ok()?;
5332    let delay = body.get("retry_after_seconds")?.as_u64()?;
5333    if !(1..=5).contains(&delay)
5334        || body.get("reason")?.as_str()? != "backend_lock_pressure"
5335        || body.get("operation")?.as_str()? != "complete_workflow_task"
5336        || body.get("outcome")?.as_str()? != "deferred"
5337        || body.get("recorded") != Some(&Value::Bool(false))
5338        || body.get("retryable") != Some(&Value::Bool(true))
5339        || body.get("task_id")?.as_str()? != task_id
5340        || body.get("lease_owner")?.as_str()? != owner
5341        || body.get("workflow_task_attempt") != Some(attempt)
5342        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
5343    {
5344        return None;
5345    }
5346    Some(Duration::from_secs(delay))
5347}
5348
5349fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5350    let Error::Http { status, body } = error else {
5351        return None;
5352    };
5353    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5354        return None;
5355    }
5356    let body: Value = serde_json::from_str(body).ok()?;
5357    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5358}
5359
5360fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5361    let Error::Http { body, .. } = error else {
5362        return false;
5363    };
5364
5365    serde_json::from_str::<Value>(body)
5366        .ok()
5367        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5368        == Some(false)
5369}
5370
5371fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5372    let Error::Http { status, body } = error else {
5373        return None;
5374    };
5375    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5376        return None;
5377    }
5378
5379    let body = serde_json::from_str::<Value>(body).ok()?;
5380    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5381        == Some("long_poll_capacity_exhausted")
5382        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5383    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5384        return None;
5385    }
5386
5387    Some(Duration::from_secs(
5388        body.get("retry_after_seconds")
5389            .and_then(Value::as_u64)
5390            .unwrap_or_default(),
5391    ))
5392}
5393
5394fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5395    let exponent = retry.saturating_sub(1).min(31) as u32;
5396    policy
5397        .initial_backoff
5398        .saturating_mul(1_u32 << exponent)
5399        .min(policy.max_backoff)
5400}
5401
5402#[derive(Debug)]
5403pub struct ClientBuilder {
5404    base_url: String,
5405    token: Option<String>,
5406    control_token: Option<String>,
5407    worker_token: Option<String>,
5408    namespace: String,
5409    timeout: Duration,
5410    max_external_payload_bytes: usize,
5411    worker_protocol_version: WorkerProtocolVersion,
5412}
5413
5414impl ClientBuilder {
5415    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5416    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5417        self.worker_protocol_version = version;
5418        self
5419    }
5420
5421    pub fn token(mut self, token: Option<String>) -> Self {
5422        self.token = token;
5423        self
5424    }
5425
5426    pub fn control_token(mut self, token: Option<String>) -> Self {
5427        self.control_token = token;
5428        self
5429    }
5430
5431    pub fn worker_token(mut self, token: Option<String>) -> Self {
5432        self.worker_token = token;
5433        self
5434    }
5435
5436    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5437        self.namespace = namespace.into();
5438        self
5439    }
5440
5441    pub fn timeout(mut self, timeout: Duration) -> Self {
5442        self.timeout = timeout;
5443        self
5444    }
5445
5446    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5447    /// References are fetched only from this client's authenticated runtime.
5448    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5449        self.max_external_payload_bytes = bytes;
5450        self
5451    }
5452
5453    pub fn build(self) -> Result<Client> {
5454        let base_url = self.base_url.trim_end_matches('/').to_string();
5455        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5456            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5457            .unwrap_or_else(|_| base_url.ends_with("/api"));
5458
5459        if has_sdk_api_suffix {
5460            return Err(Error::InvalidBaseUrl);
5461        }
5462
5463        Ok(Client {
5464            http: reqwest::Client::builder()
5465                .timeout(self.timeout)
5466                .redirect(reqwest::redirect::Policy::none())
5467                .build()?,
5468            hydration_timeout: self.timeout,
5469            base_url,
5470            token: self.token,
5471            control_token: self.control_token,
5472            worker_token: self.worker_token,
5473            namespace: self.namespace,
5474            max_external_payload_bytes: self.max_external_payload_bytes,
5475            worker_storage_admission: None,
5476            cooperative_worker_protocol: false,
5477            worker_protocol_version: self.worker_protocol_version,
5478            local_activities_enabled: false,
5479            worker_sessions_enabled: false,
5480            max_concurrent_worker_sessions: 10,
5481            worker_build_id: None,
5482            sticky_cache: None,
5483            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5484        })
5485    }
5486}
5487
5488#[derive(Clone, Debug)]
5489pub struct WorkflowHandle {
5490    client: Client,
5491    pub workflow_id: String,
5492    pub run_id: Option<String>,
5493    pub workflow_type: String,
5494}
5495
5496impl WorkflowHandle {
5497    /// Describe whichever run is current for this stable workflow instance.
5498    pub async fn describe(&self) -> Result<WorkflowDescription> {
5499        self.client.describe_workflow(&self.workflow_id).await
5500    }
5501
5502    /// Describe the run identity originally selected by this handle.
5503    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5504        let run_id = self.run_id.as_deref().ok_or_else(|| {
5505            Error::Codec("run_id is required for selected-run description".to_string())
5506        })?;
5507        self.client
5508            .describe_workflow_run(&self.workflow_id, run_id)
5509            .await
5510    }
5511
5512    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5513        self.client
5514            .signal_workflow(&self.workflow_id, signal_name, input)
5515            .await
5516    }
5517
5518    pub async fn append_message<T: Serialize>(
5519        &self,
5520        stream_name: &str,
5521        message_id: &str,
5522        input: T,
5523    ) -> Result<Value> {
5524        self.client
5525            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5526            .await
5527    }
5528
5529    /// Signal only if this handle's selected run is still current.
5530    pub async fn signal_selected_run<T: Serialize>(
5531        &self,
5532        signal_name: &str,
5533        input: T,
5534    ) -> Result<Value> {
5535        let run_id = self.run_id.as_deref().ok_or_else(|| {
5536            Error::Codec("run_id is required for selected-run signaling".to_string())
5537        })?;
5538        self.client
5539            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5540            .await
5541    }
5542
5543    /// Close whichever run is current as cancelled, without workflow cleanup.
5544    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5545        self.client
5546            .cancel_workflow(&self.workflow_id, options)
5547            .await
5548    }
5549
5550    /// Request cancellation only if this handle's selected run is still current.
5551    pub async fn cancel_selected_run(
5552        &self,
5553        options: WorkflowCommandOptions,
5554    ) -> Result<WorkflowCommandResult> {
5555        let run_id = self.run_id.as_deref().ok_or_else(|| {
5556            Error::Codec("run_id is required for selected-run cancellation".to_string())
5557        })?;
5558        self.client
5559            .cancel_workflow_run(&self.workflow_id, run_id, options)
5560            .await
5561    }
5562
5563    /// Forcefully terminate whichever run is current.
5564    pub async fn terminate(
5565        &self,
5566        options: WorkflowCommandOptions,
5567    ) -> Result<WorkflowCommandResult> {
5568        self.client
5569            .terminate_workflow(&self.workflow_id, options)
5570            .await
5571    }
5572
5573    /// Terminate only if this handle's selected run is still current.
5574    pub async fn terminate_selected_run(
5575        &self,
5576        options: WorkflowCommandOptions,
5577    ) -> Result<WorkflowCommandResult> {
5578        let run_id = self.run_id.as_deref().ok_or_else(|| {
5579            Error::Codec("run_id is required for selected-run termination".to_string())
5580        })?;
5581        self.client
5582            .terminate_workflow_run(&self.workflow_id, run_id, options)
5583            .await
5584    }
5585
5586    /// Continue this handle's failed run without repeating completed activities.
5587    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5588        let run_id = self
5589            .run_id
5590            .as_deref()
5591            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5592        self.client
5593            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5594            .await
5595    }
5596
5597    /// Execute a named, read-only query against this workflow.
5598    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5599        self.client
5600            .query_workflow(&self.workflow_id, query_name, input)
5601            .await
5602    }
5603
5604    pub async fn query_avro_value<T: Serialize>(
5605        &self,
5606        query_name: &str,
5607        input: T,
5608    ) -> Result<AvroValue> {
5609        self.client
5610            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5611            .await
5612    }
5613
5614    pub async fn update<T: Serialize>(
5615        &self,
5616        update_name: &str,
5617        input: T,
5618        request_id: Option<&str>,
5619    ) -> Result<Value> {
5620        self.client
5621            .update_workflow(&self.workflow_id, update_name, input, request_id)
5622            .await
5623    }
5624
5625    pub async fn update_avro_value<T: Serialize>(
5626        &self,
5627        update_name: &str,
5628        input: T,
5629        request_id: Option<&str>,
5630    ) -> Result<AvroValue> {
5631        self.client
5632            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5633            .await
5634    }
5635
5636    /// Query only if this handle's selected run is still current.
5637    pub async fn query_selected_run<T: Serialize>(
5638        &self,
5639        query_name: &str,
5640        input: T,
5641    ) -> Result<Value> {
5642        let run_id = self
5643            .run_id
5644            .as_deref()
5645            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5646        self.client
5647            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5648            .await
5649    }
5650
5651    /// Await the final terminal outcome of the current continue-as-new chain.
5652    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5653        self.result_target(options, None).await
5654    }
5655
5656    /// Await the final result without projecting Avro bytes through JSON.
5657    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5658        self.result_avro_value_target(options, None).await
5659    }
5660
5661    /// Await the final result and decode it into a Serde application type.
5662    pub async fn result_typed<T: DeserializeOwned>(
5663        &self,
5664        options: WorkflowResultOptions,
5665    ) -> Result<T> {
5666        let result = self.result_avro_value(options).await?;
5667        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5668    }
5669
5670    /// Await only the run identity originally selected by this handle.
5671    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5672        let run_id = self.run_id.as_deref().ok_or_else(|| {
5673            Error::Codec("run_id is required for selected-run result".to_string())
5674        })?;
5675        self.result_target(options, Some(run_id)).await
5676    }
5677
5678    /// Await the selected run's result on the lossless Avro Value surface.
5679    pub async fn result_selected_run_avro_value(
5680        &self,
5681        options: WorkflowResultOptions,
5682    ) -> Result<AvroValue> {
5683        let run_id = self.run_id.as_deref().ok_or_else(|| {
5684            Error::Codec("run_id is required for selected-run result".to_string())
5685        })?;
5686        self.result_avro_value_target(options, Some(run_id)).await
5687    }
5688
5689    /// Await the selected run and decode its result into a Serde type.
5690    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5691        &self,
5692        options: WorkflowResultOptions,
5693    ) -> Result<T> {
5694        let result = self.result_selected_run_avro_value(options).await?;
5695        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5696    }
5697
5698    async fn result_avro_value_target(
5699        &self,
5700        options: WorkflowResultOptions,
5701        selected_run_id: Option<&str>,
5702    ) -> Result<AvroValue> {
5703        let started = Instant::now();
5704
5705        loop {
5706            let description = match selected_run_id {
5707                Some(run_id) => {
5708                    self.client
5709                        .describe_workflow_run(&self.workflow_id, run_id)
5710                        .await?
5711                }
5712                None => self.describe().await?,
5713            };
5714            if description.is_completed() {
5715                return description.output_avro_value.ok_or_else(|| {
5716                    Error::Codec(
5717                        "missing_payload_envelope: typed workflow result requires output_envelope"
5718                            .to_string(),
5719                    )
5720                });
5721            }
5722            if description.is_terminal() {
5723                let outcome =
5724                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5725                return Err(match outcome.kind {
5726                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5727                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5728                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5729                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5730                });
5731            }
5732            if started.elapsed() >= options.timeout {
5733                return Err(Error::Timeout);
5734            }
5735            tokio::time::sleep(options.poll_interval).await;
5736        }
5737    }
5738
5739    async fn result_target(
5740        &self,
5741        options: WorkflowResultOptions,
5742        selected_run_id: Option<&str>,
5743    ) -> Result<Value> {
5744        let started = Instant::now();
5745
5746        loop {
5747            let description = match selected_run_id {
5748                Some(run_id) => {
5749                    self.client
5750                        .describe_workflow_run(&self.workflow_id, run_id)
5751                        .await?
5752                }
5753                None => self.describe().await?,
5754            };
5755            if description.is_completed() {
5756                return Ok(description.output.unwrap_or(Value::Null));
5757            }
5758
5759            if description.is_terminal() {
5760                let outcome =
5761                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5762                return Err(match outcome.kind {
5763                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5764                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5765                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5766                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5767                });
5768            }
5769
5770            if started.elapsed() >= options.timeout {
5771                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5772                    kind: WorkflowTerminalKind::TimedOut,
5773                    workflow_id: description
5774                        .workflow_id
5775                        .clone()
5776                        .unwrap_or_else(|| self.workflow_id.clone()),
5777                    run_id: description
5778                        .run_id
5779                        .clone()
5780                        .or_else(|| selected_run_id.map(str::to_string)),
5781                    reason: "result_wait_timeout".to_string(),
5782                    failure_category: Some("client_timeout".to_string()),
5783                    failure_id: None,
5784                    exception_type: None,
5785                    exception_class: None,
5786                    non_retryable: None,
5787                    message: Some(format!(
5788                        "workflow result was not terminal within {:?}",
5789                        options.timeout
5790                    )),
5791                    exception: None,
5792                    raw: description.raw_value(),
5793                }));
5794            }
5795
5796            tokio::time::sleep(options.poll_interval).await;
5797        }
5798    }
5799}
5800
5801#[derive(Clone, Copy, Debug)]
5802pub struct WorkflowResultOptions {
5803    pub poll_interval: Duration,
5804    pub timeout: Duration,
5805}
5806
5807impl Default for WorkflowResultOptions {
5808    fn default() -> Self {
5809        Self {
5810            poll_interval: Duration::from_millis(500),
5811            timeout: Duration::from_secs(30),
5812        }
5813    }
5814}
5815
5816#[derive(Clone, Debug, Deserialize)]
5817pub struct WorkflowDescription {
5818    pub workflow_id: Option<String>,
5819    pub run_id: Option<String>,
5820    pub workflow_type: Option<String>,
5821    pub status: Option<String>,
5822    #[serde(default)]
5823    pub closed_reason: Option<String>,
5824    #[serde(default)]
5825    pub error: Option<String>,
5826    #[serde(default)]
5827    pub failure: Option<Value>,
5828    #[serde(default)]
5829    pub exception: Option<Value>,
5830    #[serde(default)]
5831    pub failures: Vec<Value>,
5832    #[serde(default)]
5833    pub output: Option<Value>,
5834    #[serde(default)]
5835    pub output_envelope: Option<Value>,
5836    #[serde(skip)]
5837    pub output_avro_value: Option<AvroValue>,
5838    #[serde(flatten)]
5839    pub raw: HashMap<String, Value>,
5840}
5841
5842/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5843#[derive(Clone, Debug, Deserialize)]
5844pub struct WorkflowStreamDescription {
5845    pub stream_name: String,
5846    pub status: String,
5847    pub last_offset: i64,
5848    pub total_items: u64,
5849    pub pending_items: u64,
5850    #[serde(default)]
5851    pub opened_at: Option<String>,
5852    #[serde(default)]
5853    pub last_appended_at: Option<String>,
5854    #[serde(default)]
5855    pub closed_at: Option<String>,
5856    #[serde(default)]
5857    pub error_reason: Option<String>,
5858    #[serde(default)]
5859    pub retention_seconds: Option<u64>,
5860    #[serde(flatten)]
5861    pub raw: HashMap<String, Value>,
5862}
5863
5864impl WorkflowStreamDescription {
5865    pub fn is_terminal(&self) -> bool {
5866        matches!(self.status.as_str(), "closed" | "errored")
5867    }
5868}
5869
5870/// One item for direct or replay-safe append.
5871#[derive(Clone, Debug, Default)]
5872pub struct WorkflowStreamAppendItem {
5873    pub payload_envelope: Option<Value>,
5874    pub payload_reference: Option<String>,
5875    pub item_type: Option<String>,
5876    pub content_type: Option<String>,
5877    pub idempotency_key: Option<String>,
5878}
5879
5880impl WorkflowStreamAppendItem {
5881    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5882    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5883        let value = AvroValue::from_serialize(&payload)?;
5884        Ok(Self {
5885            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5886            ..Self::default()
5887        })
5888    }
5889
5890    /// Preserve an external payload URI as an opaque service-contract reference.
5891    pub fn from_reference(reference: impl Into<String>) -> Self {
5892        Self {
5893            payload_reference: Some(reference.into()),
5894            ..Self::default()
5895        }
5896    }
5897
5898    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5899        self.item_type = Some(item_type.into());
5900        self
5901    }
5902
5903    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5904        self.content_type = Some(content_type.into());
5905        self
5906    }
5907
5908    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5909        self.idempotency_key = Some(idempotency_key.into());
5910        self
5911    }
5912
5913    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5914        let mut item = serde_json::Map::new();
5915        if let Some(payload) = &self.payload_envelope {
5916            item.insert("payload".to_string(), payload.clone());
5917            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5918        }
5919        if let Some(reference) = &self.payload_reference {
5920            item.insert("payload_reference".to_string(), json!(reference));
5921        }
5922        if let Some(item_type) = &self.item_type {
5923            item.insert("item_type".to_string(), json!(item_type));
5924        }
5925        if let Some(content_type) = &self.content_type {
5926            item.insert("content_type".to_string(), json!(content_type));
5927        }
5928        if let Some(key) = derived_idempotency_key
5929            .as_ref()
5930            .or(self.idempotency_key.as_ref())
5931        {
5932            item.insert("idempotency_key".to_string(), json!(key));
5933        }
5934        Value::Object(item)
5935    }
5936}
5937
5938/// One durable item at its stable zero-based offset.
5939#[derive(Clone, Debug)]
5940pub struct WorkflowStreamItem {
5941    pub offset: u64,
5942    pub payload: Option<Value>,
5943    pub payload_envelope: Option<Value>,
5944    pub payload_reference: Option<String>,
5945    pub payload_codec: Option<String>,
5946    pub idempotency_key: Option<String>,
5947    pub item_type: Option<String>,
5948    pub content_type: Option<String>,
5949    pub origin: Option<String>,
5950    pub origin_reference: Option<String>,
5951    pub emitted_at: Option<String>,
5952    pub raw: Value,
5953}
5954
5955/// One bounded at-least-once subscription page.
5956#[derive(Clone, Debug)]
5957pub struct WorkflowStreamPage {
5958    pub stream: WorkflowStreamDescription,
5959    pub items: Vec<WorkflowStreamItem>,
5960    pub next_offset: u64,
5961    pub terminal: bool,
5962}
5963
5964/// Durable acceptance and deduplication outcome for an append request.
5965#[derive(Clone, Debug)]
5966pub struct WorkflowStreamAppendResult {
5967    pub stream: WorkflowStreamDescription,
5968    pub accepted_offsets: Vec<u64>,
5969    pub accepted: u64,
5970    pub deduped: u64,
5971}
5972
5973#[derive(Deserialize)]
5974struct WorkflowStreamListResponse {
5975    #[serde(default)]
5976    streams: Vec<WorkflowStreamDescription>,
5977}
5978
5979#[derive(Deserialize)]
5980struct WorkflowStreamDescriptionResponse {
5981    stream: WorkflowStreamDescription,
5982}
5983
5984#[derive(Deserialize)]
5985struct WorkflowStreamPageResponse {
5986    stream: WorkflowStreamDescription,
5987    #[serde(default)]
5988    items: Vec<Value>,
5989    next_offset: u64,
5990    terminal: bool,
5991}
5992
5993#[derive(Deserialize)]
5994struct WorkflowStreamAppendResponse {
5995    stream: WorkflowStreamDescription,
5996    #[serde(default)]
5997    accepted_offsets: Vec<u64>,
5998    accepted: u64,
5999    deduped: u64,
6000}
6001
6002impl WorkflowDescription {
6003    pub fn is_completed(&self) -> bool {
6004        matches!(self.status.as_deref(), Some("completed" | "Completed"))
6005    }
6006
6007    pub fn is_terminal(&self) -> bool {
6008        matches!(
6009            self.status.as_deref(),
6010            Some(
6011                "completed"
6012                    | "Completed"
6013                    | "failed"
6014                    | "Failed"
6015                    | "cancelled"
6016                    | "Cancelled"
6017                    | "terminated"
6018                    | "Terminated"
6019                    | "timed_out"
6020                    | "TimedOut",
6021            )
6022        )
6023    }
6024
6025    fn decode_payloads(&mut self) -> Result<()> {
6026        if let Some(envelope) = &self.output_envelope {
6027            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
6028            self.output = Some(value.clone().into_json()?);
6029            self.output_avro_value = Some(value);
6030        }
6031
6032        Ok(())
6033    }
6034
6035    fn raw_value(&self) -> Value {
6036        let mut data = self.raw.clone();
6037        data.insert(
6038            "workflow_id".to_string(),
6039            self.workflow_id
6040                .clone()
6041                .map(Value::String)
6042                .unwrap_or(Value::Null),
6043        );
6044        data.insert(
6045            "run_id".to_string(),
6046            self.run_id
6047                .clone()
6048                .map(Value::String)
6049                .unwrap_or(Value::Null),
6050        );
6051        data.insert(
6052            "workflow_type".to_string(),
6053            self.workflow_type
6054                .clone()
6055                .map(Value::String)
6056                .unwrap_or(Value::Null),
6057        );
6058        data.insert(
6059            "status".to_string(),
6060            self.status
6061                .clone()
6062                .map(Value::String)
6063                .unwrap_or(Value::Null),
6064        );
6065        data.insert(
6066            "closed_reason".to_string(),
6067            self.closed_reason
6068                .clone()
6069                .map(Value::String)
6070                .unwrap_or(Value::Null),
6071        );
6072        if let Some(failure) = &self.failure {
6073            data.insert("failure".to_string(), failure.clone());
6074        }
6075        if let Some(exception) = &self.exception {
6076            data.insert("exception".to_string(), exception.clone());
6077        }
6078        Value::Object(data.into_iter().collect())
6079    }
6080}
6081
6082fn workflow_terminal_outcome(
6083    description: &WorkflowDescription,
6084    workflow_id: &str,
6085    run_id: Option<&str>,
6086) -> WorkflowTerminalOutcome {
6087    let terminal_kind = description
6088        .closed_reason
6089        .as_deref()
6090        .or(description.status.as_deref())
6091        .unwrap_or("failed")
6092        .to_ascii_lowercase();
6093    let kind = match terminal_kind.as_str() {
6094        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6095        "terminated" => WorkflowTerminalKind::Terminated,
6096        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6097        _ => WorkflowTerminalKind::Failed,
6098    };
6099    let default_reason = match kind {
6100        WorkflowTerminalKind::Failed => "workflow_failed",
6101        WorkflowTerminalKind::Cancelled => "cancelled",
6102        WorkflowTerminalKind::Terminated => "terminated",
6103        WorkflowTerminalKind::TimedOut => "timed_out",
6104    };
6105    let failure = description
6106        .failure
6107        .as_ref()
6108        .filter(|value| value.is_object());
6109    let nested_failure = failure
6110        .and_then(|value| value.get("failures"))
6111        .and_then(Value::as_array)
6112        .and_then(|failures| failures.last())
6113        .or_else(|| description.failures.last());
6114    let exception = description
6115        .exception
6116        .clone()
6117        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6118        .or_else(|| {
6119            nested_failure
6120                .and_then(|value| value.get("exception_payload"))
6121                .cloned()
6122        });
6123    let string_field = |name: &str| {
6124        failure
6125            .and_then(|value| value.get(name))
6126            .and_then(Value::as_str)
6127            .or_else(|| {
6128                nested_failure
6129                    .and_then(|value| value.get(name))
6130                    .and_then(Value::as_str)
6131            })
6132            .map(str::to_string)
6133    };
6134    let exception_field = |name: &str| {
6135        exception
6136            .as_ref()
6137            .and_then(|value| value.get(name))
6138            .and_then(Value::as_str)
6139            .map(str::to_string)
6140    };
6141    let message = description
6142        .error
6143        .clone()
6144        .or_else(|| string_field("message"))
6145        .or_else(|| exception_field("message"));
6146    let reason = description
6147        .raw
6148        .get("reason")
6149        .and_then(Value::as_str)
6150        .map(str::to_string)
6151        .or_else(|| {
6152            failure
6153                .and_then(|value| value.get("reason"))
6154                .and_then(Value::as_str)
6155                .map(str::to_string)
6156        })
6157        .or_else(|| description.closed_reason.clone())
6158        .unwrap_or_else(|| default_reason.to_string());
6159    let failure_id = string_field("failure_id").or_else(|| {
6160        nested_failure
6161            .and_then(|value| value.get("id"))
6162            .and_then(Value::as_str)
6163            .map(str::to_string)
6164    });
6165
6166    WorkflowTerminalOutcome {
6167        kind,
6168        workflow_id: description
6169            .workflow_id
6170            .clone()
6171            .unwrap_or_else(|| workflow_id.to_string()),
6172        run_id: description
6173            .run_id
6174            .clone()
6175            .or_else(|| run_id.map(str::to_string)),
6176        reason,
6177        failure_category: string_field("failure_category")
6178            .or_else(|| Some(default_reason.to_string())),
6179        failure_id,
6180        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6181        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6182        non_retryable: failure
6183            .and_then(|value| value.get("non_retryable"))
6184            .and_then(Value::as_bool)
6185            .or_else(|| {
6186                nested_failure
6187                    .and_then(|value| value.get("non_retryable"))
6188                    .and_then(Value::as_bool)
6189            }),
6190        message,
6191        exception,
6192        raw: description.raw_value(),
6193    }
6194}
6195
6196#[derive(Clone, Debug, Deserialize)]
6197pub struct RegisterWorkerResponse {
6198    pub worker_id: String,
6199    pub registered: bool,
6200    #[serde(default)]
6201    pub heartbeat_interval_seconds: Option<u64>,
6202    #[serde(default)]
6203    pub protocol_version: Option<String>,
6204    #[serde(default)]
6205    pub server_capabilities: Option<Value>,
6206}
6207
6208/// Result of gracefully removing a worker-plane registration.
6209#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6210pub struct WorkerDeregistrationEnvelope {
6211    pub worker_id: String,
6212    pub outcome: String,
6213    pub recovered_workflow_task_count: u64,
6214}
6215
6216#[derive(Clone, Debug, Deserialize)]
6217pub struct PollWorkflowTaskResponse {
6218    #[serde(default)]
6219    pub task: Option<WorkflowTask>,
6220    #[serde(default)]
6221    pub poll_status: Option<String>,
6222    #[serde(default)]
6223    pub reason: Option<String>,
6224    #[serde(default)]
6225    pub protocol_version: Option<String>,
6226    #[serde(default)]
6227    pub server_capabilities: Option<Value>,
6228}
6229
6230impl PollWorkflowTaskResponse {
6231    /// Classify this response without parsing server display text.
6232    pub fn outcome(&self) -> WorkerPollOutcome {
6233        worker_poll_outcome(
6234            self.task.is_some(),
6235            self.poll_status.as_deref(),
6236            self.reason.as_deref(),
6237        )
6238    }
6239}
6240
6241fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6242    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6243        return false;
6244    };
6245    let supported = capabilities
6246        .get("workflow_memo_updates")
6247        .and_then(Value::as_object)
6248        .and_then(|memo| memo.get("supported"))
6249        .and_then(Value::as_bool)
6250        == Some(true);
6251    let command_advertised = capabilities
6252        .get("supported_workflow_task_commands")
6253        .and_then(Value::as_array)
6254        .is_some_and(|commands| {
6255            commands
6256                .iter()
6257                .any(|command| command.as_str() == Some("upsert_memo"))
6258        });
6259    supported && command_advertised
6260}
6261
6262fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6263    commands
6264        .iter()
6265        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6266}
6267
6268#[derive(Clone, Debug, Deserialize)]
6269pub struct PollActivityTaskResponse {
6270    #[serde(default)]
6271    pub task: Option<ActivityTask>,
6272    #[serde(default)]
6273    pub poll_status: Option<String>,
6274    #[serde(default)]
6275    pub reason: Option<String>,
6276}
6277
6278impl PollActivityTaskResponse {
6279    /// Classify this response without parsing server display text.
6280    pub fn outcome(&self) -> WorkerPollOutcome {
6281        worker_poll_outcome(
6282            self.task.is_some(),
6283            self.poll_status.as_deref(),
6284            self.reason.as_deref(),
6285        )
6286    }
6287}
6288
6289#[derive(Clone, Debug, Deserialize)]
6290pub struct PollQueryTaskResponse {
6291    #[serde(default)]
6292    pub task: Option<QueryTask>,
6293    #[serde(default)]
6294    pub poll_status: Option<String>,
6295    #[serde(default)]
6296    pub reason: Option<String>,
6297}
6298
6299impl PollQueryTaskResponse {
6300    /// Classify this response without parsing server display text.
6301    pub fn outcome(&self) -> WorkerPollOutcome {
6302        worker_poll_outcome(
6303            self.task.is_some(),
6304            self.poll_status.as_deref(),
6305            self.reason.as_deref(),
6306        )
6307    }
6308}
6309
6310/// Stable classification for worker poll responses.
6311#[derive(Clone, Debug, PartialEq, Eq)]
6312pub enum WorkerPollOutcome {
6313    /// A task was leased and is available on the response.
6314    Task,
6315    /// No task was leased, but the worker should continue polling.
6316    Idle {
6317        poll_status: Option<String>,
6318        reason: Option<String>,
6319    },
6320    /// The server asked this worker to stop claiming new work.
6321    Stop {
6322        poll_status: Option<String>,
6323        reason: Option<String>,
6324    },
6325}
6326
6327impl WorkerPollOutcome {
6328    pub fn should_stop(&self) -> bool {
6329        matches!(self, Self::Stop { .. })
6330    }
6331}
6332
6333fn worker_poll_outcome(
6334    has_task: bool,
6335    poll_status: Option<&str>,
6336    reason: Option<&str>,
6337) -> WorkerPollOutcome {
6338    if worker_poll_is_stop(poll_status, reason) {
6339        return WorkerPollOutcome::Stop {
6340            poll_status: poll_status.map(str::to_string),
6341            reason: reason.map(str::to_string),
6342        };
6343    }
6344
6345    if has_task {
6346        WorkerPollOutcome::Task
6347    } else {
6348        WorkerPollOutcome::Idle {
6349            poll_status: poll_status.map(str::to_string),
6350            reason: reason.map(str::to_string),
6351        }
6352    }
6353}
6354
6355/// An ephemeral server-routed query task.
6356#[derive(Clone, Debug, Deserialize)]
6357pub struct QueryTask {
6358    pub query_task_id: String,
6359    #[serde(default = "default_workflow_task_attempt")]
6360    pub query_task_attempt: u64,
6361    #[serde(default)]
6362    pub lease_owner: Option<String>,
6363    #[serde(default)]
6364    pub workflow_id: Option<String>,
6365    #[serde(default)]
6366    pub run_id: Option<String>,
6367    pub workflow_type: String,
6368    pub query_name: String,
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 workflow_arguments: Option<Value>,
6376    #[serde(default)]
6377    pub query_arguments: Option<Value>,
6378    #[serde(default)]
6379    pub history_events: Vec<HistoryEvent>,
6380    #[serde(default)]
6381    pub history_export: Option<Value>,
6382    #[serde(default)]
6383    pub run_status: Option<String>,
6384}
6385
6386#[derive(Clone, Debug, Deserialize)]
6387pub struct WorkflowTask {
6388    pub task_id: String,
6389    #[serde(default)]
6390    pub workflow_command_id: Option<String>,
6391    #[serde(default)]
6392    pub workflow_id: Option<String>,
6393    #[serde(default)]
6394    pub run_id: Option<String>,
6395    pub workflow_type: String,
6396    #[serde(default)]
6397    pub cancel_requested: bool,
6398    #[serde(
6399        default = "missing_task_payload_codec",
6400        deserialize_with = "deserialize_task_payload_codec"
6401    )]
6402    pub payload_codec: String,
6403    #[serde(default)]
6404    pub arguments: Option<Value>,
6405    #[serde(default)]
6406    pub history_events: Vec<HistoryEvent>,
6407    #[serde(default)]
6408    pub total_history_events: Option<u64>,
6409    #[serde(default)]
6410    pub history_size_bytes: Option<u64>,
6411    #[serde(default)]
6412    pub continue_as_new_recommended: Option<bool>,
6413    #[serde(default)]
6414    pub history_budget_pressure: Option<String>,
6415    #[serde(default)]
6416    pub next_history_page_token: Option<String>,
6417    #[serde(default = "default_workflow_task_attempt")]
6418    pub workflow_task_attempt: u64,
6419    #[serde(default)]
6420    pub workflow_signal_id: Option<String>,
6421    #[serde(default)]
6422    pub signal_name: Option<String>,
6423    #[serde(default)]
6424    pub signal_arguments: Option<Value>,
6425    #[serde(default)]
6426    pub workflow_update_id: Option<String>,
6427    #[serde(default)]
6428    pub update_name: Option<String>,
6429    #[serde(default)]
6430    pub lease_owner: Option<String>,
6431}
6432
6433impl WorkflowTask {
6434    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6435        self.history_events.extend(page.history_events);
6436
6437        if page.total_history_events.is_some() {
6438            self.total_history_events = page.total_history_events;
6439        }
6440
6441        self.next_history_page_token = page
6442            .next_history_page_token
6443            .filter(|token| !token.is_empty());
6444    }
6445}
6446
6447#[derive(Clone, Debug, Deserialize)]
6448struct WorkflowTaskHistoryPage {
6449    #[serde(default)]
6450    history_events: Vec<HistoryEvent>,
6451    #[serde(default)]
6452    total_history_events: Option<u64>,
6453    #[serde(default)]
6454    next_history_page_token: Option<String>,
6455}
6456
6457#[derive(Clone, Debug, Deserialize)]
6458pub struct ActivityTask {
6459    pub task_id: String,
6460    #[serde(default)]
6461    pub activity_attempt_id: Option<String>,
6462    #[serde(default)]
6463    pub attempt_id: Option<String>,
6464    pub activity_type: String,
6465    #[serde(
6466        default = "missing_task_payload_codec",
6467        deserialize_with = "deserialize_task_payload_codec"
6468    )]
6469    pub payload_codec: String,
6470    #[serde(default)]
6471    pub arguments: Option<Value>,
6472    #[serde(default = "default_attempt_number")]
6473    pub attempt_number: u64,
6474    #[serde(default)]
6475    pub lease_owner: Option<String>,
6476}
6477
6478#[derive(Clone, Debug, Serialize, Deserialize)]
6479pub struct HistoryEvent {
6480    #[serde(alias = "type")]
6481    pub event_type: String,
6482    #[serde(default)]
6483    pub payload: Value,
6484    #[serde(flatten)]
6485    pub raw: HashMap<String, Value>,
6486}
6487
6488/// One decoded signal in the committed workflow-history snapshot.
6489#[derive(Clone, Debug, PartialEq)]
6490pub struct QuerySignal {
6491    pub id: Option<String>,
6492    pub name: String,
6493    pub arguments: Vec<Value>,
6494    avro_arguments: Vec<AvroValue>,
6495    pub workflow_sequence: Option<u64>,
6496}
6497
6498impl QuerySignal {
6499    /// Lossless fixed Avro Value arguments for this committed signal.
6500    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6501        &self.avro_arguments
6502    }
6503}
6504
6505/// Immutable state supplied to a registered query handler.
6506///
6507/// This context intentionally exposes no activity, signal-wait, or command
6508/// APIs. Query handlers inspect committed history and return a value; query
6509/// completion does not append an event or advance deterministic execution.
6510#[derive(Clone, Debug)]
6511pub struct QueryContext {
6512    pub workflow_id: Option<String>,
6513    pub run_id: Option<String>,
6514    pub workflow_type: String,
6515    pub run_status: Option<String>,
6516    workflow_input: Value,
6517    workflow_input_avro_value: AvroValue,
6518    history_events: Arc<Vec<HistoryEvent>>,
6519    signal_events: Arc<Vec<QuerySignal>>,
6520}
6521
6522impl QueryContext {
6523    /// The normalized argument list used to start the workflow.
6524    pub fn workflow_input(&self) -> &Value {
6525        &self.workflow_input
6526    }
6527
6528    /// The lossless fixed Avro Value argument list used to start the workflow.
6529    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6530        &self.workflow_input_avro_value
6531    }
6532
6533    /// The immutable committed history used for this query snapshot.
6534    pub fn history_events(&self) -> &[HistoryEvent] {
6535        self.history_events.as_slice()
6536    }
6537
6538    /// All decoded signals in committed workflow order.
6539    pub fn signal_events(&self) -> &[QuerySignal] {
6540        self.signal_events.as_slice()
6541    }
6542
6543    /// Decoded argument lists for each committed signal with `signal_name`.
6544    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6545        self.signal_events
6546            .iter()
6547            .filter(|signal| signal.name == signal_name)
6548            .map(|signal| signal.arguments.clone())
6549            .collect()
6550    }
6551
6552    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6553    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6554        self.signal_events
6555            .iter()
6556            .filter(|signal| signal.name == signal_name)
6557            .map(|signal| signal.avro_arguments.clone())
6558            .collect()
6559    }
6560}
6561
6562#[derive(Clone, Debug, Deserialize)]
6563pub struct ActivityHeartbeatResponse {
6564    #[serde(default)]
6565    pub cancel_requested: bool,
6566    #[serde(default)]
6567    pub heartbeat_recorded: bool,
6568    #[serde(default)]
6569    pub can_continue: Option<bool>,
6570    #[serde(default)]
6571    pub reason: Option<String>,
6572    #[serde(default)]
6573    pub run_closed_reason: Option<String>,
6574    #[serde(default)]
6575    pub run_closed_at: Option<String>,
6576    #[serde(default)]
6577    pub lease_expires_at: Option<String>,
6578    #[serde(default)]
6579    pub last_heartbeat_at: Option<String>,
6580}
6581
6582impl ActivityHeartbeatResponse {
6583    /// Whether the activity should stop instead of attempting completion.
6584    pub fn should_stop(&self) -> bool {
6585        self.cancel_requested || self.can_continue == Some(false)
6586    }
6587}
6588
6589fn missing_task_payload_codec() -> String {
6590    MISSING_TASK_PAYLOAD_CODEC.to_string()
6591}
6592
6593fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6594where
6595    D: Deserializer<'de>,
6596{
6597    Ok(match Value::deserialize(deserializer)? {
6598        Value::String(codec) => codec,
6599        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6600        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6601    })
6602}
6603
6604fn default_workflow_task_attempt() -> u64 {
6605    1
6606}
6607
6608fn default_attempt_number() -> u64 {
6609    1
6610}
6611
6612type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6613type WorkflowHandler =
6614    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<WorkflowFuture> + Send + Sync>;
6615type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6616type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6617type ReplayedWorkflowHandler =
6618    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<ReplayedWorkflowInvocation> + Send + Sync>;
6619type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6620type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6621type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6622type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6623type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6624type ReplayedQueryHandler = Arc<
6625    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6626        + Send
6627        + Sync,
6628>;
6629type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6630
6631struct ReplayedWorkflowInvocation {
6632    future: WorkflowFuture,
6633    snapshot: WorkflowStateSnapshot,
6634}
6635
6636#[derive(Clone)]
6637struct RegisteredWorkflow {
6638    execute: WorkflowHandler,
6639    replay: Option<ReplayedWorkflowHandler>,
6640    state_type: Option<TypeId>,
6641    definition_fingerprint: Option<String>,
6642}
6643
6644fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
6645    names
6646        .iter()
6647        .map(|name| {
6648            json!({
6649                "name": name,
6650                "parameters": [{
6651                    "name": "args",
6652                    "position": 0,
6653                    "required": false,
6654                    "variadic": true,
6655                    "type": null,
6656                    "allows_null": true,
6657                    "default_available": false,
6658                    "default": null,
6659                }],
6660            })
6661        })
6662        .collect()
6663}
6664
6665#[derive(Debug)]
6666struct WorkflowTaskDecision {
6667    commands: Vec<Value>,
6668    message_stream_cursors: Vec<Value>,
6669    message_stream_waits: Vec<Value>,
6670    cancellation_delivery: Option<CancellationDelivery>,
6671    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6672    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6673}
6674
6675enum PreparedWorkflowTask {
6676    Decision(WorkflowTaskDecision),
6677    Execution {
6678        task: WorkflowTask,
6679        context: WorkflowContext,
6680        future: WorkflowFuture,
6681    },
6682}
6683
6684impl WorkflowTaskDecision {
6685    fn without_message_streams(commands: Vec<Value>) -> Self {
6686        Self {
6687            commands,
6688            message_stream_cursors: Vec::new(),
6689            message_stream_waits: Vec::new(),
6690            cancellation_delivery: None,
6691            cancellation_scope_opening: None,
6692            cancellation_scope_delivery: None,
6693        }
6694    }
6695}
6696
6697#[derive(Clone)]
6698enum RegisteredQuery {
6699    Snapshot(QueryHandler),
6700    Replayed {
6701        state_type: TypeId,
6702        handler: ReplayedQueryHandler,
6703    },
6704}
6705
6706#[derive(Clone, Debug)]
6707pub struct WorkerHeartbeatObservation {
6708    pub worker_id: String,
6709    pub task_queue: String,
6710    pub acknowledged_at_unix_millis: u64,
6711    pub acknowledgement: Value,
6712}
6713
6714/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6715///
6716/// Expected empty long polls and explicit Server capacity backpressure are
6717/// normal worker states. Capacity backpressure honors the advertised retry
6718/// delay without consuming this retry budget. Other transport failures,
6719/// retryable HTTP 408/429 responses, and server errors are retried with capped
6720/// exponential backoff. Authentication, protocol, codec, and handler failures
6721/// are never retried by the worker.
6722/// Explicit storage admission pauses also preserve the already-serialized worker
6723/// request without consuming this budget or rerunning its handler. The delay is
6724/// capped by `max_backoff`, except an explicit completion deferral must honor
6725/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
6726/// completion retries remain bounded by the original cleanup deadline.
6727/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6728/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6729/// and `max_retries = 0` disables ordinary retries in either mode.
6730#[derive(Clone, Copy, Debug)]
6731pub struct WorkerRetryPolicy {
6732    /// Number of retries after the initial request fails.
6733    pub max_retries: usize,
6734    /// Delay before the first retry.
6735    pub initial_backoff: Duration,
6736    /// Maximum delay between retries.
6737    pub max_backoff: Duration,
6738}
6739
6740impl Default for WorkerRetryPolicy {
6741    fn default() -> Self {
6742        Self {
6743            max_retries: 5,
6744            initial_backoff: Duration::from_millis(100),
6745            max_backoff: Duration::from_secs(5),
6746        }
6747    }
6748}
6749
6750#[derive(Clone, Debug)]
6751struct WorkerStorageAdmission {
6752    policy: WorkerRetryPolicy,
6753    stop: Arc<AtomicBool>,
6754    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
6755}
6756
6757struct StopWorkerOnDrop(Arc<AtomicBool>);
6758
6759impl Drop for StopWorkerOnDrop {
6760    fn drop(&mut self) {
6761        self.0.store(true, Ordering::SeqCst);
6762    }
6763}
6764
6765async fn wait_for_worker_stop(stop: &AtomicBool) {
6766    while !stop.load(Ordering::SeqCst) {
6767        tokio::time::sleep(Duration::from_millis(100)).await;
6768    }
6769}
6770
6771#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6772enum ManagedPollOutcome {
6773    Idle,
6774    Handled,
6775    Stop,
6776}
6777
6778#[derive(Clone)]
6779pub struct Worker {
6780    client: Client,
6781    worker_id: String,
6782    task_queue: String,
6783    workflows: HashMap<String, RegisteredWorkflow>,
6784    activities: HashMap<String, ActivityHandler>,
6785    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6786    signals: HashMap<String, Vec<String>>,
6787    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6788    registration_definitions:
6789        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
6790    registration_error: Option<DuplicateRegistrationError>,
6791    max_concurrent_workflow_tasks: usize,
6792    max_concurrent_activity_tasks: usize,
6793    poll_timeout: Duration,
6794    heartbeat_interval: Duration,
6795    retry_policy: WorkerRetryPolicy,
6796    recover_transient_outages: bool,
6797    run_stop: Option<Arc<AtomicBool>>,
6798    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6799    cooperative_cancellation_enabled: bool,
6800    allow_cancellation_scope_authoring: bool,
6801    allow_cancellation_scope_delivery: bool,
6802    cooperative_registration_confirmed: Arc<AtomicBool>,
6803    local_registration_confirmed: Arc<AtomicBool>,
6804    session_registration_confirmed: Arc<AtomicBool>,
6805    sticky_registration_confirmed: Arc<AtomicBool>,
6806    require_query_task_authority: bool,
6807    query_authority_confirmed: Arc<AtomicBool>,
6808    resource_capabilities: Vec<String>,
6809    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6810}
6811
6812impl Worker {
6813    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6814        Self {
6815            client,
6816            worker_id: default_worker_id(),
6817            task_queue: task_queue.into(),
6818            workflows: HashMap::new(),
6819            activities: HashMap::new(),
6820            queries: HashMap::new(),
6821            signals: HashMap::new(),
6822            updates: HashMap::new(),
6823            registration_definitions: HashMap::new(),
6824            registration_error: None,
6825            max_concurrent_workflow_tasks: 10,
6826            max_concurrent_activity_tasks: 10,
6827            poll_timeout: Duration::from_secs(30),
6828            heartbeat_interval: Duration::from_secs(60),
6829            retry_policy: WorkerRetryPolicy::default(),
6830            recover_transient_outages: false,
6831            run_stop: None,
6832            heartbeat_observer: None,
6833            cooperative_cancellation_enabled: false,
6834            allow_cancellation_scope_authoring: false,
6835            allow_cancellation_scope_delivery: false,
6836            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6837            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6838            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6839            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
6840            require_query_task_authority: false,
6841            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
6842            resource_capabilities: Vec::new(),
6843            sessions: Arc::new(Mutex::new(HashMap::new())),
6844        }
6845    }
6846
6847    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6848        self.worker_id = worker_id.into();
6849        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6850        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6851        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6852        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
6853        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
6854        self.client.reset_sticky_cache();
6855        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6856        self
6857    }
6858
6859    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6860        self.poll_timeout = timeout;
6861        self
6862    }
6863
6864    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6865        self.heartbeat_interval = interval;
6866        self
6867    }
6868
6869    /// Require original query timing and non-renewing runtime observation.
6870    ///
6871    /// Registration refuses before creating a Worker unless protocol 1.20 and
6872    /// the runtime's `query_task_authority` capability are available. By default,
6873    /// older Servers retain their weaker, disclosed local-timing behavior.
6874    pub fn require_query_task_authority(mut self, required: bool) -> Self {
6875        self.require_query_task_authority = required;
6876        self
6877    }
6878
6879    /// Explicitly enable inline local activities in this workflow worker.
6880    ///
6881    /// The worker advertises the capability to Server only when enabled.
6882    /// These callbacks must yield to Tokio and have idempotent side effects.
6883    /// Cooperative prepared local supervision is a separate capability.
6884    pub fn local_activities(mut self, enabled: bool) -> Self {
6885        self.client.local_activities_enabled = enabled;
6886        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6887        self
6888    }
6889
6890    /// Opt in to separate cooperative workflow cancellation requests.
6891    ///
6892    /// Registration requires the Server to acknowledge this exact worker,
6893    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6894    /// processing uses canonical delivery and activity ownership fences.
6895    /// Existing terminal cancel and terminate operations remain terminal.
6896    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
6897    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6898    /// and [`Worker::run_until`] register automatically.
6899    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6900        self.cooperative_cancellation_enabled = enabled;
6901        self.client.cooperative_worker_protocol = enabled;
6902        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6903        self
6904    }
6905
6906    /// Enable candidate scope authoring without advertising scoped execution.
6907    #[doc(hidden)]
6908    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6909        self.allow_cancellation_scope_authoring = enabled;
6910        self
6911    }
6912
6913    /// Enable the candidate scoped call consumer with canonical authoring.
6914    #[doc(hidden)]
6915    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6916        self.allow_cancellation_scope_delivery = enabled;
6917        self
6918    }
6919
6920    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6921    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6922        self.retry_policy = policy;
6923        self
6924    }
6925
6926    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6927    ///
6928    /// Retries preserve the poll request identity and use capped exponential
6929    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6930    /// An in-flight poll is allowed to finish so leased work is not discarded.
6931    /// Authentication, protocol, codec, handler and task settlement failures
6932    /// remain errors. Registration and deregistration are not retried here.
6933    ///
6934    /// The default is disabled, preserving the bounded retry contract.
6935    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6936    /// even when this option is enabled.
6937    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6938        self.recover_transient_outages = enabled;
6939        self
6940    }
6941
6942    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6943    where
6944        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6945    {
6946        self.heartbeat_observer = Some(Arc::new(observer));
6947        self
6948    }
6949
6950    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6951        self.max_concurrent_workflow_tasks = count.max(1);
6952        self
6953    }
6954
6955    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6956        self.max_concurrent_activity_tasks = count.max(1);
6957        self
6958    }
6959
6960    /// Validate local handler admission without making a Server request.
6961    ///
6962    /// Registration methods retain their existing signatures. A duplicate keeps
6963    /// the original handler and makes this Worker invalid, including its clones.
6964    /// `register`, `run`, `run_until` and `run_once` enforce this check before
6965    /// any network request. Build a new Worker to correct an invalid configuration.
6966    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
6967        match &self.registration_error {
6968            Some(error) => Err(error.clone()),
6969            None => Ok(()),
6970        }
6971    }
6972
6973    #[track_caller]
6974    fn admit_registration<F>(
6975        &mut self,
6976        handler_kind: RegistrationKind,
6977        workflow_type: Option<&str>,
6978        handler_name: &str,
6979        method: &'static str,
6980    ) -> bool {
6981        let location = std::panic::Location::caller();
6982        let definition = HandlerRegistration {
6983            method,
6984            handler_type: type_name::<F>(),
6985            file: location.file(),
6986            line: location.line(),
6987            column: location.column(),
6988        };
6989        let key = (
6990            handler_kind,
6991            workflow_type.map(str::to_owned),
6992            handler_name.to_owned(),
6993        );
6994        if let Some(first_definition) = self.registration_definitions.get(&key) {
6995            if self.registration_error.is_none() {
6996                self.registration_error = Some(DuplicateRegistrationError {
6997                    handler_kind,
6998                    workflow_type: key.1.clone(),
6999                    handler_name: key.2.clone(),
7000                    first_definition: first_definition.clone(),
7001                    second_definition: definition,
7002                });
7003            }
7004            return false;
7005        }
7006        self.registration_definitions.insert(key, definition);
7007        true
7008    }
7009
7010    /// Register a workflow handler.
7011    ///
7012    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
7013    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
7014    /// while acquiring or decoding a worker task remain worker-operation
7015    /// failures and do not get converted into workflow outcomes.
7016    #[track_caller]
7017    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
7018    where
7019        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
7020        Fut: Future<Output = Result<Value>> + Send + 'static,
7021    {
7022        let workflow_type = workflow_type.into();
7023        if !self.admit_registration::<F>(
7024            RegistrationKind::Workflow,
7025            None,
7026            &workflow_type,
7027            "register_workflow",
7028        ) {
7029            return;
7030        }
7031        let handler = Arc::new(handler);
7032        self.workflows.insert(
7033            workflow_type,
7034            RegisteredWorkflow {
7035                execute: Arc::new(move |ctx, input| {
7036                    let handler = Arc::clone(&handler);
7037                    Ok(Box::pin(async move {
7038                        let result = handler(ctx, input.into_json()?).await?;
7039                        AvroValue::from_serialize(&result)
7040                    }))
7041                }),
7042                replay: None,
7043                state_type: None,
7044                definition_fingerprint: None,
7045            },
7046        );
7047    }
7048
7049    /// Register a workflow with one Serde request value and a Serde result.
7050    ///
7051    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
7052    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
7053    /// workflow-specific schema. A task must contain zero arguments for a unit
7054    /// request or exactly one argument for every other request type.
7055    ///
7056    /// See the runnable
7057    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
7058    /// for typed workflow and activity contracts with retry and timeout policy.
7059    #[track_caller]
7060    pub fn register_typed_workflow<I, O, F, Fut>(
7061        &mut self,
7062        workflow_type: impl Into<String>,
7063        handler: F,
7064    ) where
7065        I: DeserializeOwned + Send + 'static,
7066        O: Serialize + Send + 'static,
7067        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
7068        Fut: Future<Output = Result<O>> + Send + 'static,
7069    {
7070        let workflow_type = workflow_type.into();
7071        if !self.admit_registration::<F>(
7072            RegistrationKind::Workflow,
7073            None,
7074            &workflow_type,
7075            "register_typed_workflow",
7076        ) {
7077            return;
7078        }
7079        let handler_name = workflow_type.clone();
7080        let handler = Arc::new(handler);
7081        self.workflows.insert(
7082            workflow_type,
7083            RegisteredWorkflow {
7084                execute: Arc::new(move |ctx, input| {
7085                    let input = decode_workflow_entry::<I>(input, &handler_name)?;
7086                    let handler = Arc::clone(&handler);
7087                    let handler_name = handler_name.clone();
7088                    Ok(Box::pin(async move {
7089                        let result = handler(ctx, input).await?;
7090                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7091                    }))
7092                }),
7093                replay: None,
7094                state_type: None,
7095                definition_fingerprint: None,
7096            },
7097        );
7098    }
7099
7100    /// Register a workflow on the lossless fixed Avro Value surface.
7101    #[track_caller]
7102    pub fn register_workflow_avro_value<F, Fut>(
7103        &mut self,
7104        workflow_type: impl Into<String>,
7105        handler: F,
7106    ) where
7107        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
7108        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7109    {
7110        let workflow_type = workflow_type.into();
7111        if !self.admit_registration::<F>(
7112            RegistrationKind::Workflow,
7113            None,
7114            &workflow_type,
7115            "register_workflow_avro_value",
7116        ) {
7117            return;
7118        }
7119        self.workflows.insert(
7120            workflow_type,
7121            RegisteredWorkflow {
7122                execute: Arc::new(move |ctx, input| Ok(Box::pin(handler(ctx, input)))),
7123                replay: None,
7124                state_type: None,
7125                definition_fingerprint: None,
7126            },
7127        );
7128    }
7129
7130    /// Register a workflow whose typed instance state can be reconstructed for queries.
7131    ///
7132    /// `state_factory` creates a fresh instance for every normal workflow task and
7133    /// query replay. The workflow handler is the single source of truth for state
7134    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7135    /// resolve. Query replay runs this same handler over committed history and
7136    /// discards any commands it would emit.
7137    #[track_caller]
7138    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7139        &mut self,
7140        workflow_type: impl Into<String>,
7141        state_factory: Factory,
7142        handler: F,
7143    ) where
7144        S: Clone + Send + Sync + 'static,
7145        Factory: Fn() -> S + Send + Sync + 'static,
7146        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7147        Fut: Future<Output = Result<Value>> + Send + 'static,
7148    {
7149        let workflow_type = workflow_type.into();
7150        if !self.admit_registration::<F>(
7151            RegistrationKind::Workflow,
7152            None,
7153            &workflow_type,
7154            "register_replayed_workflow",
7155        ) {
7156            return;
7157        }
7158        let state_factory = Arc::new(state_factory);
7159        let handler = Arc::new(handler);
7160
7161        let execute_factory = Arc::clone(&state_factory);
7162        let execute_handler = Arc::clone(&handler);
7163        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7164            let state = WorkflowInstance::new(execute_factory());
7165            let handler = Arc::clone(&execute_handler);
7166            Ok(Box::pin(async move {
7167                let result = handler(ctx, input.into_json()?, state).await?;
7168                AvroValue::from_serialize(&result)
7169            }) as WorkflowFuture)
7170        });
7171
7172        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7173            let state = WorkflowInstance::new(state_factory());
7174            let snapshot_state = state.clone();
7175            let snapshot: WorkflowStateSnapshot =
7176                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7177            let replay_handler = Arc::clone(&handler);
7178            let future = async move {
7179                let result = replay_handler(ctx, input.into_json()?, state).await?;
7180                AvroValue::from_serialize(&result)
7181            };
7182            Ok(ReplayedWorkflowInvocation {
7183                future: Box::pin(future),
7184                snapshot,
7185            })
7186        });
7187
7188        self.workflows.insert(
7189            workflow_type,
7190            RegisteredWorkflow {
7191                execute,
7192                replay: Some(replay),
7193                state_type: Some(TypeId::of::<S>()),
7194                definition_fingerprint: None,
7195            },
7196        );
7197    }
7198
7199    /// Register a replayable workflow with one Serde request value and result.
7200    ///
7201    /// Normal task execution and instance-state query replay both decode and
7202    /// encode through the fixed Avro Value codec. The state factory and handler
7203    /// otherwise follow [`Worker::register_replayed_workflow`].
7204    #[track_caller]
7205    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7206        &mut self,
7207        workflow_type: impl Into<String>,
7208        state_factory: Factory,
7209        handler: F,
7210    ) where
7211        I: DeserializeOwned + Send + 'static,
7212        O: Serialize + Send + 'static,
7213        S: Clone + Send + Sync + 'static,
7214        Factory: Fn() -> S + Send + Sync + 'static,
7215        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7216        Fut: Future<Output = Result<O>> + Send + 'static,
7217    {
7218        let workflow_type = workflow_type.into();
7219        if !self.admit_registration::<F>(
7220            RegistrationKind::Workflow,
7221            None,
7222            &workflow_type,
7223            "register_typed_replayed_workflow",
7224        ) {
7225            return;
7226        }
7227        let state_factory = Arc::new(state_factory);
7228        let handler = Arc::new(handler);
7229
7230        let execute_name = workflow_type.clone();
7231        let execute_factory = Arc::clone(&state_factory);
7232        let execute_handler = Arc::clone(&handler);
7233        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7234            let input = decode_workflow_entry::<I>(input, &execute_name)?;
7235            let state = WorkflowInstance::new(execute_factory());
7236            let handler = Arc::clone(&execute_handler);
7237            let handler_name = execute_name.clone();
7238            Ok(Box::pin(async move {
7239                let result = handler(ctx, input, state).await?;
7240                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7241            }) as WorkflowFuture)
7242        });
7243
7244        let replay_name = workflow_type.clone();
7245        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7246            let input = decode_workflow_entry::<I>(input, &replay_name)?;
7247            let state = WorkflowInstance::new(state_factory());
7248            let snapshot_state = state.clone();
7249            let snapshot: WorkflowStateSnapshot =
7250                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7251            let handler = Arc::clone(&handler);
7252            let handler_name = replay_name.clone();
7253            let future = async move {
7254                let result = handler(ctx, input, state).await?;
7255                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7256            };
7257            Ok(ReplayedWorkflowInvocation {
7258                future: Box::pin(future),
7259                snapshot,
7260            })
7261        });
7262
7263        self.workflows.insert(
7264            workflow_type,
7265            RegisteredWorkflow {
7266                execute,
7267                replay: Some(replay),
7268                state_type: Some(TypeId::of::<S>()),
7269                definition_fingerprint: None,
7270            },
7271        );
7272    }
7273
7274    /// Declare the signal names consumed by a registered workflow.
7275    ///
7276    /// Call this after registering the workflow and before starting the worker.
7277    /// Names read through `wait_signal` or `signals` need a declaration for
7278    /// Server command admission. Arguments remain arbitrary positional values,
7279    /// including lossless Avro values. This replaces the previous declaration;
7280    /// an empty slice declares no signals. Names are sorted and deduplicated.
7281    /// Existing runs retain the declarations captured when they started.
7282    pub fn declare_workflow_signals(
7283        &mut self,
7284        workflow_type: &str,
7285        signal_names: &[&str],
7286    ) -> Result<()> {
7287        if !self.workflows.contains_key(workflow_type) {
7288            return Err(Error::Codec(format!(
7289                "workflow type {workflow_type:?} is not registered"
7290            )));
7291        }
7292        if signal_names
7293            .iter()
7294            .any(|name| name.is_empty() || *name != name.trim())
7295        {
7296            return Err(Error::Codec(
7297                "signal names must be non-empty and have no surrounding whitespace".into(),
7298            ));
7299        }
7300        let mut names = signal_names
7301            .iter()
7302            .map(|name| (*name).to_string())
7303            .collect::<Vec<_>>();
7304        names.sort();
7305        names.dedup();
7306        self.signals.insert(workflow_type.to_string(), names);
7307        Ok(())
7308    }
7309
7310    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7311    ///
7312    /// Supply `include_str!` values for the workflow body and every helper whose
7313    /// behavior can affect replay. Register the workflow once, then set its
7314    /// identity before starting the worker. Duplicate registrations are invalid. The server
7315    /// rejects reusing a worker ID when its prior fingerprint disappears.
7316    /// Workflows without source identity remain runnable but cannot be safely redriven.
7317    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7318    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7319    pub fn set_workflow_definition_sources(
7320        &mut self,
7321        workflow_type: &str,
7322        sources: &[&str],
7323    ) -> Result<()> {
7324        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7325            return Err(Error::Codec(
7326                "workflow definition sources must be non-empty".to_string(),
7327            ));
7328        }
7329        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7330            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7331        })?;
7332        let mut hasher = Sha256::new();
7333        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7334        hasher.update((workflow_type.len() as u64).to_be_bytes());
7335        hasher.update(workflow_type.as_bytes());
7336        for source in sources {
7337            hasher.update((source.len() as u64).to_be_bytes());
7338            hasher.update(source.as_bytes());
7339        }
7340        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7341        Ok(())
7342    }
7343
7344    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7345    #[track_caller]
7346    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7347        &mut self,
7348        workflow_type: impl Into<String>,
7349        state_factory: Factory,
7350        handler: F,
7351    ) where
7352        S: Clone + Send + Sync + 'static,
7353        Factory: Fn() -> S + Send + Sync + 'static,
7354        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7355        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7356    {
7357        let workflow_type = workflow_type.into();
7358        if !self.admit_registration::<F>(
7359            RegistrationKind::Workflow,
7360            None,
7361            &workflow_type,
7362            "register_replayed_workflow_avro_value",
7363        ) {
7364            return;
7365        }
7366        let state_factory = Arc::new(state_factory);
7367        let handler = Arc::new(handler);
7368
7369        let execute_factory = Arc::clone(&state_factory);
7370        let execute_handler = Arc::clone(&handler);
7371        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7372            let state = WorkflowInstance::new(execute_factory());
7373            Ok(Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture)
7374        });
7375
7376        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7377            let state = WorkflowInstance::new(state_factory());
7378            let snapshot_state = state.clone();
7379            let snapshot: WorkflowStateSnapshot =
7380                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7381            Ok(ReplayedWorkflowInvocation {
7382                future: Box::pin(handler(ctx, input, state)),
7383                snapshot,
7384            })
7385        });
7386
7387        self.workflows.insert(
7388            workflow_type,
7389            RegisteredWorkflow {
7390                execute,
7391                replay: Some(replay),
7392                state_type: Some(TypeId::of::<S>()),
7393                definition_fingerprint: None,
7394            },
7395        );
7396    }
7397
7398    #[track_caller]
7399    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7400    where
7401        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7402        Fut: Future<Output = Result<Value>> + Send + 'static,
7403    {
7404        let activity_type = activity_type.into();
7405        if !self.admit_registration::<F>(
7406            RegistrationKind::Activity,
7407            None,
7408            &activity_type,
7409            "register_activity",
7410        ) {
7411            return;
7412        }
7413        let handler = Arc::new(handler);
7414        self.activities.insert(
7415            activity_type,
7416            Arc::new(move |ctx, args| {
7417                let handler = Arc::clone(&handler);
7418                Box::pin(async move {
7419                    let result = handler(ctx, args.into_json()?).await?;
7420                    AvroValue::from_serialize(&result)
7421                })
7422            }),
7423        );
7424    }
7425
7426    /// Register an activity with one Serde request value and a Serde result.
7427    ///
7428    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7429    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7430    /// with the activity name and Rust type.
7431    #[track_caller]
7432    pub fn register_typed_activity<I, O, F, Fut>(
7433        &mut self,
7434        activity_type: impl Into<String>,
7435        handler: F,
7436    ) where
7437        I: DeserializeOwned + Send + 'static,
7438        O: Serialize + Send + 'static,
7439        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
7440        Fut: Future<Output = Result<O>> + Send + 'static,
7441    {
7442        let activity_type = activity_type.into();
7443        if !self.admit_registration::<F>(
7444            RegistrationKind::Activity,
7445            None,
7446            &activity_type,
7447            "register_typed_activity",
7448        ) {
7449            return;
7450        }
7451        let handler_name = activity_type.clone();
7452        let handler = Arc::new(handler);
7453        self.activities.insert(
7454            activity_type,
7455            Arc::new(move |ctx, input| {
7456                let handler = Arc::clone(&handler);
7457                let handler_name = handler_name.clone();
7458                Box::pin(async move {
7459                    let input =
7460                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
7461                    let result = handler(ctx, input).await?;
7462                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
7463                })
7464            }),
7465        );
7466    }
7467
7468    /// Register an activity on the lossless fixed Avro Value surface.
7469    #[track_caller]
7470    pub fn register_activity_avro_value<F, Fut>(
7471        &mut self,
7472        activity_type: impl Into<String>,
7473        handler: F,
7474    ) where
7475        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
7476        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7477    {
7478        let activity_type = activity_type.into();
7479        if !self.admit_registration::<F>(
7480            RegistrationKind::Activity,
7481            None,
7482            &activity_type,
7483            "register_activity_avro_value",
7484        ) {
7485            return;
7486        }
7487        self.activities.insert(
7488            activity_type,
7489            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7490        );
7491    }
7492
7493    /// Register a named, read-only query handler for a workflow type.
7494    ///
7495    /// The workflow type must also be registered with [`Worker::register_workflow`]
7496    /// before the worker runs. The handler receives only an immutable committed
7497    /// state snapshot and normalized query arguments.
7498    #[track_caller]
7499    pub fn register_query<F, Fut>(
7500        &mut self,
7501        workflow_type: impl Into<String>,
7502        query_name: impl Into<String>,
7503        handler: F,
7504    ) where
7505        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7506        Fut: Future<Output = Result<Value>> + Send + 'static,
7507    {
7508        let workflow_type = workflow_type.into();
7509        let query_name = query_name.into();
7510        if !self.admit_registration::<F>(
7511            RegistrationKind::Query,
7512            Some(&workflow_type),
7513            &query_name,
7514            "register_query",
7515        ) {
7516            return;
7517        }
7518        let handler = Arc::new(handler);
7519        self.queries.entry(workflow_type).or_default().insert(
7520            query_name,
7521            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
7522                let handler = Arc::clone(&handler);
7523                Box::pin(async move {
7524                    let result = handler(ctx, args.into_json()?).await?;
7525                    AvroValue::from_serialize(&result)
7526                })
7527            })),
7528        );
7529    }
7530
7531    /// Register a query handler on the lossless fixed Avro Value surface.
7532    #[track_caller]
7533    pub fn register_query_avro_value<F, Fut>(
7534        &mut self,
7535        workflow_type: impl Into<String>,
7536        query_name: impl Into<String>,
7537        handler: F,
7538    ) where
7539        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7540        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7541    {
7542        let workflow_type = workflow_type.into();
7543        let query_name = query_name.into();
7544        if !self.admit_registration::<F>(
7545            RegistrationKind::Query,
7546            Some(&workflow_type),
7547            &query_name,
7548            "register_query_avro_value",
7549        ) {
7550            return;
7551        }
7552        self.queries.entry(workflow_type).or_default().insert(
7553            query_name,
7554            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
7555        );
7556    }
7557
7558    /// Register a named query against deterministically replayed instance state.
7559    ///
7560    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
7561    /// same state type `S`. The handler receives an immutable, detached state
7562    /// clone, so successful and failed queries cannot affect workflow execution
7563    /// or the state reconstructed by a later query.
7564    #[track_caller]
7565    pub fn register_replayed_query<S, F, Fut>(
7566        &mut self,
7567        workflow_type: impl Into<String>,
7568        query_name: impl Into<String>,
7569        handler: F,
7570    ) where
7571        S: Clone + Send + Sync + 'static,
7572        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
7573        Fut: Future<Output = Result<Value>> + Send + 'static,
7574    {
7575        let workflow_type = workflow_type.into();
7576        let query_name = query_name.into();
7577        if !self.admit_registration::<F>(
7578            RegistrationKind::Query,
7579            Some(&workflow_type),
7580            &query_name,
7581            "register_replayed_query",
7582        ) {
7583            return;
7584        }
7585        let handler = Arc::new(handler);
7586        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7587            let state = state.downcast::<S>().map_err(|_| {
7588                "registered query state type does not match the replayed workflow state".to_string()
7589            })?;
7590            let handler = Arc::clone(&handler);
7591            Ok(Box::pin(async move {
7592                let result = handler(ctx, state, args.into_json()?).await?;
7593                AvroValue::from_serialize(&result)
7594            }))
7595        });
7596
7597        self.queries.entry(workflow_type).or_default().insert(
7598            query_name,
7599            RegisteredQuery::Replayed {
7600                state_type: TypeId::of::<S>(),
7601                handler: erased_handler,
7602            },
7603        );
7604    }
7605
7606    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7607    #[track_caller]
7608    pub fn register_replayed_query_avro_value<S, F, Fut>(
7609        &mut self,
7610        workflow_type: impl Into<String>,
7611        query_name: impl Into<String>,
7612        handler: F,
7613    ) where
7614        S: Clone + Send + Sync + 'static,
7615        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7616        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7617    {
7618        let workflow_type = workflow_type.into();
7619        let query_name = query_name.into();
7620        if !self.admit_registration::<F>(
7621            RegistrationKind::Query,
7622            Some(&workflow_type),
7623            &query_name,
7624            "register_replayed_query_avro_value",
7625        ) {
7626            return;
7627        }
7628        let handler = Arc::new(handler);
7629        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7630            let state = state.downcast::<S>().map_err(|_| {
7631                "registered query state type does not match the replayed workflow state".to_string()
7632            })?;
7633            Ok(Box::pin(handler(ctx, state, args)))
7634        });
7635
7636        self.queries.entry(workflow_type).or_default().insert(
7637            query_name,
7638            RegisteredQuery::Replayed {
7639                state_type: TypeId::of::<S>(),
7640                handler: erased_handler,
7641            },
7642        );
7643    }
7644
7645    /// Register a synchronous workflow update handler.
7646    #[track_caller]
7647    pub fn register_update<F, Fut>(
7648        &mut self,
7649        workflow_type: impl Into<String>,
7650        update_name: impl Into<String>,
7651        handler: F,
7652    ) where
7653        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7654        Fut: Future<Output = Result<Value>> + Send + 'static,
7655    {
7656        let workflow_type = workflow_type.into();
7657        let update_name = update_name.into();
7658        if !self.admit_registration::<F>(
7659            RegistrationKind::Update,
7660            Some(&workflow_type),
7661            &update_name,
7662            "register_update",
7663        ) {
7664            return;
7665        }
7666        let handler = Arc::new(handler);
7667        self.updates.entry(workflow_type).or_default().insert(
7668            update_name,
7669            Arc::new(move |ctx, args| {
7670                let handler = Arc::clone(&handler);
7671                Box::pin(async move {
7672                    let result = handler(ctx, args.into_json()?).await?;
7673                    AvroValue::from_serialize(&result)
7674                })
7675            }),
7676        );
7677    }
7678
7679    /// Register an update handler on the lossless fixed Avro Value surface.
7680    #[track_caller]
7681    pub fn register_update_avro_value<F, Fut>(
7682        &mut self,
7683        workflow_type: impl Into<String>,
7684        update_name: impl Into<String>,
7685        handler: F,
7686    ) where
7687        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7688        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7689    {
7690        let workflow_type = workflow_type.into();
7691        let update_name = update_name.into();
7692        if !self.admit_registration::<F>(
7693            RegistrationKind::Update,
7694            Some(&workflow_type),
7695            &update_name,
7696            "register_update_avro_value",
7697        ) {
7698            return;
7699        }
7700        self.updates.entry(workflow_type).or_default().insert(
7701            update_name,
7702            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7703        );
7704    }
7705
7706    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7707        self.validate_registration()?;
7708        self.query_authority_confirmed
7709            .store(false, Ordering::SeqCst);
7710        if self.require_query_task_authority {
7711            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
7712                return Err(Error::WorkerLoop(
7713                    "query authority requires worker protocol 1.20".into(),
7714                ));
7715            }
7716            // Discovery uses the Worker credential, including worker-only Clients.
7717            let discovery: Value = self
7718                .client
7719                .request_json_unresolved_with_timeout::<Value, Value>(
7720                    reqwest::Method::GET,
7721                    "/cluster/info",
7722                    RequestProtocol::Worker("1.20"),
7723                    None,
7724                    Duration::from_secs(5),
7725                )
7726                .await?;
7727            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
7728                return Err(Error::WorkerLoop(
7729                    "runtime does not advertise query_task_authority".into(),
7730                ));
7731            }
7732        }
7733        self.sticky_registration_confirmed
7734            .store(false, Ordering::SeqCst);
7735        self.session_registration_confirmed
7736            .store(false, Ordering::SeqCst);
7737        for capability in &self.resource_capabilities {
7738            worker_session::validate_resource_capability(capability)?;
7739        }
7740        self.local_registration_confirmed
7741            .store(false, Ordering::SeqCst);
7742        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7743            return Err(Error::CooperativeCancellationUnavailable(
7744                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7745            ));
7746        }
7747        let mut command_contracts = serde_json::Map::new();
7748        for workflow_type in self.workflows.keys() {
7749            let mut queries = self
7750                .queries
7751                .get(workflow_type)
7752                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7753                .unwrap_or_default();
7754            queries.sort();
7755            let mut updates = self
7756                .updates
7757                .get(workflow_type)
7758                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7759                .unwrap_or_default();
7760            updates.sort();
7761            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
7762            command_contracts.insert(
7763                workflow_type.clone(),
7764                json!({
7765                    "queries": queries,
7766                    "query_contracts": argument_vector_contracts(&queries),
7767                    "signals": signals,
7768                    "signal_contracts": argument_vector_contracts(&signals),
7769                    "updates": updates,
7770                    "update_contracts": argument_vector_contracts(&updates),
7771                    "update_validators": [],
7772                }),
7773            );
7774        }
7775
7776        self.cooperative_registration_confirmed
7777            .store(false, Ordering::SeqCst);
7778        let response = self
7779            .client
7780            .register_worker_with_definition_fingerprints(
7781                &self.worker_id,
7782                &self.task_queue,
7783                self.workflows.keys().cloned().collect(),
7784                self.activities.keys().cloned().collect(),
7785                self.max_concurrent_workflow_tasks,
7786                self.max_concurrent_activity_tasks,
7787                [
7788                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7789                    Some("workflow_entry_arguments_validation".to_string()),
7790                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7791                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7792                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7793                    self.client
7794                        .local_activities_enabled
7795                        .then(|| "local_activities".to_string()),
7796                    self.client
7797                        .worker_sessions_enabled
7798                        .then(|| "worker_sessions".to_string()),
7799                    self.client
7800                        .sticky_cache
7801                        .is_some()
7802                        .then(|| "sticky_execution".to_string()),
7803                    self.cooperative_cancellation_enabled
7804                        .then(|| "cooperative_cancellation".to_string()),
7805                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7806                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7807                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7808                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7809                ]
7810                .into_iter()
7811                .flatten()
7812                .chain(self.resource_capabilities.iter().cloned())
7813                .collect(),
7814                Value::Object(command_contracts),
7815                Some(
7816                    self.workflows
7817                        .iter()
7818                        .filter_map(|(workflow_type, workflow)| {
7819                            workflow
7820                                .definition_fingerprint
7821                                .as_ref()
7822                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7823                        })
7824                        .collect(),
7825                ),
7826            )
7827            .await?;
7828        if self.cooperative_cancellation_enabled && response.registered {
7829            self.cooperative_registration_confirmed
7830                .store(true, Ordering::SeqCst);
7831        }
7832        if self.client.local_activities_enabled && response.registered {
7833            self.local_registration_confirmed
7834                .store(true, Ordering::SeqCst);
7835        }
7836        if self.client.worker_sessions_enabled && response.registered {
7837            self.session_registration_confirmed
7838                .store(true, Ordering::SeqCst);
7839        }
7840        if self.client.sticky_cache.is_some() && response.registered {
7841            self.sticky_registration_confirmed
7842                .store(true, Ordering::SeqCst);
7843        }
7844        self.query_authority_confirmed.store(
7845            response.registered
7846                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
7847                && response
7848                    .server_capabilities
7849                    .as_ref()
7850                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
7851            Ordering::SeqCst,
7852        );
7853        Ok(response)
7854    }
7855
7856    /// Run until shutdown or a terminal worker error occurs.
7857    ///
7858    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7859    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7860    /// authentication, protocol, and other non-retryable failures are returned.
7861    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7862    /// poll and heartbeat outages beyond the ordinary retry budget.
7863    pub async fn run(&self) -> Result<()> {
7864        self.run_until(std::future::pending::<()>()).await
7865    }
7866
7867    /// Run until `shutdown` resolves or a terminal worker error occurs.
7868    ///
7869    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7870    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7871    where
7872        F: Future<Output = ()>,
7873    {
7874        let _clear_cache_on_drop =
7875            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
7876        let stop = Arc::new(AtomicBool::new(false));
7877        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7878        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7879        worker.run_stop = Some(Arc::clone(&stop));
7880        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7881        tokio::pin!(run);
7882        tokio::pin!(shutdown);
7883        tokio::select! {
7884            result = &mut run => result,
7885            _ = &mut shutdown => {
7886                stop.store(true, Ordering::SeqCst);
7887                run.await
7888            }
7889        }
7890    }
7891
7892    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7893        let mut worker = self.clone();
7894        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7895            policy: self.retry_policy,
7896            stop,
7897            workflow_completion_retry_deadline: None,
7898        });
7899        worker
7900    }
7901
7902    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7903        let registration = self.register().await?;
7904        if !registration.registered {
7905            return Err(Error::WorkerLoop(format!(
7906                "worker registration for {:?} was not accepted",
7907                self.worker_id
7908            )));
7909        }
7910        let registered_worker_id = registration.worker_id.clone();
7911        let primary = self.run_registered_until(stop, registration).await;
7912        let primary = match (primary, self.close_worker_sessions().await) {
7913            (Ok(()), result) => result,
7914            (Err(error), Ok(())) => Err(error),
7915            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7916                primary: Box::new(primary),
7917                deregistration: Box::new(close),
7918            }),
7919        };
7920        self.session_registration_confirmed
7921            .store(false, Ordering::SeqCst);
7922        self.cooperative_registration_confirmed
7923            .store(false, Ordering::SeqCst);
7924        self.local_registration_confirmed
7925            .store(false, Ordering::SeqCst);
7926        let deregistration = self
7927            .client
7928            .deregister_worker_registration(&registered_worker_id)
7929            .await;
7930        self.sticky_registration_confirmed
7931            .store(false, Ordering::SeqCst);
7932        self.client.clear_sticky_cache()?;
7933
7934        match (primary, deregistration) {
7935            (Ok(()), Ok(_)) => Ok(()),
7936            (Ok(()), Err(deregistration)) => Err(deregistration),
7937            (Err(primary), Ok(_)) => Err(primary),
7938            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7939                primary: Box::new(primary),
7940                deregistration: Box::new(deregistration),
7941            }),
7942        }
7943    }
7944
7945    async fn run_registered_until(
7946        &self,
7947        stop: Arc<AtomicBool>,
7948        registration: RegisterWorkerResponse,
7949    ) -> Result<()> {
7950        if self.require_query_task_authority
7951            && !self.query_authority_confirmed.load(Ordering::SeqCst)
7952        {
7953            return Err(Error::WorkerLoop(
7954                "registration did not confirm query_task_authority".into(),
7955            ));
7956        }
7957        let heartbeat_interval = Duration::from_secs(
7958            registration
7959                .heartbeat_interval_seconds
7960                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7961        );
7962        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7963        // from the completion of the preceding attempt, including its bounded
7964        // retries. A fixed-epoch interval can leave an already-due tick queued
7965        // while an acknowledgement is slow, producing a catch-up heartbeat as
7966        // soon as that request completes.
7967        let heartbeat = tokio::time::sleep(Duration::ZERO);
7968        tokio::pin!(heartbeat);
7969        // Poll responses may already have leased server-side work by the time
7970        // they become ready, so each poller owns its responses through
7971        // completion or failure instead of racing raw polls in this select.
7972        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7973            let worker = self.clone();
7974            let stop = Arc::clone(&stop);
7975            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7976        });
7977        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7978            let worker = self.clone();
7979            let stop = Arc::clone(&stop);
7980            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7981        });
7982        let mut query_poller = (!self.queries.is_empty()).then(|| {
7983            let worker = self.clone();
7984            let stop = Arc::clone(&stop);
7985            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7986        });
7987
7988        loop {
7989            tokio::select! {
7990                _ = wait_for_worker_stop(&stop) => {
7991                    stop.store(true, Ordering::SeqCst);
7992                    break;
7993                }
7994                _ = &mut heartbeat => {
7995                    let result = self.retry_worker_operation(|| {
7996                        self.client.heartbeat_worker_with_sessions(
7997                            &self.worker_id,
7998                            self.max_concurrent_workflow_tasks,
7999                            self.max_concurrent_activity_tasks,
8000                            self.client.worker_sessions_enabled.then(|| self.session_available()),
8001                        )
8002                    }).await;
8003                    heartbeat
8004                        .as_mut()
8005                        .reset(tokio::time::Instant::now() + heartbeat_interval);
8006                    match result {
8007                        Ok(Some(acknowledgement)) => {
8008                            if let Some(observer) = &self.heartbeat_observer {
8009                                observer(&WorkerHeartbeatObservation {
8010                                    worker_id: self.worker_id.clone(),
8011                                    task_queue: self.task_queue.clone(),
8012                                    acknowledged_at_unix_millis: SystemTime::now()
8013                                        .duration_since(UNIX_EPOCH)
8014                                        .unwrap_or_default()
8015                                        .as_millis()
8016                                        .min(u64::MAX as u128)
8017                                        as u64,
8018                                    acknowledgement,
8019                                });
8020                            }
8021                        }
8022                        Ok(None) => break,
8023                        Err(error) => {
8024                            stop.store(true, Ordering::SeqCst);
8025                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
8026                            return Err(error);
8027                        }
8028                    }
8029                }
8030                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
8031                    workflow_poller = None;
8032                    let stopped_by_server = stop.load(Ordering::SeqCst);
8033                    stop.store(true, Ordering::SeqCst);
8034                    let poller_result = optional_poller_result("workflow", result);
8035                    let join_result =
8036                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8037                    poller_result?;
8038                    join_result?;
8039                    if stopped_by_server {
8040                        return Ok(());
8041                    }
8042                    return Err(Error::WorkerLoop(
8043                        "workflow poller stopped unexpectedly".to_string(),
8044                    ));
8045                }
8046                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
8047                    activity_poller = None;
8048                    let stopped_by_server = stop.load(Ordering::SeqCst);
8049                    stop.store(true, Ordering::SeqCst);
8050                    let poller_result = optional_poller_result("activity", result);
8051                    let join_result =
8052                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8053                    poller_result?;
8054                    join_result?;
8055                    if stopped_by_server {
8056                        return Ok(());
8057                    }
8058                    return Err(Error::WorkerLoop(
8059                        "activity poller stopped unexpectedly".to_string(),
8060                    ));
8061                }
8062                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
8063                    query_poller = None;
8064                    let stopped_by_server = stop.load(Ordering::SeqCst);
8065                    stop.store(true, Ordering::SeqCst);
8066                    let poller_result = optional_poller_result("query", result);
8067                    let join_result =
8068                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8069                    poller_result?;
8070                    join_result?;
8071                    if stopped_by_server {
8072                        return Ok(());
8073                    }
8074                    return Err(Error::WorkerLoop(
8075                        "query poller stopped unexpectedly".to_string(),
8076                    ));
8077                }
8078            }
8079        }
8080
8081        join_pollers(
8082            workflow_poller.take(),
8083            activity_poller.take(),
8084            query_poller.take(),
8085        )
8086        .await
8087    }
8088
8089    /// Poll and settle at most one task from each enabled task family.
8090    ///
8091    /// A workflow may reach its server-enforced run deadline while this worker
8092    /// holds a task. When the completion endpoint authoritatively rejects that
8093    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
8094    /// terminal `run_status=failed`, the workflow tick is considered settled:
8095    /// the late command was not recorded and cannot replace the terminal run.
8096    /// Every other completion rejection remains an error. This worker-level
8097    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
8098    /// only bounds how long a client waits for a result.
8099    ///
8100    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
8101    /// the original [`Error::Http`] status and response body.
8102    pub async fn run_once(&self) -> Result<usize> {
8103        self.validate_registration()?;
8104        if self.client.worker_sessions_enabled {
8105            self.require_session_registration()?;
8106        }
8107        if self.cooperative_cancellation_enabled
8108            && !self
8109                .cooperative_registration_confirmed
8110                .load(Ordering::SeqCst)
8111        {
8112            return Err(Error::CooperativeCancellationUnavailable(
8113                "register this cooperative worker before polling tasks".into(),
8114            ));
8115        }
8116        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
8117        let mut handled = 0;
8118        match worker.poll_workflow_once().await? {
8119            ManagedPollOutcome::Handled => handled += 1,
8120            ManagedPollOutcome::Stop => return Ok(handled),
8121            ManagedPollOutcome::Idle => {}
8122        }
8123        match worker.poll_activity_once().await? {
8124            ManagedPollOutcome::Handled => handled += 1,
8125            ManagedPollOutcome::Stop => return Ok(handled),
8126            ManagedPollOutcome::Idle => {}
8127        }
8128        if !self.queries.is_empty() {
8129            match worker.poll_query_once().await? {
8130                ManagedPollOutcome::Handled => handled += 1,
8131                ManagedPollOutcome::Stop => return Ok(handled),
8132                ManagedPollOutcome::Idle => {}
8133            }
8134        }
8135        Ok(handled)
8136    }
8137
8138    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
8139        if self.client.sticky_cache.is_some()
8140            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
8141        {
8142            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
8143        }
8144        if self.client.local_activities_enabled
8145            && !self.local_registration_confirmed.load(Ordering::SeqCst)
8146        {
8147            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
8148        }
8149        if self.cooperative_cancellation_enabled {
8150            return self.poll_cooperative_workflow_once().await;
8151        }
8152        let poll_request_id = unique_request_id("rust-workflow-poll");
8153        let response = self
8154            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
8155            .await;
8156        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
8157            return Ok(ManagedPollOutcome::Idle);
8158        };
8159        if response.outcome().should_stop() {
8160            return Ok(ManagedPollOutcome::Stop);
8161        }
8162        let memo_updates_supported =
8163            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
8164        let Some(task) = response.task else {
8165            return Ok(ManagedPollOutcome::Idle);
8166        };
8167
8168        let task_id = task.task_id.clone();
8169        let attempt = task.workflow_task_attempt;
8170        let run_id = task.run_id.clone();
8171        let lease_owner = task
8172            .lease_owner
8173            .clone()
8174            .unwrap_or_else(|| self.worker_id.clone());
8175
8176        let decision = match self.execute_workflow_with_local_activities(task).await {
8177            Ok(Some(decision)) => Ok(decision),
8178            Ok(None) => return Ok(ManagedPollOutcome::Handled),
8179            Err(error) => Err(error),
8180        };
8181        self.settle_workflow_task_decision(
8182            &task_id,
8183            &lease_owner,
8184            attempt,
8185            run_id.as_deref(),
8186            decision,
8187            memo_updates_supported,
8188            snapshot,
8189        )
8190        .await
8191    }
8192
8193    #[allow(clippy::too_many_arguments)]
8194    async fn settle_workflow_task_decision(
8195        &self,
8196        task_id: &str,
8197        lease_owner: &str,
8198        attempt: u64,
8199        run_id: Option<&str>,
8200        decision: Result<WorkflowTaskDecision>,
8201        memo_updates_supported: bool,
8202        snapshot: Option<sticky_worker::StickySnapshot>,
8203    ) -> Result<ManagedPollOutcome> {
8204        match decision {
8205            Ok(decision)
8206                if decision.cancellation_delivery.is_some()
8207                    || decision.cancellation_scope_delivery.is_some()
8208                    || decision.cancellation_scope_opening.is_some() =>
8209            {
8210                return Err(Error::CooperativeCancellationUnavailable(
8211                    "worker cancellation delivery has not been negotiated".into(),
8212                ));
8213            }
8214            Ok(decision)
8215                if commands_use_workflow_memo_updates(&decision.commands)
8216                    && !memo_updates_supported =>
8217            {
8218                self.client
8219                    .fail_workflow_task(
8220                        task_id,
8221                        lease_owner,
8222                        attempt,
8223                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8224                    )
8225                    .await?;
8226            }
8227            Ok(decision) if decision.commands.is_empty() => {
8228                // A replay can consume a recorded pending durable command
8229                // without producing a new command. The standalone protocol
8230                // acknowledges that state through the typed waiting outcome;
8231                // an empty completion is rejected by servers that require at
8232                // least one executable command.
8233                self.client
8234                    .fail_workflow_task_with_type(
8235                        task_id,
8236                        lease_owner,
8237                        attempt,
8238                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8239                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8240                    )
8241                    .await?;
8242            }
8243            Ok(decision) => {
8244                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8245                let completion = self
8246                    .client
8247                    .complete_workflow_task_with_message_streams(
8248                        task_id,
8249                        lease_owner,
8250                        attempt,
8251                        decision.commands,
8252                        decision.message_stream_cursors,
8253                        decision.message_stream_waits,
8254                        sticky_claim,
8255                    )
8256                    .await;
8257                if let Err(error) = completion {
8258                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8259                    if !workflow_task_completion_is_terminal_timeout(
8260                        &error, task_id, attempt, run_id,
8261                    ) {
8262                        return Err(error);
8263                    }
8264                }
8265            }
8266            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8267            Err(error) => {
8268                self.discard_sticky_snapshot(snapshot.as_ref())?;
8269                if matches!(
8270                    error,
8271                    Error::HandlerType {
8272                        handler_kind: HandlerKind::Workflow,
8273                        value_kind: HandlerValueKind::Input,
8274                        ..
8275                    }
8276                ) {
8277                    self.client
8278                        .fail_workflow_task_with_failure(
8279                            task_id,
8280                            lease_owner,
8281                            attempt,
8282                            json!({
8283                                "message": error.to_string(),
8284                                "type": "WorkflowEntryArgumentsMismatch",
8285                                "reason": "workflow_entry_arguments_mismatch",
8286                            }),
8287                        )
8288                        .await?;
8289                } else {
8290                    self.client
8291                        .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8292                        .await?;
8293                }
8294            }
8295        }
8296
8297        Ok(ManagedPollOutcome::Handled)
8298    }
8299
8300    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8301        while !stop.load(Ordering::SeqCst) {
8302            match self.poll_workflow_once().await {
8303                Ok(ManagedPollOutcome::Stop) => {
8304                    stop.store(true, Ordering::SeqCst);
8305                    break;
8306                }
8307                Err(error) => {
8308                    stop.store(true, Ordering::SeqCst);
8309                    return Err(error);
8310                }
8311                _ => {}
8312            }
8313        }
8314
8315        Ok(())
8316    }
8317
8318    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
8319        if self.client.worker_sessions_enabled {
8320            self.require_session_registration()?;
8321        }
8322        if self.cooperative_cancellation_enabled {
8323            return self.poll_cooperative_activity_once().await;
8324        }
8325        let poll_request_id = unique_request_id("rust-activity-poll");
8326        let response = self
8327            .retry_worker_operation(|| {
8328                self.client.poll_activity_task_response_with_request_id(
8329                    &self.worker_id,
8330                    &self.task_queue,
8331                    self.poll_timeout,
8332                    &poll_request_id,
8333                    0,
8334                )
8335            })
8336            .await;
8337        let response = match response {
8338            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8339            response => response,
8340        };
8341        let Some(response) = self.settle_worker_poll_response(response).await? else {
8342            return Ok(ManagedPollOutcome::Idle);
8343        };
8344        if response.outcome().should_stop() {
8345            return Ok(ManagedPollOutcome::Stop);
8346        }
8347        let Some(task) = response.task else {
8348            return Ok(ManagedPollOutcome::Idle);
8349        };
8350
8351        let session = self.track_session_task(task.worker_session.as_ref())?;
8352        let hydration_claim = task.hydration_claim;
8353        let task = task.task;
8354
8355        let task_id = task.task_id.clone();
8356        let attempt_id = task
8357            .activity_attempt_id
8358            .clone()
8359            .or(task.attempt_id.clone())
8360            .unwrap_or_default();
8361        let lease_owner = task
8362            .lease_owner
8363            .clone()
8364            .unwrap_or_else(|| self.worker_id.clone());
8365        let codec = task.payload_codec.clone();
8366        let result = self
8367            .execute_session_activity_task(task, session, hydration_claim.as_ref())
8368            .await;
8369        match result {
8370            Err(Error::ActivityExecutionAbandoned(_)) => {}
8371            Err(error) if activity_hydration::stopped(&error) => {}
8372            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
8373            Ok(value) => {
8374                let completion = self
8375                    .client
8376                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
8377                    .await;
8378                if let Err(error) = completion {
8379                    if !activity_task_rejection_is_final(&error) {
8380                        return Err(error);
8381                    }
8382                }
8383            }
8384            Err(error) => {
8385                let failure = self
8386                    .client
8387                    .fail_activity_task(
8388                        &task_id,
8389                        &attempt_id,
8390                        &lease_owner,
8391                        error.to_string(),
8392                        false,
8393                    )
8394                    .await;
8395                if let Err(error) = failure {
8396                    if !activity_task_rejection_is_final(&error) {
8397                        return Err(error);
8398                    }
8399                }
8400            }
8401        }
8402
8403        Ok(ManagedPollOutcome::Handled)
8404    }
8405
8406    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8407        // Each lane retains its leased response through callback settlement.
8408        // A bounded independent activity must not occupy the cleanup lane too.
8409        // Preserve the existing serial loop unless cooperation is enabled.
8410        let lane_count = if self.cooperative_cancellation_enabled {
8411            self.max_concurrent_activity_tasks
8412        } else {
8413            1
8414        };
8415        let mut lanes = FuturesUnordered::new();
8416        for _ in 0..lane_count {
8417            let worker = self.clone();
8418            let stop = Arc::clone(&stop);
8419            lanes.push(async move {
8420                while !stop.load(Ordering::SeqCst) {
8421                    match worker.poll_activity_once().await {
8422                        Ok(ManagedPollOutcome::Stop) => {
8423                            stop.store(true, Ordering::SeqCst);
8424                            break;
8425                        }
8426                        Err(error) => {
8427                            stop.store(true, Ordering::SeqCst);
8428                            return Err(error);
8429                        }
8430                        _ => {}
8431                    }
8432                }
8433                Ok(())
8434            });
8435        }
8436        // Join every lane before deregistration, including after one fails.
8437        let mut first_error = None;
8438        while let Some(result) = lanes.next().await {
8439            if let Err(error) = result {
8440                first_error.get_or_insert(error);
8441            }
8442        }
8443        first_error.map_or(Ok(()), Err)
8444    }
8445
8446    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
8447        let poll_request_id = unique_request_id("rust-query-poll");
8448        let response = self
8449            .retry_worker_operation(|| {
8450                let body = json!({"worker_id":self.worker_id,"task_queue":self.task_queue,
8451                    "poll_request_id":poll_request_id,
8452                    "timeout_seconds":long_poll_timeout_seconds(self.poll_timeout)});
8453                async move {
8454                    self.client
8455                        .poll_request_json_unresolved::<Value, Value>(
8456                            "/worker/query-tasks/poll",
8457                            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
8458                            &body,
8459                            self.poll_timeout + Duration::from_secs(5),
8460                            0,
8461                        )
8462                        .await
8463                }
8464            })
8465            .await;
8466        let Some(mut wire) = self.settle_worker_poll_response(response).await? else {
8467            return Ok(ManagedPollOutcome::Idle);
8468        };
8469        let authority = if wire.get("task").is_some_and(|task| !task.is_null()) {
8470            match query_authority::Authority::capture(&wire["task"], self) {
8471                Ok(authority) => authority,
8472                Err(_) => return Ok(ManagedPollOutcome::Handled),
8473            }
8474        } else {
8475            None
8476        };
8477        let loading = self.client.resolve_runtime_payloads(
8478            &mut wire,
8479            "/worker/query-tasks/poll",
8480            RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
8481        );
8482        match query_authority::Authority::protect(authority.as_ref(), self, loading).await {
8483            Err(_) => return Ok(ManagedPollOutcome::Handled),
8484            Ok(result) => result?,
8485        }
8486        let response: PollQueryTaskResponse = serde_json::from_value(wire)?;
8487        if response.outcome().should_stop() {
8488            return Ok(ManagedPollOutcome::Stop);
8489        }
8490        let Some(task) = response.task else {
8491            return Ok(ManagedPollOutcome::Idle);
8492        };
8493
8494        let query_task_id = task.query_task_id.clone();
8495        let attempt = task.query_task_attempt;
8496        let lease_owner = task
8497            .lease_owner
8498            .clone()
8499            .unwrap_or_else(|| self.worker_id.clone());
8500        let codec = task.payload_codec.clone();
8501
8502        let execution = query_authority::Authority::protect(
8503            authority.as_ref(),
8504            self,
8505            self.execute_query_task_with_authority(task, authority.as_ref()),
8506        )
8507        .await;
8508        let execution = match execution {
8509            Err(_) => return Ok(ManagedPollOutcome::Handled),
8510            Ok(Err(failure)) if failure.reason == "query_authority_lost" => {
8511                return Ok(ManagedPollOutcome::Handled)
8512            }
8513            Ok(result) => result,
8514        };
8515        match execution {
8516            Ok(value) => {
8517                let result_envelope = match encode_typed_envelope(&value, &codec) {
8518                    Ok(result_envelope) => result_envelope,
8519                    Err(error) => {
8520                        let failure = query_authority::Authority::protect(
8521                            authority.as_ref(),
8522                            self,
8523                            self.client.fail_query_task(
8524                                &query_task_id,
8525                                &lease_owner,
8526                                attempt,
8527                                error.to_string(),
8528                                "query_result_encode_failed",
8529                                "QueryResultEncodeFailed",
8530                            ),
8531                        )
8532                        .await;
8533                        let Ok(failure) = failure else {
8534                            return Ok(ManagedPollOutcome::Handled);
8535                        };
8536                        if let Err(error) = failure {
8537                            if !query_task_rejection_is_final(&error) {
8538                                return Err(error);
8539                            }
8540                        }
8541                        return Ok(ManagedPollOutcome::Handled);
8542                    }
8543                };
8544
8545                let completion = query_authority::Authority::protect(
8546                    authority.as_ref(),
8547                    self,
8548                    self.client.complete_query_task_with_envelope(
8549                        &query_task_id,
8550                        &lease_owner,
8551                        attempt,
8552                        value.clone().into_json()?,
8553                        result_envelope,
8554                    ),
8555                )
8556                .await;
8557                let Ok(completion) = completion else {
8558                    return Ok(ManagedPollOutcome::Handled);
8559                };
8560                if let Err(error) = completion {
8561                    if !query_task_rejection_is_final(&error) {
8562                        return Err(error);
8563                    }
8564                }
8565            }
8566            Err(failure) => {
8567                let result = query_authority::Authority::protect(
8568                    authority.as_ref(),
8569                    self,
8570                    self.client.fail_query_task(
8571                        &query_task_id,
8572                        &lease_owner,
8573                        attempt,
8574                        failure.message,
8575                        failure.reason,
8576                        failure.failure_type,
8577                    ),
8578                )
8579                .await;
8580                let Ok(result) = result else {
8581                    return Ok(ManagedPollOutcome::Handled);
8582                };
8583                if let Err(error) = result {
8584                    if !query_task_rejection_is_final(&error) {
8585                        return Err(error);
8586                    }
8587                }
8588            }
8589        }
8590
8591        Ok(ManagedPollOutcome::Handled)
8592    }
8593
8594    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8595        while !stop.load(Ordering::SeqCst) {
8596            match self.poll_query_once().await {
8597                Ok(ManagedPollOutcome::Stop) => {
8598                    stop.store(true, Ordering::SeqCst);
8599                    break;
8600                }
8601                Err(error) => {
8602                    stop.store(true, Ordering::SeqCst);
8603                    return Err(error);
8604                }
8605                _ => {}
8606            }
8607        }
8608
8609        Ok(())
8610    }
8611
8612    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
8613    where
8614        F: FnMut() -> Fut,
8615        Fut: Future<Output = Result<T>>,
8616    {
8617        let mut retries = 0;
8618
8619        loop {
8620            if self
8621                .run_stop
8622                .as_ref()
8623                .is_some_and(|stop| stop.load(Ordering::SeqCst))
8624            {
8625                return Ok(None);
8626            }
8627            match operation().await {
8628                Err(error)
8629                    if (workflow_hydration::stopped(&error)
8630                        || activity_hydration::stopped(&error))
8631                        && self
8632                            .run_stop
8633                            .as_ref()
8634                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
8635                {
8636                    return Ok(None);
8637                }
8638                Err(error)
8639                    if worker_operation_is_retryable(&error)
8640                        && (retries < self.retry_policy.max_retries
8641                            || (self.recover_transient_outages
8642                                && self.run_stop.is_some()
8643                                && self.retry_policy.max_retries > 0)) =>
8644                {
8645                    retries = retries.saturating_add(1);
8646                    let delay = worker_retry_delay(self.retry_policy, retries)
8647                        .max(Duration::from_millis(1));
8648                    if let Some(stop) = &self.run_stop {
8649                        tokio::select! {
8650                            _ = tokio::time::sleep(delay) => {}
8651                            _ = wait_for_worker_stop(stop) => return Ok(None),
8652                        }
8653                    } else {
8654                        tokio::time::sleep(delay).await;
8655                    }
8656                }
8657                result => return result.map(Some),
8658            }
8659        }
8660    }
8661
8662    async fn settle_worker_poll_response<T>(
8663        &self,
8664        response: Result<Option<T>>,
8665    ) -> Result<Option<T>> {
8666        match response {
8667            Ok(response) => Ok(response),
8668            Err(error) => {
8669                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
8670                    return Err(error);
8671                };
8672                let minimum_delay = self
8673                    .retry_policy
8674                    .initial_backoff
8675                    .max(Duration::from_millis(1));
8676                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
8677                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
8678                Ok(None)
8679            }
8680        }
8681    }
8682
8683    #[cfg(test)]
8684    async fn execute_query_task(
8685        &self,
8686        task: QueryTask,
8687    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8688        self.execute_query_task_with_authority(task, None).await
8689    }
8690
8691    async fn execute_query_task_with_authority(
8692        &self,
8693        mut task: QueryTask,
8694        authority: Option<&query_authority::Authority>,
8695    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8696        validate_query_task_payloads(&task).map_err(|error| {
8697            QueryTaskExecutionFailure::new(
8698                "query_payload_decode_failed",
8699                error.to_string(),
8700                "QueryPayloadDecodeFailed",
8701            )
8702        })?;
8703
8704        if !self.workflows.contains_key(&task.workflow_type) {
8705            return Err(QueryTaskExecutionFailure::new(
8706                "query_workflow_type_not_registered",
8707                format!("no workflow registered for type {:?}", task.workflow_type),
8708                "WorkflowTypeNotRegistered",
8709            ));
8710        }
8711
8712        let Some(handlers) = self.queries.get(&task.workflow_type) else {
8713            return Err(QueryTaskExecutionFailure::new(
8714                "query_handler_unavailable",
8715                format!(
8716                    "query handlers are unavailable for workflow type {:?}",
8717                    task.workflow_type
8718                ),
8719                "QueryHandlerUnavailable",
8720            ));
8721        };
8722        let Some(query) = handlers.get(&task.query_name) else {
8723            return Err(QueryTaskExecutionFailure::new(
8724                "rejected_unknown_query",
8725                format!("unknown query {:?}", task.query_name),
8726                "QueryFailed",
8727            ));
8728        };
8729
8730        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
8731            .map_err(|error| {
8732            QueryTaskExecutionFailure::new(
8733                "query_payload_decode_failed",
8734                format!("cannot decode query arguments: {error}"),
8735                "QueryPayloadDecodeFailed",
8736            )
8737        })?;
8738        let workflow_input_typed =
8739            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
8740                .map_err(|error| {
8741                    QueryTaskExecutionFailure::new(
8742                        "query_workflow_state_unavailable",
8743                        format!("cannot decode workflow start input: {error}"),
8744                        "QueryWorkflowStateUnavailable",
8745                    )
8746                })?;
8747        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
8748            QueryTaskExecutionFailure::new(
8749                "query_workflow_state_unavailable",
8750                format!("cannot project workflow start input: {error}"),
8751                "QueryWorkflowStateUnavailable",
8752            )
8753        })?;
8754        hydrate_query_history_from_export(&mut task).map_err(|error| {
8755            QueryTaskExecutionFailure::new(
8756                "query_workflow_state_unavailable",
8757                format!("cannot restore query history snapshot: {error}"),
8758                "QueryWorkflowStateUnavailable",
8759            )
8760        })?;
8761        enrich_query_history_from_export(&mut task).map_err(|error| {
8762            QueryTaskExecutionFailure::new(
8763                "query_workflow_state_unavailable",
8764                format!("cannot restore compact query history payloads: {error}"),
8765                "QueryWorkflowStateUnavailable",
8766            )
8767        })?;
8768        let signal_events = query_signal_events(&task).map_err(|error| {
8769            QueryTaskExecutionFailure::new(
8770                "query_workflow_state_unavailable",
8771                format!("cannot decode committed workflow signals: {error}"),
8772                "QueryWorkflowStateUnavailable",
8773            )
8774        })?;
8775        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8776        let context = QueryContext {
8777            workflow_id: task.workflow_id,
8778            run_id: task.run_id,
8779            workflow_type: task.workflow_type.clone(),
8780            run_status: task.run_status,
8781            workflow_input,
8782            workflow_input_avro_value: workflow_input_typed.clone(),
8783            history_events: Arc::clone(&history_events),
8784            signal_events: Arc::new(signal_events),
8785        };
8786
8787        let future = match query {
8788            RegisteredQuery::Snapshot(handler) => {
8789                query_authority::before_handler(authority, &self.client).await?;
8790                handler(context, args)
8791            }
8792            RegisteredQuery::Replayed {
8793                state_type,
8794                handler,
8795            } => {
8796                let workflow = self
8797                    .workflows
8798                    .get(&task.workflow_type)
8799                    .expect("workflow registration was checked above");
8800                if workflow.state_type != Some(*state_type) {
8801                    return Err(QueryTaskExecutionFailure::new(
8802                        "query_workflow_state_unavailable",
8803                        "replayed query state type does not match its workflow registration",
8804                        "QueryWorkflowStateUnavailable",
8805                    ));
8806                }
8807                let replay = workflow.replay.as_ref().ok_or_else(|| {
8808                    QueryTaskExecutionFailure::new(
8809                        "query_workflow_state_unavailable",
8810                        format!(
8811                            "workflow type {:?} is not registered for instance-state replay",
8812                            task.workflow_type
8813                        ),
8814                        "QueryWorkflowStateUnavailable",
8815                    )
8816                })?;
8817                let workflow_state = Arc::new(Mutex::new(
8818                    WorkflowState::new_with_identity(
8819                        history_events.as_ref().clone(),
8820                        context.workflow_id.clone(),
8821                        context.run_id.clone(),
8822                        self.task_queue.clone(),
8823                        task.payload_codec,
8824                        None,
8825                    )
8826                    .map_err(|error| {
8827                        QueryTaskExecutionFailure::new(
8828                            "query_workflow_state_unavailable",
8829                            format!("workflow replay failed before query: {error}"),
8830                            "QueryWorkflowStateUnavailable",
8831                        )
8832                    })?,
8833                ));
8834                let workflow_context = WorkflowContext {
8835                    state: workflow_state,
8836                    cancellation_scope_id: "root".into(),
8837                };
8838                query_authority::before_handler(authority, &self.client).await?;
8839                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone())
8840                    .map_err(|error| {
8841                        QueryTaskExecutionFailure::new(
8842                            "query_workflow_state_unavailable",
8843                            error.to_string(),
8844                            "QueryWorkflowStateUnavailable",
8845                        )
8846                    })?;
8847                let outcome = {
8848                    let mut cx = TaskContext::from_waker(noop_waker_ref());
8849                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8850                        .map_err(|error| {
8851                            QueryTaskExecutionFailure::new(
8852                                "query_workflow_state_unavailable",
8853                                error.to_string(),
8854                                "QueryWorkflowStateUnavailable",
8855                            )
8856                        })?;
8857                    invocation.future.as_mut().poll(&mut cx)
8858                };
8859                match outcome {
8860                    Poll::Ready(Ok(_)) => {
8861                        workflow_context
8862                            .ensure_history_consumed()
8863                            .map_err(|error| {
8864                                QueryTaskExecutionFailure::new(
8865                                    "query_workflow_state_unavailable",
8866                                    format!("workflow replay failed before query: {error}"),
8867                                    "QueryWorkflowStateUnavailable",
8868                                )
8869                            })?;
8870                    }
8871                    Poll::Ready(Err(error)) => {
8872                        return Err(QueryTaskExecutionFailure::new(
8873                            "query_workflow_state_unavailable",
8874                            format!("workflow replay failed before query: {error}"),
8875                            "QueryWorkflowStateUnavailable",
8876                        ));
8877                    }
8878                    Poll::Pending => {
8879                        let commands = workflow_context.take_commands().map_err(|error| {
8880                            QueryTaskExecutionFailure::new(
8881                                "query_workflow_state_unavailable",
8882                                format!("workflow replay failed before query: {error}"),
8883                                "QueryWorkflowStateUnavailable",
8884                            )
8885                        })?;
8886                        if commands.is_empty()
8887                            && !workflow_context
8888                                .matched_recorded_pending()
8889                                .map_err(|error| {
8890                                    QueryTaskExecutionFailure::new(
8891                                        "query_workflow_state_unavailable",
8892                                        format!("workflow replay failed before query: {error}"),
8893                                        "QueryWorkflowStateUnavailable",
8894                                    )
8895                                })?
8896                        {
8897                            return Err(QueryTaskExecutionFailure::new(
8898                                "query_workflow_state_unavailable",
8899                                "workflow replay yielded without a durable command",
8900                                "QueryWorkflowStateUnavailable",
8901                            ));
8902                        }
8903                    }
8904                }
8905                let state = (invocation.snapshot)().map_err(|error| {
8906                    QueryTaskExecutionFailure::new(
8907                        "query_workflow_state_unavailable",
8908                        format!("cannot snapshot replayed workflow state: {error}"),
8909                        "QueryWorkflowStateUnavailable",
8910                    )
8911                })?;
8912                query_authority::before_handler(authority, &self.client).await?;
8913                handler(context, state, args).map_err(|message| {
8914                    QueryTaskExecutionFailure::new(
8915                        "query_workflow_state_unavailable",
8916                        message,
8917                        "QueryWorkflowStateUnavailable",
8918                    )
8919                })?
8920            }
8921        };
8922
8923        future.await.map_err(|error| {
8924            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8925        })
8926    }
8927
8928    #[cfg(test)]
8929    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8930        Ok(self.execute_workflow_task_decision(task)?.commands)
8931    }
8932
8933    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8934        self.execute_workflow_task_decision_with_cancellation(task, None)
8935    }
8936
8937    fn execute_workflow_task_decision_with_cancellation(
8938        &self,
8939        task: WorkflowTask,
8940        observation: Option<&CancellationRequest>,
8941    ) -> Result<WorkflowTaskDecision> {
8942        match self.prepare_workflow_task_execution(task, observation)? {
8943            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8944            PreparedWorkflowTask::Execution {
8945                task,
8946                context,
8947                mut future,
8948            } => {
8949                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8950                self.finish_workflow_task_execution(&task, &context, outcome)
8951            }
8952        }
8953    }
8954
8955    fn prepare_workflow_task_execution(
8956        &self,
8957        task: WorkflowTask,
8958        observation: Option<&CancellationRequest>,
8959    ) -> Result<PreparedWorkflowTask> {
8960        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8961            && !self.cooperative_cancellation_enabled
8962        {
8963            return Err(Error::CancellationScopeExecutionUnavailable);
8964        }
8965        validate_workflow_task_payloads(&task)?;
8966        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8967            &task.history_events,
8968            self.allow_cancellation_scope_authoring,
8969            self.allow_cancellation_scope_delivery,
8970        )?;
8971        let cancellation_history = if let Some(observation) = observation {
8972            observation.validate_observation()?;
8973            cooperative_cancellation::cancellation_claim(&task)?;
8974            let canonical = CancellationHistory::from_events(
8975                &task.history_events,
8976                task.run_id.as_deref().unwrap_or_default(),
8977                Some(observation),
8978            )?;
8979            if canonical.request_index >= task.history_events.len() {
8980                return Err(Error::InvalidCooperativeCancellation(
8981                    "workflow replay requires the observed canonical request".into(),
8982                ));
8983            }
8984            Some(canonical)
8985        } else {
8986            None
8987        };
8988        if let Some(update_id) = task
8989            .workflow_update_id
8990            .as_deref()
8991            .filter(|update_id| !update_id.is_empty())
8992        {
8993            if self.allow_cancellation_scope_delivery {
8994                return Err(Error::CancellationScopeExecutionUnavailable);
8995            }
8996            CancellationHistory::from_events(
8997                &task.history_events,
8998                task.run_id.as_deref().unwrap_or_default(),
8999                None,
9000            )?;
9001            return self
9002                .execute_update_task(&task, update_id)
9003                .map(WorkflowTaskDecision::without_message_streams)
9004                .map(PreparedWorkflowTask::Decision);
9005        }
9006
9007        let workflow = self
9008            .workflows
9009            .get(&task.workflow_type)
9010            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
9011        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9012        let resume_signal = decode_resume_signal(&task)?;
9013        let history_budget = WorkflowHistoryBudget {
9014            event_count: task
9015                .total_history_events
9016                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
9017            size_bytes: task.history_size_bytes,
9018            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
9019            pressure: task.history_budget_pressure.clone(),
9020        };
9021        let workflow_command_identity = task
9022            .workflow_command_id
9023            .clone()
9024            .filter(|identity| !identity.is_empty())
9025            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
9026            .unwrap_or_default();
9027        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
9028            task.history_events.clone(),
9029            task.workflow_id.clone(),
9030            task.run_id.clone(),
9031            self.task_queue.clone(),
9032            task.payload_codec.clone(),
9033            resume_signal,
9034            self.allow_cancellation_scope_authoring,
9035            self.allow_cancellation_scope_delivery,
9036        )?;
9037        workflow_state.history_budget = history_budget;
9038        workflow_state.workflow_command_identity = workflow_command_identity;
9039        if let Some(canonical) = cancellation_history {
9040            workflow_state.cancellation_history = canonical;
9041            workflow_state.cancellation_delivery_enabled = true;
9042        }
9043        if workflow_state.cancellation_history.request.is_none() {
9044            workflow_state.cancel_requested = task.cancel_requested;
9045        }
9046        let state = Arc::new(Mutex::new(workflow_state));
9047        let ctx = WorkflowContext {
9048            state,
9049            cancellation_scope_id: "root".into(),
9050        };
9051        let future = (workflow.execute)(ctx.clone(), input)?;
9052        Ok(PreparedWorkflowTask::Execution {
9053            task,
9054            context: ctx,
9055            future,
9056        })
9057    }
9058
9059    fn poll_workflow_future(
9060        ctx: &WorkflowContext,
9061        future: &mut WorkflowFuture,
9062    ) -> Result<Poll<Result<AvroValue>>> {
9063        let mut cx = TaskContext::from_waker(noop_waker_ref());
9064        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
9065        Ok(future.as_mut().poll(&mut cx))
9066    }
9067
9068    fn finish_workflow_task_execution(
9069        &self,
9070        task: &WorkflowTask,
9071        ctx: &WorkflowContext,
9072        outcome: Poll<Result<AvroValue>>,
9073    ) -> Result<WorkflowTaskDecision> {
9074        if !ctx
9075            .state
9076            .lock()
9077            .map_err(|_| Error::WorkflowStatePoisoned)?
9078            .local_activity_requests
9079            .is_empty()
9080        {
9081            return Err(Error::CooperativeCancellationUnavailable(
9082                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
9083            ));
9084        }
9085        let awaiting_canonical_boundary = {
9086            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9087            state.cancellation_delivery_intent.is_some()
9088                || state.cancellation_scope_opening.is_some()
9089                || state
9090                    .scope_delivery
9091                    .as_ref()
9092                    .is_some_and(|replay| replay.intent.is_some())
9093        };
9094        if awaiting_canonical_boundary {
9095            // A private delivery intent never becomes an application error.
9096            // Even a custom future which ignores a pending durable call cannot
9097            // publish terminal commands before canonical delivery and replay.
9098            if let Poll::Ready(Err(error)) = outcome {
9099                if workflow_task_integrity_error(&error) {
9100                    return Err(error);
9101                }
9102            }
9103            return self.message_stream_decision(&ctx, ctx.take_commands()?);
9104        }
9105
9106        match outcome {
9107            Poll::Ready(Ok(result)) => {
9108                ctx.ensure_history_consumed()?;
9109                let result = encode_typed_envelope(&result, &task.payload_codec)?;
9110                let mut commands = ctx.take_commands()?;
9111                commands.push(json!({
9112                    "type": "complete_workflow",
9113                    "result": result
9114                }));
9115                self.message_stream_decision(&ctx, commands)
9116            }
9117            Poll::Ready(Err(error)) => {
9118                if let Error::ContinueAsNew(request) = error {
9119                    let mut commands = ctx.take_commands()?;
9120                    if let Some(command) = ctx.continue_as_new_command(request)? {
9121                        commands.push(command);
9122                    }
9123                    ctx.ensure_history_consumed()?;
9124                    return self.message_stream_decision(&ctx, commands);
9125                }
9126                if workflow_task_integrity_error(&error) {
9127                    // Replay and protocol failures describe the workflow-task
9128                    // decision itself. Preserve their specific failure reason
9129                    // instead of replacing it with the derivative fact that
9130                    // recorded commands remain unconsumed.
9131                    return Err(error);
9132                }
9133                // A handler error must not hide a committed durable command that
9134                // upgraded workflow code no longer consumes.
9135                ctx.ensure_history_consumed()?;
9136                let mut commands = ctx.take_commands()?;
9137                commands.push(workflow_failure_command(
9138                    &error,
9139                    recorded_activity_failure_boundary(&ctx, &error),
9140                ));
9141                self.message_stream_decision(&ctx, commands)
9142            }
9143            Poll::Pending => {
9144                let commands = ctx.take_commands()?;
9145                if commands.is_empty() && !ctx.matched_recorded_pending()? {
9146                    Err(Error::WorkflowYieldedWithoutCommand)
9147                } else {
9148                    self.message_stream_decision(&ctx, commands)
9149                }
9150            }
9151        }
9152    }
9153
9154    fn message_stream_decision(
9155        &self,
9156        ctx: &WorkflowContext,
9157        commands: Vec<Value>,
9158    ) -> Result<WorkflowTaskDecision> {
9159        if !self.cooperative_cancellation_enabled
9160            && commands.iter().any(|command| {
9161                command["type"] == "schedule_activity"
9162                    && command.get("cancellation_policy").is_some()
9163            })
9164        {
9165            return Err(Error::CooperativeCancellationUnavailable(format!(
9166                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9167                self.worker_id,
9168            )));
9169        }
9170        if !self.cooperative_cancellation_enabled
9171            && commands.iter().any(|command| {
9172                command["type"] == "start_child_workflow"
9173                    && (command["parent_close_policy"] == "request_cancellation"
9174                        || matches!(
9175                            command["cancellation_policy"].as_str(),
9176                            Some("try_cancel" | "wait_cancellation_completed")
9177                        ))
9178            })
9179        {
9180            return Err(Error::CooperativeCancellationUnavailable(format!(
9181                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9182                self.worker_id,
9183            )));
9184        }
9185        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
9186        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9187        let scope_delivery = state
9188            .scope_delivery
9189            .as_ref()
9190            .and_then(|replay| replay.intent.clone());
9191        if scope_delivery
9192            .as_ref()
9193            .is_some_and(|intent| commands.len() != intent.command_count)
9194        {
9195            return Err(invalid_recorded_history(
9196                "cancellation_scope_pending_call_escaped",
9197                scope_delivery.as_ref().unwrap().boundary.sequence,
9198                "commands preceding the pending scoped call",
9199                "commands after suspension",
9200                "workflow cannot publish beyond an uncommitted scope delivery",
9201            ));
9202        }
9203        if let Some(opening) = &state.cancellation_scope_opening {
9204            if commands.len() != opening.command_count {
9205                return Err(invalid_recorded_history(
9206                    "cancellation_scope_pending_call_escaped",
9207                    opening.sequence,
9208                    "commands before original scope opening",
9209                    "commands after suspended opening",
9210                    "workflow cannot publish beyond an uncommitted scope opening",
9211                ));
9212            }
9213        }
9214        if state.cancellation_delivery_intent.is_some()
9215            && commands.len() != state.cancellation_delivery_command_count
9216        {
9217            return Err(invalid_recorded_history(
9218                "cooperative_cancellation_pending_call_escaped",
9219                state
9220                    .cancellation_delivery_intent
9221                    .as_ref()
9222                    .expect("pending delivery")
9223                    .sequence,
9224                "only commands preceding the pending cancellation call",
9225                "commands authored after a suspended call",
9226                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
9227            ));
9228        }
9229        Ok(WorkflowTaskDecision {
9230            commands,
9231            message_stream_cursors,
9232            message_stream_waits,
9233            cancellation_delivery: state.cancellation_delivery_intent.clone(),
9234            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
9235            cancellation_scope_delivery: scope_delivery,
9236        })
9237    }
9238
9239    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
9240        if !self.workflows.contains_key(&task.workflow_type) {
9241            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
9242        }
9243
9244        let accepted = task.history_events.iter().rev().find_map(|event| {
9245            (event.event_type == "UpdateAccepted"
9246                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
9247            .then_some(&event.payload)
9248        });
9249        let update_name = accepted
9250            .and_then(|payload| payload.get("update_name"))
9251            .and_then(Value::as_str)
9252            .or(task.update_name.as_deref())
9253            .unwrap_or_default();
9254        let Some(handler) = self
9255            .updates
9256            .get(&task.workflow_type)
9257            .and_then(|handlers| handlers.get(update_name))
9258        else {
9259            return Ok(vec![json!({
9260                "type": "fail_update",
9261                "update_id": update_id,
9262                "message": format!(
9263                    "no update handler is registered for {}.{update_name}",
9264                    task.workflow_type
9265                ),
9266                "exception_type": "UnknownUpdate",
9267                "non_retryable": true,
9268            })]);
9269        };
9270        let arguments = accepted
9271            .and_then(|payload| payload.get("arguments"))
9272            .or(task.arguments.as_ref());
9273        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9274        let workflow_input_avro_value =
9275            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9276        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9277        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9278        let context = QueryContext {
9279            workflow_id: task.workflow_id.clone(),
9280            run_id: task.run_id.clone(),
9281            workflow_type: task.workflow_type.clone(),
9282            run_status: Some("running".to_string()),
9283            workflow_input,
9284            workflow_input_avro_value,
9285            history_events: Arc::new(task.history_events.clone()),
9286            signal_events: Arc::new(signal_events),
9287        };
9288        let mut future = handler(context, arguments);
9289        let mut cx = TaskContext::from_waker(noop_waker_ref());
9290
9291        match future.as_mut().poll(&mut cx) {
9292            Poll::Ready(Ok(result)) => Ok(vec![json!({
9293                "type": "complete_update",
9294                "update_id": update_id,
9295                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9296            })]),
9297            Poll::Ready(Err(error)) => Ok(vec![json!({
9298                "type": "fail_update",
9299                "update_id": update_id,
9300                "message": error.to_string(),
9301                "exception_type": "UpdateFailed",
9302                "non_retryable": true,
9303            })]),
9304            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9305        }
9306    }
9307
9308    #[cfg(test)]
9309    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9310        self.execute_session_activity_task(task, None, None).await
9311    }
9312
9313    async fn execute_session_activity_task(
9314        &self,
9315        task: ActivityTask,
9316        worker_session: Option<WorkerSession>,
9317        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9318    ) -> Result<AvroValue> {
9319        validate_activity_task_payloads(&task)?;
9320        if worker_session.is_some() {
9321            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
9322                || task
9323                    .activity_attempt_id
9324                    .as_deref()
9325                    .or(task.attempt_id.as_deref())
9326                    .is_none_or(str::is_empty)
9327                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
9328            {
9329                return Err(Error::ActivityExecutionAbandoned(
9330                    "session activity requires this worker's exact immutable claim".into(),
9331                ));
9332            }
9333        }
9334
9335        let handler = self
9336            .activities
9337            .get(&task.activity_type)
9338            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
9339        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9340        let attempt_id = task
9341            .activity_attempt_id
9342            .clone()
9343            .or(task.attempt_id.clone())
9344            .unwrap_or_default();
9345        let lease_owner = task
9346            .lease_owner
9347            .clone()
9348            .unwrap_or_else(|| self.worker_id.clone());
9349        let session = worker_session.clone();
9350        let ctx = ActivityContext {
9351            client: self.client.clone(),
9352            task_id: task.task_id,
9353            activity_attempt_id: attempt_id,
9354            lease_owner,
9355            activity_type: task.activity_type,
9356            attempt_number: task.attempt_number,
9357            task_queue: self.task_queue.clone(),
9358            worker_id: self.worker_id.clone(),
9359            claim_guard: None,
9360            local_heartbeats: None,
9361            worker_session,
9362        };
9363
9364        if let Some(claim) = hydration_claim {
9365            claim.confirm(&self.client).await?;
9366        }
9367        let callback = handler(ctx, args);
9368        if let Some(session) = session {
9369            tokio::select! {
9370                biased;
9371                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
9372                result = callback => if session.active() { result } else {
9373                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
9374                },
9375            }
9376        } else {
9377            callback.await
9378        }
9379    }
9380}
9381
9382fn poller_result(
9383    kind: &str,
9384    result: std::result::Result<Result<()>, tokio::task::JoinError>,
9385) -> Result<()> {
9386    match result {
9387        Ok(result) => result,
9388        Err(error) => Err(Error::WorkerLoop(format!(
9389            "{kind} poller join error: {error}"
9390        ))),
9391    }
9392}
9393
9394fn optional_poller_result(
9395    kind: &str,
9396    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
9397) -> Result<()> {
9398    match result {
9399        Some(result) => poller_result(kind, result),
9400        None => Ok(()),
9401    }
9402}
9403
9404async fn join_pollers(
9405    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9406    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9407    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9408) -> Result<()> {
9409    let mut first_error = None;
9410
9411    if let Some(handle) = workflow_poller {
9412        if let Err(error) = poller_result("workflow", handle.await) {
9413            first_error.get_or_insert(error);
9414        }
9415    }
9416
9417    if let Some(handle) = activity_poller {
9418        if let Err(error) = poller_result("activity", handle.await) {
9419            first_error.get_or_insert(error);
9420        }
9421    }
9422
9423    if let Some(handle) = query_poller {
9424        if let Err(error) = poller_result("query", handle.await) {
9425            first_error.get_or_insert(error);
9426        }
9427    }
9428
9429    if let Some(error) = first_error {
9430        Err(error)
9431    } else {
9432        Ok(())
9433    }
9434}
9435
9436fn default_worker_id() -> String {
9437    let millis = SystemTime::now()
9438        .duration_since(UNIX_EPOCH)
9439        .unwrap_or_default()
9440        .as_millis();
9441    format!("rust-worker-{}-{millis}", std::process::id())
9442}
9443
9444fn percent_encode_path_segment(segment: &str) -> String {
9445    const HEX: &[u8; 16] = b"0123456789ABCDEF";
9446    let mut encoded = String::with_capacity(segment.len());
9447
9448    for byte in segment.bytes() {
9449        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
9450            encoded.push(char::from(byte));
9451        } else {
9452            encoded.push('%');
9453            encoded.push(char::from(HEX[(byte >> 4) as usize]));
9454            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
9455        }
9456    }
9457
9458    encoded
9459}
9460
9461fn unique_request_id(prefix: &str) -> String {
9462    let nanos = SystemTime::now()
9463        .duration_since(UNIX_EPOCH)
9464        .unwrap_or_default()
9465        .as_nanos();
9466    format!("{prefix}-{}-{nanos}", std::process::id())
9467}
9468
9469#[derive(Debug)]
9470struct QueryTaskExecutionFailure {
9471    reason: String,
9472    message: String,
9473    failure_type: String,
9474}
9475
9476impl QueryTaskExecutionFailure {
9477    fn new(
9478        reason: impl Into<String>,
9479        message: impl Into<String>,
9480        failure_type: impl Into<String>,
9481    ) -> Self {
9482        Self {
9483            reason: reason.into(),
9484            message: message.into(),
9485            failure_type: failure_type.into(),
9486        }
9487    }
9488}
9489
9490/// Typed local state owned by one deterministic workflow invocation.
9491///
9492/// Use [`WorkflowInstance::update`] for the same state transitions during
9493/// ordinary execution and replay. A replayed query receives a detached
9494/// immutable `Arc<S>` rather than this mutation-capable handle.
9495#[derive(Clone, Debug)]
9496pub struct WorkflowInstance<S> {
9497    state: Arc<Mutex<S>>,
9498}
9499
9500impl<S> WorkflowInstance<S> {
9501    fn new(state: S) -> Self {
9502        Self {
9503            state: Arc::new(Mutex::new(state)),
9504        }
9505    }
9506
9507    /// Read the current workflow-instance state without changing it.
9508    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
9509        let state = self
9510            .state
9511            .lock()
9512            .map_err(|_| Error::WorkflowStatePoisoned)?;
9513        Ok(reader(&state))
9514    }
9515
9516    /// Apply one deterministic workflow-instance state transition.
9517    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
9518        let mut state = self
9519            .state
9520            .lock()
9521            .map_err(|_| Error::WorkflowStatePoisoned)?;
9522        Ok(transition(&mut state))
9523    }
9524}
9525
9526impl<S: Clone> WorkflowInstance<S> {
9527    fn snapshot(&self) -> Result<S> {
9528        self.read(Clone::clone)
9529    }
9530}
9531
9532#[derive(Clone, Debug, PartialEq)]
9533pub struct MessageStreamMessage {
9534    pub stream_name: String,
9535    pub message_id: String,
9536    pub position: u64,
9537    pub arguments: Vec<AvroValue>,
9538}
9539
9540#[derive(Clone, Debug)]
9541pub struct MessageStream {
9542    ctx: WorkflowContext,
9543    name: String,
9544}
9545
9546impl MessageStream {
9547    /// Wait for one message, then return a bounded currently-available batch.
9548    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
9549        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
9550            return Err(Error::Codec(format!(
9551                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
9552            )));
9553        }
9554        loop {
9555            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
9556                return Ok(batch);
9557            }
9558
9559            self.ctx.record_message_stream_wait(&self.name)?;
9560            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
9561            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
9562            self.ctx.buffer_message_stream_delivery(arguments)?;
9563            if let Some(sequence) = replay_wait_sequence {
9564                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
9565            }
9566        }
9567    }
9568
9569    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
9570        self.receive(1)
9571            .await?
9572            .into_iter()
9573            .next()
9574            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
9575    }
9576}
9577
9578#[derive(Clone, Debug)]
9579pub struct WorkflowContext {
9580    state: Arc<Mutex<WorkflowState>>,
9581    cancellation_scope_id: String,
9582}
9583
9584fn valid_memo_key(key: &str) -> bool {
9585    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
9586
9587    !key.is_empty()
9588        && key.len() <= 64
9589        && (numeric_candidate.is_empty()
9590            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
9591        && key
9592            .bytes()
9593            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
9594}
9595
9596fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
9597    BASE64
9598        .decode(encode_avro_value(value)?.blob)
9599        .map(|bytes| bytes.len())
9600        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
9601}
9602
9603fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
9604    let AvroValue::Map(entries) = value else {
9605        return Err(Error::InvalidMemoUpdate(
9606            "entries must serialize to an Avro string-keyed map".to_string(),
9607        ));
9608    };
9609    if require_entries && entries.is_empty() {
9610        return Err(Error::InvalidMemoUpdate(
9611            "at least one entry is required".to_string(),
9612        ));
9613    }
9614    if entries.len() > MAX_MEMO_ENTRIES {
9615        return Err(Error::InvalidMemoUpdate(format!(
9616            "at most {MAX_MEMO_ENTRIES} entries are allowed"
9617        )));
9618    }
9619
9620    for (key, value) in &entries {
9621        if !valid_memo_key(&key) {
9622            return Err(Error::InvalidMemoUpdate(
9623                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
9624            ));
9625        }
9626        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
9627            return Err(Error::InvalidMemoUpdate(format!(
9628                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
9629            )));
9630        }
9631    }
9632
9633    let value = AvroValue::Map(entries);
9634    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
9635        return Err(Error::InvalidMemoUpdate(format!(
9636            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
9637        )));
9638    }
9639    Ok(value)
9640}
9641
9642fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
9643    let object = envelope.as_object().ok_or_else(|| {
9644        Error::InvalidMemoUpdate(
9645            "history field must use the public {codec, blob} payload envelope".to_string(),
9646        )
9647    })?;
9648    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
9649        return Err(Error::InvalidMemoUpdate(
9650            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
9651        ));
9652    }
9653
9654    canonical_memo_entries(
9655        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
9656        require_entries,
9657    )
9658}
9659
9660impl WorkflowContext {
9661    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
9662        let name = name.into();
9663        if name.is_empty()
9664            || name.len() > 128
9665            || !name.bytes().all(|byte| {
9666                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
9667            })
9668        {
9669            return Err(Error::Codec(
9670                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
9671                    .to_string(),
9672            ));
9673        }
9674        Ok(MessageStream {
9675            ctx: self.clone(),
9676            name,
9677        })
9678    }
9679
9680    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
9681        let mut state = self
9682            .state
9683            .lock()
9684            .map_err(|_| Error::WorkflowStatePoisoned)?;
9685        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9686        state
9687            .message_stream_waits
9688            .insert(name.to_string(), position);
9689        Ok(())
9690    }
9691
9692    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
9693        let mut state = self
9694            .state
9695            .lock()
9696            .map_err(|_| Error::WorkflowStatePoisoned)?;
9697        let cursor = state
9698            .message_stream_cursors
9699            .get(&message.stream_name)
9700            .copied()
9701            .unwrap_or(0);
9702        if message.position <= cursor {
9703            return Ok(());
9704        }
9705        let pending = state
9706            .message_stream_messages
9707            .entry(message.stream_name.clone())
9708            .or_default();
9709        if pending.iter().any(|candidate| {
9710            candidate.position == message.position || candidate.message_id == message.message_id
9711        }) {
9712            return Ok(());
9713        }
9714        pending.push(message);
9715        pending.sort_by_key(|candidate| candidate.position);
9716        Ok(())
9717    }
9718
9719    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
9720        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
9721            match delivery {
9722                MessageStreamDelivery::Message(message) => {
9723                    let stream_name = message.stream_name.clone();
9724                    self.buffer_message_stream(message)?;
9725                    return Ok(Some(stream_name));
9726                }
9727                MessageStreamDelivery::Cursor {
9728                    stream_name,
9729                    through_position,
9730                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
9731            }
9732        }
9733        Ok(None)
9734    }
9735
9736    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
9737        let state = self
9738            .state
9739            .lock()
9740            .map_err(|_| Error::WorkflowStatePoisoned)?;
9741        Ok(match state.recorded_commands.get(state.command_cursor) {
9742            Some(RecordedCommand::SignalWait {
9743                sequence,
9744                signal_name,
9745                ..
9746            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
9747            _ => None,
9748        })
9749    }
9750
9751    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
9752        let (history, payload_codec) = {
9753            let state = self
9754                .state
9755                .lock()
9756                .map_err(|_| Error::WorkflowStatePoisoned)?;
9757            (
9758                Arc::clone(&state.history_events),
9759                state.payload_codec.clone(),
9760            )
9761        };
9762
9763        let Some(opened_index) = history.iter().position(|event| {
9764            event.event_type == "SignalWaitOpened"
9765                && durable_event_sequence(event) == Some(wait_sequence)
9766                && event.payload.get("signal_name").and_then(Value::as_str)
9767                    == Some(MESSAGE_STREAM_SIGNAL)
9768        }) else {
9769            return Ok(());
9770        };
9771        let boundary_index = history
9772            .iter()
9773            .enumerate()
9774            .skip(opened_index + 1)
9775            .find_map(|(index, event)| {
9776                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
9777                    && is_authored_command_open_event(event))
9778                .then_some(index)
9779            })
9780            .unwrap_or(history.len());
9781
9782        for event in history[opened_index + 1..boundary_index]
9783            .iter()
9784            .filter(|event| {
9785                event.event_type == "SignalReceived"
9786                    && event.payload.get("signal_name").and_then(Value::as_str)
9787                        == Some(MESSAGE_STREAM_SIGNAL)
9788            })
9789        {
9790            let arguments = decode_signal_event_arguments(event, &payload_codec)?
9791                .into_iter()
9792                .map(AvroValue::into_json)
9793                .collect::<Result<Vec<_>>>()?;
9794            self.buffer_message_stream_delivery(arguments)?;
9795        }
9796        Ok(())
9797    }
9798
9799    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9800        let mut state = self
9801            .state
9802            .lock()
9803            .map_err(|_| Error::WorkflowStatePoisoned)?;
9804        let cursor = state
9805            .message_stream_cursors
9806            .entry(name.to_string())
9807            .or_default();
9808        *cursor = (*cursor).max(through_position);
9809        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9810            pending.retain(|message| message.position > through_position);
9811        }
9812        Ok(())
9813    }
9814
9815    fn take_message_stream_batch(
9816        &self,
9817        name: &str,
9818        max_items: usize,
9819    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9820        let mut state = self
9821            .state
9822            .lock()
9823            .map_err(|_| Error::WorkflowStatePoisoned)?;
9824        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9825        let pending = state
9826            .message_stream_messages
9827            .entry(name.to_string())
9828            .or_default();
9829        let count = contiguous_message_stream_count(pending, cursor, max_items);
9830        if count == 0 {
9831            return Ok(None);
9832        }
9833        let batch = pending.drain(..count).collect::<Vec<_>>();
9834        let position = batch.last().map(|message| message.position).unwrap_or(0);
9835        state
9836            .message_stream_cursors
9837            .insert(name.to_string(), position);
9838        state.message_stream_waits.remove(name);
9839        Ok(Some(batch))
9840    }
9841
9842    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9843        let state = self
9844            .state
9845            .lock()
9846            .map_err(|_| Error::WorkflowStatePoisoned)?;
9847        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9848        cursors.sort_by_key(|(name, _)| *name);
9849        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9850        waits.sort_by_key(|(name, _)| *name);
9851        Ok((
9852            cursors
9853                .into_iter()
9854                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9855                .collect(),
9856            waits
9857                .into_iter()
9858                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9859                .collect(),
9860        ))
9861    }
9862    /// Identity of the parent workflow currently being replayed.
9863    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9864        let state = self
9865            .state
9866            .lock()
9867            .map_err(|_| Error::WorkflowStatePoisoned)?;
9868        Ok(WorkflowIdentity {
9869            workflow_id: state.workflow_id.clone(),
9870            run_id: state.run_id.clone(),
9871        })
9872    }
9873
9874    /// Return the server-published history budget for this workflow task.
9875    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9876        let state = self
9877            .state
9878            .lock()
9879            .map_err(|_| Error::WorkflowStatePoisoned)?;
9880        Ok(state.history_budget.clone())
9881    }
9882
9883    /// Continue this workflow instance as a fresh run with replacement arguments.
9884    ///
9885    /// Return this value directly from the workflow handler. The worker converts
9886    /// it to the terminal protocol command only after replay has consumed every
9887    /// recorded durable command.
9888    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9889        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9890    }
9891
9892    /// Continue as new with optional workflow-type and task-queue overrides.
9893    pub fn continue_as_new_with_options<T: Serialize>(
9894        &self,
9895        options: ContinueAsNewOptions,
9896        args: T,
9897    ) -> Result<Value> {
9898        options.validate()?;
9899        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9900            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9901            options,
9902        }))
9903    }
9904
9905    pub fn activity<T: Serialize>(
9906        &self,
9907        activity_type: impl Into<String>,
9908        args: T,
9909    ) -> ActivityCall {
9910        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9911    }
9912
9913    pub fn activity_on_queue<T, Q>(
9914        &self,
9915        activity_type: impl Into<String>,
9916        task_queue: Option<Q>,
9917        args: T,
9918    ) -> ActivityCall
9919    where
9920        T: Serialize,
9921        Q: Into<String>,
9922    {
9923        let mut options = ActivityOptions::new();
9924        options.task_queue = task_queue.map(Into::into);
9925        self.activity_with_options(activity_type, options, args)
9926    }
9927
9928    /// Schedule one durable activity with retry, routing, and timeout options.
9929    ///
9930    /// Options are validated before the command is emitted. Once the command is
9931    /// recorded, replay consumes the same activity lifecycle at this command
9932    /// position and never emits a duplicate schedule.
9933    ///
9934    /// ```no_run
9935    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9936    /// # use std::time::Duration;
9937    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9938    /// let result = ctx
9939    ///     .activity_with_options(
9940    ///         "charge-card",
9941    ///         ActivityOptions::new()
9942    ///             .task_queue("payments")
9943    ///             .retry_policy(
9944    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9945    ///                     Duration::from_secs(1),
9946    ///                     2,
9947    ///                     Some(Duration::from_secs(30)),
9948    ///                 ),
9949    ///             )
9950    ///             .start_to_close_timeout(Duration::from_secs(60))
9951    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9952    ///             .heartbeat_timeout(Duration::from_secs(15)),
9953    ///         json!([{"order_id": "order-42"}]),
9954    ///     )
9955    ///     .await;
9956    /// match result {
9957    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9958    ///         "reason": failure.reason,
9959    ///         "timeout_kind": failure.timeout_kind,
9960    ///     })),
9961    ///     other => other,
9962    /// }
9963    /// # }
9964    /// ```
9965    pub fn activity_with_options<T: Serialize>(
9966        &self,
9967        activity_type: impl Into<String>,
9968        options: ActivityOptions,
9969        args: T,
9970    ) -> ActivityCall {
9971        ActivityCall {
9972            ctx: self.clone(),
9973            activity_type: activity_type.into(),
9974            options,
9975            worker_session: None,
9976            args: Some(AvroValue::from_serialize(&args)),
9977            scheduled: false,
9978            local: false,
9979            local_result: None,
9980            parallel_group_path: Vec::new(),
9981        }
9982    }
9983
9984    pub async fn activity_avro_value<T: Serialize>(
9985        &self,
9986        activity_type: impl Into<String>,
9987        args: T,
9988    ) -> Result<AvroValue> {
9989        let mut call = self.activity(activity_type, args);
9990        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9991    }
9992
9993    pub async fn activity_avro_value_with_options<T: Serialize>(
9994        &self,
9995        activity_type: impl Into<String>,
9996        options: ActivityOptions,
9997        args: T,
9998    ) -> Result<AvroValue> {
9999        let mut call = self.activity_with_options(activity_type, options, args);
10000        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10001    }
10002
10003    /// Schedule an activity with a Serde request and decode its Serde result.
10004    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
10005    where
10006        I: Serialize,
10007        O: DeserializeOwned,
10008    {
10009        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
10010            .await
10011    }
10012
10013    /// Schedule an activity with options and decode its result into `O`.
10014    ///
10015    /// Both directions use the fixed Avro Value codec. In particular, this
10016    /// method does not deserialize the JSON-safe inspection projection returned
10017    /// by the dynamic [`ActivityCall`] future.
10018    pub async fn activity_typed_with_options<I, O>(
10019        &self,
10020        activity_type: impl Into<String>,
10021        options: ActivityOptions,
10022        args: I,
10023    ) -> Result<O>
10024    where
10025        I: Serialize,
10026        O: DeserializeOwned,
10027    {
10028        let activity_type = activity_type.into();
10029        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
10030            handler_type_error::<I>(
10031                HandlerKind::Activity,
10032                &activity_type,
10033                HandlerValueKind::Input,
10034                error.to_string(),
10035            )
10036        });
10037        let mut call = ActivityCall {
10038            ctx: self.clone(),
10039            activity_type: activity_type.clone(),
10040            options,
10041            worker_session: None,
10042            args: Some(encoded),
10043            scheduled: false,
10044            local: false,
10045            local_result: None,
10046            parallel_group_path: Vec::new(),
10047        };
10048        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
10049        decode_handler_result(result, HandlerKind::Activity, &activity_type)
10050    }
10051
10052    /// Schedule and join a deterministic activity/child/timer group.
10053    ///
10054    /// Nested groups retain their input shape. Every durable leaf is scheduled
10055    /// before this future yields, results are assembled by declaration order,
10056    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
10057    /// declaration path, stable group metadata, and completed siblings.
10058    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10059        ParallelCall::new(self.clone(), operations)
10060    }
10061
10062    /// Alias for [`WorkflowContext::parallel`].
10063    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10064        self.parallel(operations)
10065    }
10066
10067    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
10068    pub async fn parallel_avro_value(
10069        &self,
10070        operations: Vec<ParallelOperation>,
10071    ) -> Result<Vec<ParallelAvroResult>> {
10072        let mut call = self.parallel(operations);
10073        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10074    }
10075
10076    /// Start every durable operation and resume from the one winner persisted
10077    /// by Server. Non-winning operations continue and remain addressable.
10078    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
10079        let operations = operations
10080            .into_iter()
10081            .enumerate()
10082            .map(|(index, operation)| (SelectionKey::Index(index), operation))
10083            .collect();
10084        SelectCall::new(self.clone(), operations)
10085    }
10086
10087    /// Named-key variant of [`WorkflowContext::select`].
10088    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
10089    where
10090        K: Into<SelectionKey>,
10091    {
10092        SelectCall::new(
10093            self.clone(),
10094            operations
10095                .into_iter()
10096                .map(|(key, operation)| (key.into(), operation))
10097                .collect(),
10098        )
10099    }
10100
10101    /// Create a workflow-local deterministic compensation registry.
10102    pub fn saga(&self) -> Saga {
10103        Saga::new(self.clone())
10104    }
10105
10106    /// Whether cancellation has reached this replay's authored boundary.
10107    ///
10108    /// Server's current `/cancel` route is terminal and does not set this flag.
10109    /// A canonical service request remains pending until its committed delivery
10110    /// is consumed. Request observation alone does not authorize an exception.
10111    pub fn is_cancellation_requested(&self) -> Result<bool> {
10112        let state = self
10113            .state
10114            .lock()
10115            .map_err(|_| Error::WorkflowStatePoisoned)?;
10116        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10117            return Ok(state
10118                .scope_delivery
10119                .as_ref()
10120                .unwrap()
10121                .contexts
10122                .contains_key(&self.cancellation_scope_id));
10123        }
10124        Ok(state.cancel_requested
10125            || state
10126                .scope_delivery
10127                .as_ref()
10128                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
10129    }
10130
10131    /// Raise a typed cooperative cancellation at an author-controlled point.
10132    ///
10133    /// Passing this result to [`Saga::finish`] compensates already registered
10134    /// forward steps before the cancellation remains the initiating outcome.
10135    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
10136        let mut state = self
10137            .state
10138            .lock()
10139            .map_err(|_| Error::WorkflowStatePoisoned)?;
10140        if state.cancellation_shield_depth == 0 {
10141            if let Some(replay) = &state.scope_delivery {
10142                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
10143                    let delivered = replay
10144                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
10145                        .ok_or_else(|| {
10146                            Error::InvalidCooperativeCancellation(
10147                                "scoped request lacks its consumed original delivery".into(),
10148                            )
10149                        })?;
10150                    return Err(Error::CancellationScopeRequested(
10151                        CancellationScopeRequested {
10152                            context: context
10153                                .clone()
10154                                .with_replay(Some(Arc::downgrade(&self.state))),
10155                            delivery: delivered.boundary.clone(),
10156                        },
10157                    ));
10158                }
10159            }
10160        }
10161        if state.cancel_requested && state.cancellation_shield_depth == 0 {
10162            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10163                return Ok(());
10164            }
10165            return Err(state.cancellation_error());
10166        }
10167        Ok(())
10168    }
10169
10170    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10171        SignalCall {
10172            ctx: self.clone(),
10173            signal_name: signal_name.into(),
10174            runtime_reserved_allowed: false,
10175            opened_wait: false,
10176            matched_pending: false,
10177            parallel_group_path: Vec::new(),
10178        }
10179    }
10180
10181    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10182        SignalCall {
10183            ctx: self.clone(),
10184            signal_name: signal_name.into(),
10185            runtime_reserved_allowed: true,
10186            opened_wait: false,
10187            matched_pending: false,
10188            parallel_group_path: Vec::new(),
10189        }
10190    }
10191
10192    pub async fn wait_signal_avro_value(
10193        &self,
10194        signal_name: impl Into<String>,
10195    ) -> Result<Vec<AvroValue>> {
10196        let mut call = self.wait_signal(signal_name);
10197        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10198    }
10199
10200    /// Return every committed signal argument list with the given name.
10201    ///
10202    /// This history-backed view is deterministic and is intended for
10203    /// condition predicates that must be re-evaluated after a signal while the
10204    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10205    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10206        self.signals_avro_value(signal_name)?
10207            .into_iter()
10208            .map(|arguments| {
10209                arguments
10210                    .into_iter()
10211                    .map(AvroValue::into_json)
10212                    .collect::<Result<Vec<_>>>()
10213            })
10214            .collect()
10215    }
10216
10217    /// Lossless fixed Avro Value view of committed signals with the given name.
10218    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10219        let state = self
10220            .state
10221            .lock()
10222            .map_err(|_| Error::WorkflowStatePoisoned)?;
10223        state
10224            .history_events
10225            .iter()
10226            .filter(|event| {
10227                event.event_type == "SignalReceived"
10228                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10229            })
10230            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10231            .collect()
10232    }
10233
10234    /// Return every committed update argument list with the given name.
10235    ///
10236    /// Accepted and applied records for the same update ID are de-duplicated.
10237    /// A Server task created after an update therefore replays the workflow and
10238    /// re-evaluates an open condition without application polling.
10239    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10240        self.updates_avro_value(update_name)?
10241            .into_iter()
10242            .map(|arguments| {
10243                arguments
10244                    .into_iter()
10245                    .map(AvroValue::into_json)
10246                    .collect::<Result<Vec<_>>>()
10247            })
10248            .collect()
10249    }
10250
10251    /// Lossless fixed Avro Value view of committed updates with the given name.
10252    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10253        let state = self
10254            .state
10255            .lock()
10256            .map_err(|_| Error::WorkflowStatePoisoned)?;
10257        let mut seen = Vec::new();
10258        let mut updates = Vec::new();
10259        for event in state.history_events.iter() {
10260            if !matches!(
10261                event.event_type.as_str(),
10262                "UpdateAccepted" | "UpdateApplied"
10263            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
10264                || event.payload.get("arguments").is_none()
10265            {
10266                continue;
10267            }
10268            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
10269                if seen.iter().any(|recorded| recorded == update_id) {
10270                    continue;
10271                }
10272                seen.push(update_id.to_string());
10273            }
10274            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
10275        }
10276        Ok(updates)
10277    }
10278
10279    /// Wait for a deterministic predicate to become true or for its durable
10280    /// timeout to elapse.
10281    ///
10282    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
10283    /// predicate tokens automatically change the recorded definition
10284    /// fingerprint. Direct callers must provide an equally stable identity in
10285    /// [`ConditionWaitOptions`].
10286    pub fn wait_condition<F>(
10287        &self,
10288        options: ConditionWaitOptions,
10289        predicate: F,
10290    ) -> ConditionWaitCall
10291    where
10292        F: Fn() -> Result<bool> + Send + 'static,
10293    {
10294        ConditionWaitCall {
10295            ctx: self.clone(),
10296            options,
10297            predicate: Box::new(predicate),
10298            occurrence_id: None,
10299            opened_wait: false,
10300            parallel_group_path: Vec::new(),
10301        }
10302    }
10303
10304    /// Wait for server-backed durable time without blocking the worker executor.
10305    ///
10306    /// Polling this future emits one `start_timer` command and yields. The
10307    /// server records the deadline, so neither worker nor server restarts reset
10308    /// the wait. Replay resolves the future only from a `TimerScheduled` and
10309    /// `TimerFired` pair at the same position in the shared durable-command
10310    /// stream, with matching sequence, timer identity, and delay. Sub-second
10311    /// durations round up because protocol deadlines use whole seconds.
10312    ///
10313    /// ```no_run
10314    /// # use durable_workflow::{json, Client, Worker};
10315    /// # use std::time::Duration;
10316    /// # fn configure(client: Client) {
10317    /// let mut worker = Worker::new(client, "rust-workers");
10318    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
10319    ///     ctx.sleep(Duration::from_secs(5)).await?;
10320    ///     Ok(json!({"status": "timer fired"}))
10321    /// });
10322    /// # }
10323    /// ```
10324    pub fn sleep(&self, duration: Duration) -> TimerCall {
10325        let delay_seconds = duration
10326            .as_secs()
10327            .checked_add(u64::from(duration.subsec_nanos() > 0));
10328        TimerCall {
10329            ctx: self.clone(),
10330            delay_seconds,
10331            scheduled: false,
10332            matched_pending: false,
10333            parallel_group_path: Vec::new(),
10334        }
10335    }
10336
10337    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
10338    pub fn start_timer(&self, duration: Duration) -> TimerCall {
10339        self.sleep(duration)
10340    }
10341
10342    /// Evaluate a non-deterministic callback once and durably record its typed value.
10343    ///
10344    /// On replay the callback is not invoked: the value is decoded from the
10345    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
10346    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
10347    /// small values that must remain fixed for the lifetime of a workflow run.
10348    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
10349    where
10350        T: Serialize + DeserializeOwned,
10351        F: FnOnce() -> T,
10352    {
10353        {
10354            let mut state = self
10355                .state
10356                .lock()
10357                .map_err(|_| Error::WorkflowStatePoisoned)?;
10358            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10359                return match recorded {
10360                    RecordedCommand::SideEffect { sequence, value } => {
10361                        state.command_cursor += 1;
10362                        value.deserialize().map_err(|error| {
10363                            Error::NonDeterministicReplay(ReplayFailure::new(
10364                                "side_effect_type_mismatch",
10365                                Some(sequence),
10366                                Some(std::any::type_name::<T>().to_string()),
10367                                Some(error.to_string()),
10368                                "recorded side-effect value is incompatible with the requested Rust type",
10369                            ))
10370                        })
10371                    }
10372                    other => Err(command_mismatch(&other, "side effect")),
10373                };
10374            }
10375        }
10376
10377        let value = callback();
10378        let avro_value = AvroValue::from_serialize(&value)?;
10379        let mut state = self
10380            .state
10381            .lock()
10382            .map_err(|_| Error::WorkflowStatePoisoned)?;
10383        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
10384        state.commands.push(json!({
10385            "type": "record_side_effect",
10386            "result": result,
10387        }));
10388        Ok(value)
10389    }
10390
10391    /// Record or replay a lossless fixed Avro Value side effect.
10392    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
10393    where
10394        F: FnOnce() -> AvroValue,
10395    {
10396        {
10397            let mut state = self
10398                .state
10399                .lock()
10400                .map_err(|_| Error::WorkflowStatePoisoned)?;
10401            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10402                return match recorded {
10403                    RecordedCommand::SideEffect { value, .. } => {
10404                        state.command_cursor += 1;
10405                        Ok(value)
10406                    }
10407                    other => Err(command_mismatch(&other, "side effect")),
10408                };
10409            }
10410        }
10411
10412        let value = callback();
10413        let mut state = self
10414            .state
10415            .lock()
10416            .map_err(|_| Error::WorkflowStatePoisoned)?;
10417        let result = encode_typed_envelope(&value, &state.payload_codec)?;
10418        state.commands.push(json!({
10419            "type": "record_side_effect",
10420            "result": result,
10421        }));
10422        Ok(value)
10423    }
10424
10425    /// Append output items at a deterministic workflow command boundary.
10426    ///
10427    /// Stable idempotency keys are derived from the server-provided durable
10428    /// workflow command identity, command ordinal, and item index. Replay
10429    /// consumes the recorded side effect and never emits another append.
10430    pub fn append_workflow_stream(
10431        &self,
10432        stream_name: impl Into<String>,
10433        items: &[WorkflowStreamAppendItem],
10434        max_pending_items: Option<u64>,
10435    ) -> Result<()> {
10436        if items.is_empty() {
10437            return Err(Error::Codec(
10438                "workflow_stream_items_empty: append requires at least one item".to_string(),
10439            ));
10440        }
10441        if max_pending_items == Some(0) {
10442            return Err(Error::Codec(
10443                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
10444                    .to_string(),
10445            ));
10446        }
10447        let stream_name = stream_name.into();
10448        if stream_name.is_empty() {
10449            return Err(Error::Codec(
10450                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10451            ));
10452        }
10453
10454        let mut state = self
10455            .state
10456            .lock()
10457            .map_err(|_| Error::WorkflowStatePoisoned)?;
10458        let command_ordinal = state.workflow_stream_command_counter;
10459        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10460            state.workflow_stream_command_counter += 1;
10461            return match recorded {
10462                RecordedCommand::SideEffect { .. } => {
10463                    state.command_cursor += 1;
10464                    Ok(())
10465                }
10466                other => Err(command_mismatch(&other, "workflow stream append")),
10467            };
10468        }
10469
10470        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10471        state.workflow_stream_command_counter += 1;
10472        let wire_items = items
10473            .iter()
10474            .enumerate()
10475            .map(|(item_index, item)| {
10476                item.wire_value(Some(format!(
10477                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
10478                )))
10479            })
10480            .collect::<Vec<_>>();
10481        let mut directive = json!({
10482            "operation": "append",
10483            "stream_name": stream_name,
10484            "command_identity": identity,
10485            "command_ordinal": command_ordinal,
10486            "items": wire_items,
10487        });
10488        if let Some(max_pending_items) = max_pending_items {
10489            directive["max_pending_items"] = json!(max_pending_items);
10490        }
10491        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10492        state.commands.push(json!({
10493            "type": "record_side_effect",
10494            "result": result,
10495            "workflow_stream": directive,
10496        }));
10497        Ok(())
10498    }
10499
10500    /// Close a run-scoped output stream at a deterministic command boundary.
10501    pub fn close_workflow_stream(
10502        &self,
10503        stream_name: impl Into<String>,
10504        retention_seconds: Option<u64>,
10505    ) -> Result<()> {
10506        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
10507    }
10508
10509    /// Mark a run-scoped output stream errored at a deterministic command boundary.
10510    pub fn error_workflow_stream(
10511        &self,
10512        stream_name: impl Into<String>,
10513        error_reason: impl Into<String>,
10514        retention_seconds: Option<u64>,
10515    ) -> Result<()> {
10516        let error_reason = error_reason.into();
10517        if error_reason.is_empty() {
10518            return Err(Error::Codec(
10519                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
10520            ));
10521        }
10522        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
10523    }
10524
10525    fn finish_workflow_stream(
10526        &self,
10527        stream_name: String,
10528        error_reason: Option<String>,
10529        retention_seconds: Option<u64>,
10530    ) -> Result<()> {
10531        if stream_name.is_empty() {
10532            return Err(Error::Codec(
10533                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10534            ));
10535        }
10536        if retention_seconds == Some(0) {
10537            return Err(Error::Codec(
10538                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
10539            ));
10540        }
10541        let mut state = self
10542            .state
10543            .lock()
10544            .map_err(|_| Error::WorkflowStatePoisoned)?;
10545        let command_ordinal = state.workflow_stream_command_counter;
10546        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10547            state.workflow_stream_command_counter += 1;
10548            return match recorded {
10549                RecordedCommand::SideEffect { .. } => {
10550                    state.command_cursor += 1;
10551                    Ok(())
10552                }
10553                other => Err(command_mismatch(&other, "workflow stream close")),
10554            };
10555        }
10556        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10557        state.workflow_stream_command_counter += 1;
10558        let mut directive = json!({
10559            "operation": if error_reason.is_some() { "error" } else { "close" },
10560            "stream_name": stream_name,
10561            "command_identity": identity,
10562            "command_ordinal": command_ordinal,
10563        });
10564        if let Some(error_reason) = error_reason {
10565            directive["error_reason"] = json!(error_reason);
10566        }
10567        if let Some(retention_seconds) = retention_seconds {
10568            directive["retention_seconds"] = json!(retention_seconds);
10569        }
10570        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10571        state.commands.push(json!({
10572            "type": "record_side_effect",
10573            "result": result,
10574            "workflow_stream": directive,
10575        }));
10576        Ok(())
10577    }
10578
10579    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
10580        let identity = state.workflow_command_identity.as_str();
10581        if identity.is_empty() {
10582            return Err(Error::MissingWorkflowCommandIdentity);
10583        }
10584        Ok(identity)
10585    }
10586
10587    /// Validate, emit, or replay a typed workflow search-attribute update.
10588    ///
10589    /// The command is non-blocking within a workflow decision, but its
10590    /// `SearchAttributesUpserted` event occupies the same deterministic command
10591    /// stream as activities, timers, conditions, and other durable operations.
10592    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
10593        update.validate()?;
10594        let (attributes, attribute_types) = update.into_wire_parts();
10595        let mut state = self
10596            .state
10597            .lock()
10598            .map_err(|_| Error::WorkflowStatePoisoned)?;
10599
10600        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10601            return match recorded {
10602                RecordedCommand::SearchAttributes {
10603                    sequence,
10604                    attributes: recorded_attributes,
10605                    attribute_types: recorded_attribute_types,
10606                } => {
10607                    if recorded_attributes != attributes {
10608                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10609                            "search_attribute_value_mismatch",
10610                            Some(sequence),
10611                            Some(recorded_attributes.to_string()),
10612                            Some(attributes.to_string()),
10613                            "search-attribute values differ from the recorded durable command",
10614                        )));
10615                    }
10616                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
10617                        if recorded_types != attribute_types {
10618                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10619                                "search_attribute_type_mismatch",
10620                                Some(sequence),
10621                                Some(json!(recorded_types).to_string()),
10622                                Some(json!(attribute_types).to_string()),
10623                                "search-attribute declared types differ from the recorded durable command",
10624                            )));
10625                        }
10626                    }
10627                    state.command_cursor += 1;
10628                    Ok(())
10629                }
10630                other => Err(command_mismatch(&other, "search-attribute update")),
10631            };
10632        }
10633
10634        let mut command = serde_json::Map::from_iter([
10635            ("type".to_string(), json!("upsert_search_attributes")),
10636            ("attributes".to_string(), attributes),
10637        ]);
10638        if !attribute_types.is_empty() {
10639            command.insert("attribute_types".to_string(), json!(attribute_types));
10640        }
10641        state.commands.push(Value::Object(command));
10642        Ok(())
10643    }
10644
10645    /// Record a UUIDv4 once and return the same UUID on every replay.
10646    pub fn uuid_v4(&self) -> Result<Uuid> {
10647        self.side_effect(Uuid::new_v4)
10648    }
10649
10650    /// Select the newest supported version for a change, or replay the version
10651    /// already committed for that stable change ID.
10652    ///
10653    /// An unmarked old history that reached its next durable operation, or
10654    /// already completed, selects `-1` when that version is supported. This
10655    /// leaves the original operation available and writes no additional marker.
10656    /// Consistent markers written by older workers retain their original ordered
10657    /// positions. Repeated calls consume a matching marker at the current cursor.
10658    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
10659    pub fn get_version(
10660        &self,
10661        change_id: impl Into<String>,
10662        min_supported: i32,
10663        max_supported: i32,
10664    ) -> Result<i32> {
10665        let change_id = change_id.into();
10666        if change_id.trim().is_empty() {
10667            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10668                "version_change_id_invalid",
10669                None,
10670                Some("non-empty change ID".to_string()),
10671                Some(change_id),
10672                "version markers require a stable non-empty change ID",
10673            )));
10674        }
10675        if min_supported > max_supported {
10676            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10677                "version_range_invalid",
10678                None,
10679                Some("min_supported <= max_supported".to_string()),
10680                Some(format!("{min_supported}..={max_supported}")),
10681                "version marker supported range is invalid",
10682            )));
10683        }
10684
10685        let mut state = self
10686            .state
10687            .lock()
10688            .map_err(|_| Error::WorkflowStatePoisoned)?;
10689        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
10690            if let Some(RecordedCommand::VersionMarker {
10691                sequence: alias_sequence,
10692                change_id: alias_change_id,
10693                version: alias_version,
10694            }) = state.recorded_commands.get(state.command_cursor)
10695            {
10696                if alias_change_id == &change_id {
10697                    if *alias_version != version {
10698                        return Err(invalid_recorded_history(
10699                            "version_marker_conflict",
10700                            *alias_sequence,
10701                            &format!("selected version {version} for change ID {change_id:?}"),
10702                            &format!("recorded version {alias_version}"),
10703                            "recorded marker conflicts with the decision already selected during replay",
10704                        ));
10705                    }
10706                    ensure_version_supported(
10707                        &change_id,
10708                        version,
10709                        min_supported,
10710                        max_supported,
10711                        *alias_sequence,
10712                    )?;
10713                    // Older workers could record the same decision again. Keep
10714                    // each physical boundary without skipping intervening work.
10715                    state.command_cursor += 1;
10716                    return Ok(version);
10717                }
10718            }
10719            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
10720            return Ok(version);
10721        }
10722
10723        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10724            return match recorded {
10725                RecordedCommand::VersionMarker {
10726                    sequence,
10727                    change_id: recorded_change_id,
10728                    version,
10729                    ..
10730                } => {
10731                    if recorded_change_id != change_id {
10732                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10733                            "version_change_id_mismatch",
10734                            Some(sequence),
10735                            Some(recorded_change_id),
10736                            Some(change_id),
10737                            "recorded version marker change ID differs from current workflow code",
10738                        )));
10739                    }
10740                    ensure_version_supported(
10741                        &change_id,
10742                        version,
10743                        min_supported,
10744                        max_supported,
10745                        sequence,
10746                    )?;
10747                    state.command_cursor += 1;
10748                    state.version_markers.insert(change_id, (version, sequence));
10749                    Ok(version)
10750                }
10751                other => {
10752                    let version = -1;
10753                    let sequence = other.sequence();
10754                    ensure_version_supported(
10755                        &change_id,
10756                        version,
10757                        min_supported,
10758                        max_supported,
10759                        sequence,
10760                    )?;
10761                    // The existing operation proves this patch site was reached
10762                    // before its marker existed. Keep its original cursor.
10763                    state.version_markers.insert(change_id, (version, sequence));
10764                    Ok(version)
10765                }
10766            };
10767        }
10768
10769        if state
10770            .history_events
10771            .iter()
10772            .any(|event| event.event_type == "WorkflowCompleted")
10773        {
10774            let version = -1;
10775            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
10776            state.version_markers.insert(change_id, (version, 0));
10777            return Ok(version);
10778        }
10779
10780        let version = max_supported;
10781        state.commands.push(json!({
10782            "type": "record_version_marker",
10783            "change_id": change_id,
10784            "version": version,
10785            "min_supported": min_supported,
10786            "max_supported": max_supported,
10787        }));
10788        // Sequence numbers are assigned by the server. Zero identifies a marker
10789        // selected in this uncommitted decision batch for duplicate-call checks.
10790        state.version_markers.insert(change_id, (version, 0));
10791        Ok(version)
10792    }
10793
10794    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
10795    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
10796        Ok(self.get_version(change_id, -1, 1)? == 1)
10797    }
10798
10799    /// Keep a patch marker in history after the legacy branch has been removed.
10800    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
10801        self.get_version(change_id, -1, 1).map(|_| ())
10802    }
10803
10804    /// Merge non-indexed workflow memo metadata through durable history.
10805    ///
10806    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
10807    /// public Avro payload envelope consumed by Server and Cloud runtimes.
10808    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
10809        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
10810        let mut state = self
10811            .state
10812            .lock()
10813            .map_err(|_| Error::WorkflowStatePoisoned)?;
10814
10815        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10816            return match recorded {
10817                RecordedCommand::Memo {
10818                    sequence,
10819                    entries: recorded_entries,
10820                } => {
10821                    if recorded_entries != entries {
10822                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10823                            "memo_update_mismatch",
10824                            Some(sequence),
10825                            Some(format!("{recorded_entries:?}")),
10826                            Some(format!("{entries:?}")),
10827                            "recorded memo entries differ from the current workflow update",
10828                        )));
10829                    }
10830                    state.command_cursor += 1;
10831                    Ok(())
10832                }
10833                other => Err(command_mismatch(&other, "memo upsert")),
10834            };
10835        }
10836
10837        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
10838        state.commands.push(json!({
10839            "type": "upsert_memo",
10840            "entries": entries_envelope,
10841        }));
10842        Ok(())
10843    }
10844
10845    /// Start a named durable child on an explicit queue and await its result.
10846    ///
10847    /// The command is recorded in the parent's sequence-ordered durable command
10848    /// stream. Replay keeps a scheduled child pending without emitting another
10849    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
10850    /// values preserve the history payload codec and include both sides of the
10851    /// durable relationship; failures are returned as
10852    /// [`Error::ChildWorkflowFailed`].
10853    ///
10854    /// ```no_run
10855    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10856    /// # fn configure(client: Client) {
10857    /// let mut worker = Worker::new(client, "parent-workers");
10858    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10859    ///     let child = ctx
10860    ///         .start_child_workflow(
10861    ///             "fulfil-order",
10862    ///             ChildWorkflowOptions::new("fulfilment-workers")
10863    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10864    ///             json!([{"order_id": "order-42"}]),
10865    ///         )
10866    ///         .await?;
10867    ///     Ok(child.result)
10868    /// });
10869    /// # }
10870    /// ```
10871    pub fn start_child_workflow<T: Serialize>(
10872        &self,
10873        workflow_type: impl Into<String>,
10874        options: ChildWorkflowOptions,
10875        args: T,
10876    ) -> ChildWorkflowCall {
10877        ChildWorkflowCall {
10878            ctx: self.clone(),
10879            workflow_type: workflow_type.into(),
10880            options,
10881            args: Some(AvroValue::from_serialize(&args)),
10882            scheduled: false,
10883            matched_pending: false,
10884            parallel_group_path: Vec::new(),
10885        }
10886    }
10887
10888    pub async fn start_child_workflow_avro_value<T: Serialize>(
10889        &self,
10890        workflow_type: impl Into<String>,
10891        options: ChildWorkflowOptions,
10892        args: T,
10893    ) -> Result<ChildWorkflowAvroResult> {
10894        let mut call = self.start_child_workflow(workflow_type, options, args);
10895        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10896    }
10897
10898    fn take_commands(&self) -> Result<Vec<Value>> {
10899        let mut state = self
10900            .state
10901            .lock()
10902            .map_err(|_| Error::WorkflowStatePoisoned)?;
10903        Ok(std::mem::take(&mut state.commands))
10904    }
10905
10906    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10907        let mut state = self
10908            .state
10909            .lock()
10910            .map_err(|_| Error::WorkflowStatePoisoned)?;
10911
10912        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10913            return Err(command_mismatch(&recorded, "continue as new"));
10914        }
10915        if state.recorded_continue_as_new_sequence.is_some() {
10916            state.continue_as_new_consumed = true;
10917            return Ok(None);
10918        }
10919
10920        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10921        let mut command = serde_json::Map::from_iter([
10922            ("type".to_string(), json!("continue_as_new")),
10923            ("arguments".to_string(), arguments),
10924            ("queue".to_string(), json!(state.task_queue.clone())),
10925        ]);
10926        if let Some(workflow_type) = request.options.workflow_type {
10927            command.insert("workflow_type".to_string(), json!(workflow_type));
10928        }
10929        if let Some(task_queue) = request.options.task_queue {
10930            command.insert("queue".to_string(), json!(task_queue));
10931        }
10932        Ok(Some(Value::Object(command)))
10933    }
10934
10935    fn matched_recorded_pending(&self) -> Result<bool> {
10936        let state = self
10937            .state
10938            .lock()
10939            .map_err(|_| Error::WorkflowStatePoisoned)?;
10940        Ok(state.matched_recorded_pending)
10941    }
10942
10943    fn ensure_history_consumed(&self) -> Result<()> {
10944        let state = self
10945            .state
10946            .lock()
10947            .map_err(|_| Error::WorkflowStatePoisoned)?;
10948        if let Some(replay) = &state.scope_delivery {
10949            if let Some((&sequence, _)) = replay
10950                .canonical
10951                .deliveries
10952                .iter()
10953                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10954            {
10955                return Err(invalid_recorded_history(
10956                    "cancellation_scope_delivery_unconsumed",
10957                    sequence,
10958                    "original scoped delivery",
10959                    "workflow completion",
10960                    "workflow completed without consuming its committed scope delivery",
10961                ));
10962            }
10963        }
10964        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10965            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10966                "recorded_commands_unconsumed",
10967                Some(command.sequence()),
10968                Some(command.shape().to_string()),
10969                Some("workflow completion".to_string()),
10970                "workflow completed before consuming all recorded durable commands",
10971            )));
10972        }
10973        if let Some(delivery) = state
10974            .cancellation_history
10975            .delivery
10976            .as_ref()
10977            .filter(|_| !state.cancellation_consumed)
10978        {
10979            return Err(invalid_recorded_history(
10980                "cooperative_cancellation_unconsumed",
10981                delivery.sequence,
10982                "committed cancellation call",
10983                "workflow completion",
10984                "workflow completed without reaching its committed cancellation boundary",
10985            ));
10986        }
10987        if let Some(sequence) = state
10988            .recorded_continue_as_new_sequence
10989            .filter(|_| !state.continue_as_new_consumed)
10990        {
10991            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10992                "recorded_continue_as_new_unconsumed",
10993                Some(sequence),
10994                Some("continue as new".to_string()),
10995                Some("workflow completion".to_string()),
10996                "workflow completed without consuming its recorded continue-as-new transition",
10997            )));
10998        }
10999        Ok(())
11000    }
11001}
11002
11003fn contiguous_message_stream_count(
11004    pending: &[MessageStreamMessage],
11005    cursor: u64,
11006    max_items: usize,
11007) -> usize {
11008    pending
11009        .iter()
11010        .take(max_items)
11011        .enumerate()
11012        .take_while(|(offset, message)| {
11013            u64::try_from(*offset)
11014                .ok()
11015                .and_then(|offset| cursor.checked_add(offset + 1))
11016                == Some(message.position)
11017        })
11018        .count()
11019}
11020
11021fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
11022    matches!(
11023        event.event_type.as_str(),
11024        "ActivityScheduled"
11025            | "TimerScheduled"
11026            | "ChildWorkflowScheduled"
11027            | "SignalWaitOpened"
11028            | "ConditionWaitOpened"
11029            | "SearchAttributesUpserted"
11030            | "SideEffectRecorded"
11031            | "VersionMarkerRecorded"
11032            | "MemoUpserted"
11033            | "WorkflowContinuedAsNew"
11034    )
11035}
11036
11037#[derive(Debug)]
11038struct WorkflowState {
11039    workflow_id: Option<String>,
11040    run_id: Option<String>,
11041    task_queue: String,
11042    payload_codec: String,
11043    history_events: Arc<Vec<HistoryEvent>>,
11044    history_budget: WorkflowHistoryBudget,
11045    cancel_requested: bool,
11046    cancellation_history: CancellationHistory,
11047    cancellation_consumed: bool,
11048    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
11049    cancellation_shield_depth: u64,
11050    cancellation_delivery_enabled: bool,
11051    cancellation_delivery_intent: Option<CancellationDelivery>,
11052    cancellation_delivery_command_count: usize,
11053    allow_cancellation_scope_authoring: bool,
11054    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
11055    cancellation_scope_memberships: BTreeMap<u64, String>,
11056    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
11057    resume_signal: Option<ResumeSignal>,
11058    recorded_commands: Vec<RecordedCommand>,
11059    selection_markers: Vec<SelectionMarker>,
11060    selection_marker_cursor: usize,
11061    cancelled_selection_members: Vec<SelectionCancellation>,
11062    recorded_continue_as_new_sequence: Option<u64>,
11063    continue_as_new_consumed: bool,
11064    command_cursor: usize,
11065    condition_wait_occurrence_counter: u64,
11066    matched_recorded_pending: bool,
11067    version_markers: HashMap<String, (i32, u64)>,
11068    workflow_command_identity: String,
11069    workflow_stream_command_counter: u64,
11070    commands: Vec<Value>,
11071    local_activity_requests: Vec<local_activity::Request>,
11072    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
11073    message_stream_cursors: HashMap<String, u64>,
11074    message_stream_waits: HashMap<String, u64>,
11075}
11076
11077impl WorkflowState {
11078    #[cfg(test)]
11079    fn new(
11080        history: Vec<HistoryEvent>,
11081        task_queue: String,
11082        payload_codec: String,
11083        resume_signal: Option<ResumeSignal>,
11084    ) -> Result<Self> {
11085        Self::new_with_identity(
11086            history,
11087            None,
11088            None,
11089            task_queue,
11090            payload_codec,
11091            resume_signal,
11092        )
11093    }
11094
11095    fn new_with_identity(
11096        history: Vec<HistoryEvent>,
11097        workflow_id: Option<String>,
11098        run_id: Option<String>,
11099        task_queue: String,
11100        payload_codec: String,
11101        resume_signal: Option<ResumeSignal>,
11102    ) -> Result<Self> {
11103        Self::new_with_identity_and_scopes(
11104            history,
11105            workflow_id,
11106            run_id,
11107            task_queue,
11108            payload_codec,
11109            resume_signal,
11110            false,
11111        )
11112    }
11113
11114    fn new_with_identity_and_scopes(
11115        history: Vec<HistoryEvent>,
11116        workflow_id: Option<String>,
11117        run_id: Option<String>,
11118        task_queue: String,
11119        payload_codec: String,
11120        resume_signal: Option<ResumeSignal>,
11121        allow_cancellation_scope_authoring: bool,
11122    ) -> Result<Self> {
11123        Self::new_with_identity_and_scope_delivery(
11124            history,
11125            workflow_id,
11126            run_id,
11127            task_queue,
11128            payload_codec,
11129            resume_signal,
11130            allow_cancellation_scope_authoring,
11131            false,
11132        )
11133    }
11134
11135    fn new_with_identity_and_scope_delivery(
11136        history: Vec<HistoryEvent>,
11137        workflow_id: Option<String>,
11138        run_id: Option<String>,
11139        task_queue: String,
11140        payload_codec: String,
11141        resume_signal: Option<ResumeSignal>,
11142        allow_cancellation_scope_authoring: bool,
11143        allow_cancellation_scope_delivery: bool,
11144    ) -> Result<Self> {
11145        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11146            &history,
11147            allow_cancellation_scope_authoring,
11148            allow_cancellation_scope_delivery,
11149        )?;
11150        let scopes = if allow_cancellation_scope_authoring {
11151            cancellation_scope::CancellationScopeHistory::read(
11152                &history,
11153                run_id.as_deref().unwrap_or_default(),
11154            )?
11155        } else {
11156            cancellation_scope::CancellationScopeHistory::default()
11157        };
11158        let cancellation_history = CancellationHistory::from_events(
11159            &history,
11160            run_id.as_deref().unwrap_or_default(),
11161            None,
11162        )?;
11163        if allow_cancellation_scope_authoring
11164            && cancellation_history.request.is_some()
11165            && !allow_cancellation_scope_delivery
11166        {
11167            return Err(Error::CancellationScopeExecutionUnavailable);
11168        }
11169        let scope_delivery = if allow_cancellation_scope_delivery {
11170            Some(cancellation_scope_replay::ScopeReplay::read(
11171                &history,
11172                &scopes,
11173                run_id.as_deref().unwrap_or_default(),
11174                workflow_id.as_deref().unwrap_or_default(),
11175            )?)
11176        } else {
11177            None
11178        };
11179        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
11180            &history,
11181            &payload_codec,
11182            WorkflowIdentity {
11183                workflow_id: workflow_id.clone(),
11184                run_id: run_id.clone(),
11185            },
11186        )?)?;
11187        for (sequence, opening) in &scopes.openings {
11188            if recorded_commands
11189                .iter()
11190                .any(|command| command.sequence() == *sequence)
11191            {
11192                return Err(invalid_recorded_history(
11193                    "invalid_cancellation_scope_history",
11194                    *sequence,
11195                    "distinct authored scope opening",
11196                    "operation collision",
11197                    "scope opening collides with a command",
11198                ));
11199            }
11200            recorded_commands.push(RecordedCommand::CancellationScope {
11201                sequence: *sequence,
11202                scope_id: opening.scope_id.clone(),
11203                parent_scope_id: opening.parent_scope_id.clone(),
11204                shield_parent: opening.shield_parent,
11205            });
11206        }
11207        recorded_commands.sort_by_key(RecordedCommand::sequence);
11208        if let Some(replay) = &scope_delivery {
11209            replay.bind_commands(&mut recorded_commands)?;
11210        }
11211        let selection_markers = recorded_selection_markers(&history)?;
11212        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11213        let recorded_continue_as_new = history
11214            .iter()
11215            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11216            .collect::<Vec<_>>();
11217        if recorded_continue_as_new.len() > 1 {
11218            return Err(invalid_recorded_history(
11219                "duplicate_continue_as_new_transition",
11220                recorded_continue_as_new
11221                    .last()
11222                    .and_then(|event| durable_event_sequence(event))
11223                    .unwrap_or(0),
11224                "one WorkflowContinuedAsNew event",
11225                &format!(
11226                    "{} WorkflowContinuedAsNew events",
11227                    recorded_continue_as_new.len()
11228                ),
11229                "workflow history records one continue-as-new transition more than once",
11230            ));
11231        }
11232        let recorded_continue_as_new_sequence = recorded_continue_as_new
11233            .first()
11234            .map(|event| {
11235                durable_event_sequence(event).ok_or_else(|| {
11236                    Error::NonDeterministicReplay(ReplayFailure::new(
11237                        "continue_as_new_sequence_missing",
11238                        None,
11239                        Some("recorded transition sequence".to_string()),
11240                        Some("missing sequence".to_string()),
11241                        "WorkflowContinuedAsNew history is missing its recorded sequence",
11242                    ))
11243                })
11244            })
11245            .transpose()?;
11246        let mut message_stream_cursors = HashMap::new();
11247        for event in &history {
11248            if !matches!(
11249                event.event_type.as_str(),
11250                "SignalReceived" | "SignalApplied"
11251            ) || event.payload.get("signal_name").and_then(Value::as_str)
11252                != Some(MESSAGE_STREAM_SIGNAL)
11253            {
11254                continue;
11255            }
11256            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
11257            if arguments.len() != 1 {
11258                continue;
11259            }
11260            let envelope = arguments[0].clone().into_json()?;
11261            let Some(envelope) = envelope.as_object() else {
11262                continue;
11263            };
11264            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
11265            {
11266                continue;
11267            }
11268            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11269                continue;
11270            };
11271            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11272            else {
11273                continue;
11274            };
11275            let cursor = message_stream_cursors
11276                .entry(stream_name.to_string())
11277                .or_insert(0);
11278            *cursor = (*cursor).max(through_position);
11279        }
11280        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
11281        let cancel_requested = history.iter().any(|event| {
11282            matches!(
11283                event.event_type.as_str(),
11284                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
11285            )
11286        });
11287        let cancellation_clock = cancellation_history
11288            .request
11289            .as_ref()
11290            .and_then(|request| request.context.as_ref())
11291            .map(|_| {
11292                cancellation_replay_clock::ReplayClock::new(
11293                    &history,
11294                    &recorded_commands,
11295                    cancellation_history.delivery_index,
11296                )
11297            })
11298            .or_else(|| {
11299                scope_delivery.as_ref().map(|_| {
11300                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
11301                })
11302            });
11303        Ok(Self {
11304            workflow_command_identity: String::new(),
11305            workflow_stream_command_counter: 0,
11306            workflow_id,
11307            run_id,
11308            task_queue,
11309            payload_codec,
11310            history_events: Arc::new(history),
11311            history_budget: WorkflowHistoryBudget {
11312                event_count,
11313                ..WorkflowHistoryBudget::default()
11314            },
11315            cancel_requested,
11316            cancellation_history,
11317            cancellation_consumed: false,
11318            cancellation_clock,
11319            cancellation_shield_depth: 0,
11320            cancellation_delivery_enabled: false,
11321            cancellation_delivery_intent: None,
11322            cancellation_delivery_command_count: 0,
11323            allow_cancellation_scope_authoring,
11324            cancellation_scope_opening: None,
11325            cancellation_scope_memberships: scopes.memberships,
11326            scope_delivery,
11327            resume_signal,
11328            recorded_commands,
11329            selection_markers,
11330            selection_marker_cursor: 0,
11331            cancelled_selection_members,
11332            recorded_continue_as_new_sequence,
11333            continue_as_new_consumed: false,
11334            command_cursor: 0,
11335            condition_wait_occurrence_counter: 0,
11336            matched_recorded_pending: false,
11337            version_markers: HashMap::new(),
11338            commands: Vec::new(),
11339            local_activity_requests: Vec::new(),
11340            message_stream_messages: HashMap::new(),
11341            message_stream_cursors,
11342            message_stream_waits: HashMap::new(),
11343        })
11344    }
11345}
11346
11347enum MessageStreamDelivery {
11348    Message(MessageStreamMessage),
11349    Cursor {
11350        stream_name: String,
11351        through_position: u64,
11352    },
11353}
11354
11355fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
11356    if arguments.len() != 1 {
11357        return Ok(None);
11358    }
11359    let envelope = arguments
11360        .into_iter()
11361        .next()
11362        .expect("one argument was checked");
11363    let Some(envelope) = envelope.as_object() else {
11364        return Ok(None);
11365    };
11366    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11367        return Ok(None);
11368    };
11369    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
11370        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11371        else {
11372            return Ok(None);
11373        };
11374        return Ok(Some(MessageStreamDelivery::Cursor {
11375            stream_name: stream_name.to_string(),
11376            through_position,
11377        }));
11378    }
11379    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
11380        return Ok(None);
11381    }
11382    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
11383        return Ok(None);
11384    };
11385    let Some(position) = envelope
11386        .get("position")
11387        .and_then(Value::as_u64)
11388        .filter(|value| *value > 0)
11389    else {
11390        return Ok(None);
11391    };
11392    let Some(payload_envelope) = envelope.get("payload_envelope") else {
11393        return Ok(None);
11394    };
11395    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
11396    else {
11397        return Ok(None);
11398    };
11399    let decoded = decode_avro_value(&payload_envelope)?;
11400    let AvroValue::Array(values) = decoded else {
11401        return Ok(None);
11402    };
11403    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
11404        stream_name: stream_name.to_string(),
11405        message_id: message_id.to_string(),
11406        position,
11407        arguments: values,
11408    })))
11409}
11410
11411#[derive(Clone, Debug)]
11412enum RecordedCommand {
11413    CancellationScope {
11414        sequence: u64,
11415        scope_id: String,
11416        parent_scope_id: String,
11417        shield_parent: bool,
11418    },
11419    CancellationGroup {
11420        sequence: u64,
11421        span: u64,
11422        original: Vec<RecordedCommand>,
11423    },
11424    CancellationBoundary {
11425        sequence: u64,
11426        call_kind: CancellationCallKind,
11427        original: Option<Box<RecordedCommand>>,
11428    },
11429    Activity {
11430        sequence: u64,
11431        activity_type: Option<String>,
11432        cancellation_policy: String,
11433        options: Option<RecordedActivityOptions>,
11434        outcome: Option<ActivityOutcome>,
11435        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11436    },
11437    Timer {
11438        sequence: u64,
11439        delay_seconds: u64,
11440        fired: bool,
11441        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11442    },
11443    ChildWorkflow {
11444        sequence: u64,
11445        workflow_type: Option<String>,
11446        policies: RecordedChildPolicies,
11447        outcome: Option<ChildWorkflowOutcome>,
11448        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11449    },
11450    SignalWait {
11451        sequence: u64,
11452        signal_name: String,
11453        value: Option<Vec<AvroValue>>,
11454        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11455    },
11456    ConditionWait {
11457        sequence: u64,
11458        occurrence_id: String,
11459        condition_key: Option<String>,
11460        predicate_identity: String,
11461        timeout_seconds: Option<u64>,
11462        result: Option<ConditionWaitResult>,
11463        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11464    },
11465    SearchAttributes {
11466        sequence: u64,
11467        attributes: Value,
11468        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
11469    },
11470    SideEffect {
11471        sequence: u64,
11472        value: AvroValue,
11473    },
11474    VersionMarker {
11475        sequence: u64,
11476        change_id: String,
11477        version: i32,
11478    },
11479    Memo {
11480        sequence: u64,
11481        entries: AvroValue,
11482    },
11483}
11484
11485#[derive(Clone, Debug, PartialEq, Eq)]
11486struct SelectionMarker {
11487    selection_group_id: String,
11488    selection_group_base_sequence: u64,
11489    selection_group_size: usize,
11490    member_key: SelectionKey,
11491    member_index: usize,
11492    member_base_sequence: u64,
11493    member_size: usize,
11494    operation_kind: String,
11495    operation_identity: String,
11496    outcome: String,
11497    resolution_event_id: String,
11498    resolution_event_type: String,
11499}
11500
11501#[derive(Clone, Debug, PartialEq, Eq)]
11502struct SelectionCancellation {
11503    selection_group_id: String,
11504    member_key: SelectionKey,
11505    member_index: usize,
11506    member_base_sequence: u64,
11507    member_size: usize,
11508    operation_kind: String,
11509    operation_identity: String,
11510}
11511
11512fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
11513    let mut markers: Vec<SelectionMarker> = Vec::new();
11514    for event in events
11515        .iter()
11516        .filter(|event| event.event_type == "SelectionResolved")
11517    {
11518        let payload = &event.payload;
11519        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
11520        let group_size = required_selection_usize(payload, "selection_group_size")?;
11521        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
11522        let member_size = required_selection_usize(payload, "member_size")?;
11523        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
11524        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
11525            invalid_recorded_history(
11526                "selection_marker_invalid",
11527                base_sequence,
11528                "non-empty selection_group_id",
11529                &payload.to_string(),
11530                "selection winner history is missing its durable group identity",
11531            )
11532        })?;
11533        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
11534        if group_id != expected_group_id {
11535            return Err(invalid_recorded_history(
11536                "selection_marker_invalid",
11537                base_sequence,
11538                &expected_group_id,
11539                &group_id,
11540                "selection winner history contains an incompatible group identity",
11541            ));
11542        }
11543        let group_end = base_sequence
11544            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
11545            .unwrap_or(u64::MAX);
11546        let member_end = member_base_sequence
11547            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
11548            .unwrap_or(u64::MAX);
11549        if member_index >= group_size
11550            || member_base_sequence < base_sequence
11551            || member_end > group_end
11552        {
11553            return Err(invalid_recorded_history(
11554                "selection_marker_invalid",
11555                base_sequence,
11556                "winner member within selection group bounds",
11557                &payload.to_string(),
11558                "selection winner history contains an invalid member range",
11559            ));
11560        }
11561        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
11562            invalid_recorded_history(
11563                "selection_marker_invalid",
11564                base_sequence,
11565                "selection operation kind",
11566                &payload.to_string(),
11567                "selection winner history is missing its operation kind",
11568            )
11569        })?;
11570        if !matches!(
11571            operation_kind.as_str(),
11572            "activity" | "child" | "timer" | "signal" | "condition" | "group"
11573        ) {
11574            return Err(invalid_recorded_history(
11575                "selection_marker_invalid",
11576                base_sequence,
11577                "activity, child, timer, signal, condition, or group",
11578                &operation_kind,
11579                "selection winner history contains an unsupported operation kind",
11580            ));
11581        }
11582        let operation_identity =
11583            payload_string(payload, "operation_identity").ok_or_else(|| {
11584                invalid_recorded_history(
11585                    "selection_marker_invalid",
11586                    base_sequence,
11587                    "non-empty operation identity",
11588                    &payload.to_string(),
11589                    "selection winner history is missing its durable operation identity",
11590                )
11591            })?;
11592        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
11593            invalid_recorded_history(
11594                "selection_marker_invalid",
11595                base_sequence,
11596                "completed or failed selection outcome",
11597                &payload.to_string(),
11598                "selection winner history is missing its outcome",
11599            )
11600        })?;
11601        if !matches!(outcome.as_str(), "completed" | "failed") {
11602            return Err(invalid_recorded_history(
11603                "selection_marker_invalid",
11604                base_sequence,
11605                "completed or failed selection outcome",
11606                &outcome,
11607                "selection winner history contains an unsupported outcome",
11608            ));
11609        }
11610        let marker = SelectionMarker {
11611            selection_group_id: group_id,
11612            selection_group_base_sequence: base_sequence,
11613            selection_group_size: group_size,
11614            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
11615            member_index,
11616            member_base_sequence,
11617            member_size,
11618            operation_kind,
11619            operation_identity,
11620            outcome,
11621            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
11622                || {
11623                    invalid_recorded_history(
11624                        "selection_marker_invalid",
11625                        base_sequence,
11626                        "durable resolution_event_id",
11627                        &payload.to_string(),
11628                        "selection winner history is missing its terminal event identity",
11629                    )
11630                },
11631            )?,
11632            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
11633                || {
11634                    invalid_recorded_history(
11635                        "selection_marker_invalid",
11636                        base_sequence,
11637                        "durable resolution_event_type",
11638                        &payload.to_string(),
11639                        "selection winner history is missing its terminal event type",
11640                    )
11641                },
11642            )?,
11643        };
11644        if let Some(existing) = markers
11645            .iter()
11646            .find(|existing| existing.selection_group_id == marker.selection_group_id)
11647        {
11648            if existing != &marker {
11649                return Err(invalid_recorded_history(
11650                    "selection_marker_conflict",
11651                    base_sequence,
11652                    &format!("one winner for {}", marker.selection_group_id),
11653                    &payload.to_string(),
11654                    "selection history records conflicting winners for one durable group",
11655                ));
11656            }
11657            continue;
11658        }
11659        markers.push(marker);
11660    }
11661    Ok(markers)
11662}
11663
11664fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
11665    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
11666    for event in events
11667        .iter()
11668        .filter(|event| event.event_type == "SelectionOperationCancelled")
11669    {
11670        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
11671            invalid_recorded_history(
11672                "selection_cancellation_invalid",
11673                0,
11674                "non-empty selection_group_id",
11675                &event.payload.to_string(),
11676                "selection cancellation history is missing its group identity",
11677            )
11678        })?;
11679        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
11680        let marker = SelectionCancellation {
11681            selection_group_id: group_id,
11682            member_key: selection_key_from_value(
11683                event.payload.get("member_key"),
11684                member_base_sequence,
11685            )?,
11686            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
11687            member_base_sequence,
11688            member_size: required_selection_usize(&event.payload, "member_size")?,
11689            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
11690                invalid_recorded_history(
11691                    "selection_cancellation_invalid",
11692                    member_base_sequence,
11693                    "selection operation kind",
11694                    &event.payload.to_string(),
11695                    "selection cancellation is missing its operation kind",
11696                )
11697            })?,
11698            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
11699                || {
11700                    invalid_recorded_history(
11701                        "selection_cancellation_invalid",
11702                        member_base_sequence,
11703                        "selection operation identity",
11704                        &event.payload.to_string(),
11705                        "selection cancellation is missing its operation identity",
11706                    )
11707                },
11708            )?,
11709        };
11710        if let Some(existing) = cancelled.iter().find(|recorded| {
11711            recorded.selection_group_id == marker.selection_group_id
11712                && recorded.member_base_sequence == marker.member_base_sequence
11713        }) {
11714            if existing != &marker {
11715                return Err(invalid_recorded_history(
11716                    "selection_cancellation_conflict",
11717                    member_base_sequence,
11718                    "one stable SelectionOperationCancelled marker",
11719                    &event.payload.to_string(),
11720                    "selection cancellation history contains conflicting member metadata",
11721                ));
11722            }
11723        } else {
11724            cancelled.push(marker);
11725        }
11726    }
11727    Ok(cancelled)
11728}
11729
11730fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
11731    payload
11732        .get(field)
11733        .and_then(value_as_u64)
11734        .filter(|value| *value > 0)
11735        .ok_or_else(|| {
11736            invalid_recorded_history(
11737                "selection_marker_invalid",
11738                0,
11739                &format!("positive integer {field}"),
11740                &payload.to_string(),
11741                "selection history contains invalid durable identity metadata",
11742            )
11743        })
11744}
11745
11746fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
11747    required_selection_usize_allow_zero(payload, field).and_then(|value| {
11748        if value > 0 {
11749            Ok(value)
11750        } else {
11751            Err(invalid_recorded_history(
11752                "selection_marker_invalid",
11753                0,
11754                &format!("positive integer {field}"),
11755                &payload.to_string(),
11756                "selection history contains invalid durable identity metadata",
11757            ))
11758        }
11759    })
11760}
11761
11762fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
11763    payload
11764        .get(field)
11765        .and_then(value_as_u64)
11766        .and_then(|value| usize::try_from(value).ok())
11767        .ok_or_else(|| {
11768            invalid_recorded_history(
11769                "selection_marker_invalid",
11770                0,
11771                &format!("non-negative integer {field}"),
11772                &payload.to_string(),
11773                "selection history contains invalid durable identity metadata",
11774            )
11775        })
11776}
11777
11778#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11779struct RecordedActivityOptions {
11780    task_queue: RecordedSnapshotValue<Option<String>>,
11781    execution_mode: RecordedSnapshotValue<Option<String>>,
11782    retry_policy: ActivityRetrySnapshot,
11783    worker_session: Option<Value>,
11784}
11785
11786#[derive(Clone, Debug)]
11787struct RecordedChildPolicies {
11788    parent_close_policy: String,
11789    cancellation_policy: String,
11790}
11791
11792fn recorded_activity_cancellation_policy(
11793    events: &[&HistoryEvent],
11794    sequence: u64,
11795) -> Result<String> {
11796    let mut policy: Option<String> = None;
11797    for event in events.iter().filter(|event| {
11798        matches!(
11799            event.event_type.as_str(),
11800            "ActivityScheduled"
11801                | "ActivityStarted"
11802                | "ActivityCompleted"
11803                | "ActivityFailed"
11804                | "ActivityTimedOut"
11805                | "ActivityCancelled"
11806        )
11807    }) {
11808        for source in [Some(&event.payload), event.payload.get("activity")]
11809            .into_iter()
11810            .flatten()
11811        {
11812            let Some(value) = source.get("cancellation_policy") else {
11813                continue;
11814            };
11815            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
11816                value.as_str()
11817            else {
11818                return Err(invalid_recorded_history(
11819                    "invalid_activity_cancellation_policy_history",
11820                    sequence,
11821                    "supported Activity cancellation policy",
11822                    &value.to_string(),
11823                    "Activity history contains an invalid cancellation policy",
11824                ));
11825            };
11826            if let Some(previous) = policy.as_deref() {
11827                if previous != incoming {
11828                    return Err(invalid_recorded_history(
11829                        "activity_cancellation_policy_history_conflict",
11830                        sequence,
11831                        previous,
11832                        incoming,
11833                        "Activity cancellation policy changed between history events",
11834                    ));
11835                }
11836            }
11837            policy = Some(incoming.to_string());
11838        }
11839        policy.get_or_insert_with(|| "try_cancel".to_string());
11840    }
11841    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
11842}
11843
11844fn recorded_child_policy_value<'a>(
11845    payload: &'a Value,
11846    field: &str,
11847    sequence: u64,
11848) -> Result<Option<&'a str>> {
11849    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
11850        return Ok(None);
11851    };
11852    let valid = match (field, value.as_str()) {
11853        (
11854            "parent_close_policy",
11855            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11856        ) => true,
11857        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11858            true
11859        }
11860        _ => false,
11861    };
11862    if !valid {
11863        return Err(invalid_recorded_history(
11864            "invalid_child_workflow_policy_history",
11865            sequence,
11866            "supported child workflow policy",
11867            &value.to_string(),
11868            "child workflow history contains an invalid policy",
11869        ));
11870    }
11871    Ok(value.as_str())
11872}
11873
11874fn recorded_child_policies(
11875    events: &[&HistoryEvent],
11876    scheduled: &HistoryEvent,
11877    sequence: u64,
11878) -> Result<RecordedChildPolicies> {
11879    let parent_close_policy =
11880        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11881            .unwrap_or("abandon")
11882            .to_string();
11883    let cancellation_policy =
11884        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11885            .unwrap_or("abandon")
11886            .to_string();
11887    for event in events {
11888        for (field, expected) in [
11889            ("parent_close_policy", parent_close_policy.as_str()),
11890            ("cancellation_policy", cancellation_policy.as_str()),
11891        ] {
11892            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11893                if actual != expected {
11894                    return Err(invalid_recorded_history(
11895                        "child_workflow_policy_history_conflict",
11896                        sequence,
11897                        expected,
11898                        actual,
11899                        "child workflow policy changed between history events",
11900                    ));
11901                }
11902            }
11903        }
11904    }
11905    Ok(RecordedChildPolicies {
11906        parent_close_policy,
11907        cancellation_policy,
11908    })
11909}
11910
11911fn ensure_child_policies_match(
11912    sequence: u64,
11913    recorded: &RecordedChildPolicies,
11914    current: &ChildWorkflowOptions,
11915) -> Result<()> {
11916    for (field, expected, actual) in [
11917        (
11918            "parent_close_policy",
11919            recorded.parent_close_policy.as_str(),
11920            current.parent_close_policy.as_str(),
11921        ),
11922        (
11923            "cancellation_policy",
11924            recorded.cancellation_policy.as_str(),
11925            current.cancellation_policy.as_str(),
11926        ),
11927    ] {
11928        if expected != actual {
11929            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11930                "child_workflow_policy_changed",
11931                Some(sequence),
11932                Some(expected.to_string()),
11933                Some(actual.to_string()),
11934                format!("child workflow {field} changed during replay"),
11935            )));
11936        }
11937    }
11938    Ok(())
11939}
11940
11941#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11942enum RecordedSnapshotValue<T> {
11943    /// Older history did not persist this field, so it cannot constrain replay.
11944    Unknown,
11945    Known(T),
11946}
11947
11948impl<T: PartialEq> RecordedSnapshotValue<T> {
11949    fn matches_current(&self, current: &Self) -> bool {
11950        match self {
11951            Self::Unknown => true,
11952            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11953        }
11954    }
11955}
11956
11957#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11958struct ActivityRetrySnapshot {
11959    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11960    max_attempts: RecordedSnapshotValue<Option<u64>>,
11961    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11962    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11963    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11964    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11965    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11966    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11967}
11968
11969impl ActivityRetrySnapshot {
11970    fn matches_current(&self, current: &Self) -> bool {
11971        self.snapshot_version
11972            .matches_current(&current.snapshot_version)
11973            && self.max_attempts.matches_current(&current.max_attempts)
11974            && self
11975                .backoff_seconds
11976                .matches_current(&current.backoff_seconds)
11977            && self
11978                .start_to_close_timeout
11979                .matches_current(&current.start_to_close_timeout)
11980            && self
11981                .schedule_to_start_timeout
11982                .matches_current(&current.schedule_to_start_timeout)
11983            && self
11984                .schedule_to_close_timeout
11985                .matches_current(&current.schedule_to_close_timeout)
11986            && self
11987                .heartbeat_timeout
11988                .matches_current(&current.heartbeat_timeout)
11989            && self
11990                .non_retryable_error_types
11991                .matches_current(&current.non_retryable_error_types)
11992    }
11993}
11994
11995fn recorded_optional_u64(
11996    object: Option<&serde_json::Map<String, Value>>,
11997    field: &str,
11998) -> RecordedSnapshotValue<Option<u64>> {
11999    match object.and_then(|object| object.get(field)) {
12000        None => RecordedSnapshotValue::Unknown,
12001        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12002        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
12003    }
12004}
12005
12006fn recorded_optional_string(
12007    object: &serde_json::Map<String, Value>,
12008    field: &str,
12009) -> RecordedSnapshotValue<Option<String>> {
12010    match object.get(field) {
12011        None => RecordedSnapshotValue::Unknown,
12012        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12013        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
12014    }
12015}
12016
12017fn recorded_activity_execution_mode(
12018    events: &[&HistoryEvent],
12019    sequence: u64,
12020) -> Result<RecordedSnapshotValue<Option<String>>> {
12021    let mut recorded = RecordedSnapshotValue::Unknown;
12022    for event in events {
12023        for object in [
12024            event.payload.as_object(),
12025            event.payload.get("activity").and_then(Value::as_object),
12026        ]
12027        .into_iter()
12028        .flatten()
12029        {
12030            let mode = match object.get("execution_mode") {
12031                None => None,
12032                Some(Value::Null) => Some(None),
12033                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
12034                Some(_) => {
12035                    return Err(invalid_recorded_history(
12036                        "activity_execution_mode_invalid",
12037                        sequence,
12038                        "null or a non-empty execution mode",
12039                        "invalid execution_mode",
12040                        "activity history contains an invalid execution mode",
12041                    ))
12042                }
12043            };
12044            let legacy_mode = match object.get("local_activity") {
12045                None => None,
12046                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
12047                Some(_) => {
12048                    return Err(invalid_recorded_history(
12049                        "activity_execution_mode_invalid",
12050                        sequence,
12051                        "boolean local_activity",
12052                        "invalid local_activity",
12053                        "activity history contains an invalid local-activity marker",
12054                    ))
12055                }
12056            };
12057            for mode in [mode, legacy_mode].into_iter().flatten() {
12058                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
12059                {
12060                    return Err(invalid_recorded_history(
12061                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
12062                        "activity lifecycle events at one workflow sequence disagree on execution mode",
12063                    ));
12064                }
12065                recorded = RecordedSnapshotValue::Known(mode);
12066            }
12067        }
12068    }
12069    Ok(recorded)
12070}
12071
12072fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
12073    let policy = policy.and_then(Value::as_object);
12074    let backoff_seconds = policy
12075        .and_then(|policy| policy.get("backoff_seconds"))
12076        .and_then(Value::as_array)
12077        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12078        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
12079    let mut non_retryable_error_types = Vec::new();
12080    for error_type in policy
12081        .and_then(|policy| policy.get("non_retryable_error_types"))
12082        .and_then(Value::as_array)
12083        .into_iter()
12084        .flatten()
12085        .filter_map(Value::as_str)
12086        .map(str::trim)
12087        .filter(|error_type| !error_type.is_empty())
12088    {
12089        if !non_retryable_error_types
12090            .iter()
12091            .any(|recorded| recorded == error_type)
12092        {
12093            non_retryable_error_types.push(error_type.to_string());
12094        }
12095    }
12096
12097    ActivityRetrySnapshot {
12098        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
12099        max_attempts: recorded_optional_u64(policy, "max_attempts"),
12100        backoff_seconds,
12101        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
12102        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
12103        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
12104        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
12105        non_retryable_error_types: if policy
12106            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
12107        {
12108            RecordedSnapshotValue::Known(non_retryable_error_types)
12109        } else {
12110            RecordedSnapshotValue::Unknown
12111        },
12112    }
12113}
12114
12115fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
12116    let policy = options.retry_policy.as_ref();
12117    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
12118        Some(Value::Null) => None,
12119        Some(value) => value_as_u64(value),
12120        None => Some(1),
12121    };
12122    let backoff_seconds = policy
12123        .and_then(|policy| policy.get("backoff_seconds"))
12124        .and_then(Value::as_array)
12125        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12126        .unwrap_or_default();
12127    let non_retryable_error_types = policy
12128        .and_then(|policy| policy.get("non_retryable_error_types"))
12129        .and_then(Value::as_array)
12130        .into_iter()
12131        .flatten()
12132        .filter_map(Value::as_str)
12133        .map(str::to_string)
12134        .collect();
12135
12136    ActivityRetrySnapshot {
12137        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
12138        max_attempts: RecordedSnapshotValue::Known(max_attempts),
12139        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
12140        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
12141        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
12142        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
12143        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
12144        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
12145    }
12146}
12147
12148fn activity_options_description(options: &RecordedActivityOptions) -> String {
12149    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
12150}
12151
12152impl RecordedCommand {
12153    fn sequence(&self) -> u64 {
12154        match self {
12155            Self::CancellationGroup { sequence, .. }
12156            | Self::CancellationScope { sequence, .. }
12157            | Self::CancellationBoundary { sequence, .. }
12158            | Self::Activity { sequence, .. }
12159            | Self::Timer { sequence, .. }
12160            | Self::ChildWorkflow { sequence, .. }
12161            | Self::SignalWait { sequence, .. }
12162            | Self::ConditionWait { sequence, .. }
12163            | Self::SearchAttributes { sequence, .. }
12164            | Self::SideEffect { sequence, .. }
12165            | Self::VersionMarker { sequence, .. }
12166            | Self::Memo { sequence, .. } => *sequence,
12167        }
12168    }
12169
12170    fn shape(&self) -> &'static str {
12171        match self {
12172            Self::CancellationScope { .. } => "cancellation scope",
12173            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
12174                "cooperative cancellation"
12175            }
12176            Self::Activity { .. } => "activity",
12177            Self::Timer { .. } => "timer",
12178            Self::ChildWorkflow { .. } => "child workflow",
12179            Self::SignalWait { .. } => "signal wait",
12180            Self::ConditionWait { .. } => "condition wait",
12181            Self::SearchAttributes { .. } => "search-attribute update",
12182            Self::SideEffect { .. } => "side effect",
12183            Self::VersionMarker { .. } => "version marker",
12184            Self::Memo { .. } => "memo upsert",
12185        }
12186    }
12187}
12188
12189fn ensure_version_supported(
12190    change_id: &str,
12191    version: i32,
12192    min_supported: i32,
12193    max_supported: i32,
12194    sequence: u64,
12195) -> Result<()> {
12196    if (min_supported..=max_supported).contains(&version) {
12197        return Ok(());
12198    }
12199    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12200        "version_marker_incompatible_range",
12201        (sequence != 0).then_some(sequence),
12202        Some(format!("{min_supported}..={max_supported}")),
12203        Some(format!("{change_id}:{version}")),
12204        "recorded workflow version is outside the range supported by current code",
12205    )))
12206}
12207
12208#[derive(Clone, Debug)]
12209struct ResumeSignal {
12210    signal_name: String,
12211    arguments: Vec<AvroValue>,
12212}
12213
12214const MAX_PARALLEL_OPERATIONS: usize = 1000;
12215
12216fn parallel_group_prefix(kind: &str) -> &'static str {
12217    match kind {
12218        "activity" => "parallel-activities",
12219        "child" => "parallel-children",
12220        "timer" => "parallel-timers",
12221        _ => "parallel-calls",
12222    }
12223}
12224
12225fn parallel_group_entry(
12226    base_sequence: u64,
12227    size: usize,
12228    index: usize,
12229    kind: &str,
12230) -> ParallelGroupMetadata {
12231    ParallelGroupMetadata {
12232        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12233        parallel_group_kind: kind.to_string(),
12234        parallel_group_base_sequence: base_sequence,
12235        parallel_group_size: size,
12236        parallel_group_index: index,
12237        parallel_group_mode: None,
12238        selection_member_key: None,
12239        selection_member_index: None,
12240        selection_member_base_sequence: None,
12241        selection_member_size: None,
12242        selection_member_kind: None,
12243    }
12244}
12245
12246struct SelectionMemberMetadata {
12247    key: SelectionKey,
12248    index: usize,
12249    base_sequence: u64,
12250    size: usize,
12251    kind: String,
12252}
12253
12254fn selection_group_entry(
12255    base_sequence: u64,
12256    size: usize,
12257    index: usize,
12258    kind: &str,
12259    member: &SelectionMemberMetadata,
12260) -> ParallelGroupMetadata {
12261    ParallelGroupMetadata {
12262        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
12263        parallel_group_kind: kind.to_string(),
12264        parallel_group_base_sequence: base_sequence,
12265        parallel_group_size: size,
12266        parallel_group_index: index,
12267        parallel_group_mode: Some("select".to_string()),
12268        selection_member_key: Some(member.key.clone()),
12269        selection_member_index: Some(member.index),
12270        selection_member_base_sequence: Some(member.base_sequence),
12271        selection_member_size: Some(member.size),
12272        selection_member_kind: Some(member.kind.clone()),
12273    }
12274}
12275
12276fn apply_parallel_group_path(
12277    command: &mut serde_json::Map<String, Value>,
12278    path: &[ParallelGroupMetadata],
12279) {
12280    let Some(inner) = path.last() else {
12281        return;
12282    };
12283    command.insert(
12284        "parallel_group_id".to_string(),
12285        json!(inner.parallel_group_id),
12286    );
12287    command.insert(
12288        "parallel_group_kind".to_string(),
12289        json!(inner.parallel_group_kind),
12290    );
12291    command.insert(
12292        "parallel_group_base_sequence".to_string(),
12293        json!(inner.parallel_group_base_sequence),
12294    );
12295    command.insert(
12296        "parallel_group_size".to_string(),
12297        json!(inner.parallel_group_size),
12298    );
12299    command.insert(
12300        "parallel_group_index".to_string(),
12301        json!(inner.parallel_group_index),
12302    );
12303    if let Some(mode) = &inner.parallel_group_mode {
12304        command.insert("parallel_group_mode".to_string(), json!(mode));
12305    }
12306    if let Some(key) = &inner.selection_member_key {
12307        command.insert("selection_member_key".to_string(), json!(key));
12308    }
12309    if let Some(index) = inner.selection_member_index {
12310        command.insert("selection_member_index".to_string(), json!(index));
12311    }
12312    if let Some(base_sequence) = inner.selection_member_base_sequence {
12313        command.insert(
12314            "selection_member_base_sequence".to_string(),
12315            json!(base_sequence),
12316        );
12317    }
12318    if let Some(size) = inner.selection_member_size {
12319        command.insert("selection_member_size".to_string(), json!(size));
12320    }
12321    if let Some(kind) = &inner.selection_member_kind {
12322        command.insert("selection_member_kind".to_string(), json!(kind));
12323    }
12324    command.insert("parallel_group_path".to_string(), json!(path));
12325}
12326
12327fn ensure_parallel_path_matches(
12328    sequence: u64,
12329    recorded: Option<&[ParallelGroupMetadata]>,
12330    expected: &[ParallelGroupMetadata],
12331) -> Result<()> {
12332    match (recorded, expected.is_empty()) {
12333        (None, true) => Ok(()),
12334        (Some(recorded), false) if recorded == expected => Ok(()),
12335        (None, false) => Err(invalid_recorded_history(
12336            "parallel_group_metadata_missing",
12337            sequence,
12338            &serde_json::to_string(expected).unwrap_or_default(),
12339            "<missing>",
12340            "recorded parallel member is missing its durable group path",
12341        )),
12342        (Some(recorded), true) => Err(invalid_recorded_history(
12343            "parallel_group_shape_mismatch",
12344            sequence,
12345            "sequential command",
12346            &serde_json::to_string(recorded).unwrap_or_default(),
12347            "recorded command belonged to a parallel group but current code schedules it sequentially",
12348        )),
12349        (Some(recorded), false) => Err(invalid_recorded_history(
12350            "parallel_group_shape_mismatch",
12351            sequence,
12352            &serde_json::to_string(recorded).unwrap_or_default(),
12353            &serde_json::to_string(expected).unwrap_or_default(),
12354            "recorded parallel-group identity or path changed during replay",
12355        )),
12356    }
12357}
12358
12359#[derive(Clone, Debug)]
12360enum ParallelShape {
12361    Leaf,
12362    Group(Vec<ParallelShape>),
12363}
12364
12365struct ParallelDescriptor {
12366    operation: ParallelOperation,
12367    offset: usize,
12368    member_path: Vec<usize>,
12369    group_path: Vec<ParallelGroupMetadata>,
12370}
12371
12372fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
12373    operations
12374        .iter()
12375        .map(|operation| match operation {
12376            ParallelOperation::Group(children) => parallel_leaf_count(children),
12377            _ => 1,
12378        })
12379        .sum()
12380}
12381
12382fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
12383    match operation {
12384        ParallelOperation::Activity { .. } => Some("activity"),
12385        ParallelOperation::ChildWorkflow { .. } => Some("child"),
12386        ParallelOperation::Timer(_) => Some("timer"),
12387        ParallelOperation::Signal(_) => Some("signal"),
12388        ParallelOperation::Condition { .. } => Some("condition"),
12389        ParallelOperation::Group(children) => parallel_group_kind(children),
12390    }
12391}
12392
12393fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
12394    let mut kind = None;
12395    for operation in operations {
12396        let Some(operation_kind) = parallel_operation_kind(operation) else {
12397            continue;
12398        };
12399        match kind {
12400            None => kind = Some(operation_kind),
12401            Some(current) if current == operation_kind => {}
12402            Some(_) => return Some("mixed"),
12403        }
12404    }
12405    kind
12406}
12407
12408fn validate_parallel_operations(
12409    operations: &[ParallelOperation],
12410    member_path: &mut Vec<usize>,
12411    root: bool,
12412) -> Result<()> {
12413    let leaves = parallel_leaf_count(operations);
12414    if leaves > MAX_PARALLEL_OPERATIONS {
12415        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12416            reason: "fan_out_limit_exceeded",
12417            member_path: member_path.clone(),
12418            message: format!(
12419                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12420            ),
12421        }));
12422    }
12423    if !root && operations.is_empty() {
12424        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12425            reason: "nested_group_empty",
12426            member_path: member_path.clone(),
12427            message: "a nested group must contain at least one durable leaf".to_string(),
12428        }));
12429    }
12430
12431    for (index, operation) in operations.iter().enumerate() {
12432        member_path.push(index);
12433        match operation {
12434            ParallelOperation::Activity {
12435                options, arguments, ..
12436            } => {
12437                options
12438                    .validate()
12439                    .map_err(|error| Error::InvalidActivityOptions(error))?;
12440                if let Err(error) = arguments {
12441                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12442                        reason: "arguments_invalid",
12443                        member_path: member_path.clone(),
12444                        message: error.to_string(),
12445                    }));
12446                }
12447            }
12448            ParallelOperation::ChildWorkflow {
12449                options, arguments, ..
12450            } => {
12451                validate_parallel_child_options(options)?;
12452                if let Err(error) = arguments {
12453                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12454                        reason: "arguments_invalid",
12455                        member_path: member_path.clone(),
12456                        message: error.to_string(),
12457                    }));
12458                }
12459            }
12460            ParallelOperation::Timer(duration)
12461                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
12462            {
12463                return Err(Error::TimerDurationOverflow);
12464            }
12465            ParallelOperation::Timer(_) => {}
12466            ParallelOperation::Signal(signal_name) => {
12467                validate_user_signal_name(signal_name)?;
12468                if signal_name.trim().is_empty() {
12469                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12470                        reason: "signal_name_empty",
12471                        member_path: member_path.clone(),
12472                        message: "signal wait name must not be empty".to_string(),
12473                    }));
12474                }
12475            }
12476            ParallelOperation::Condition { options, .. } => {
12477                options.validate()?;
12478            }
12479            ParallelOperation::Group(children) => {
12480                validate_parallel_operations(children, member_path, false)?;
12481            }
12482        }
12483        member_path.pop();
12484    }
12485    Ok(())
12486}
12487
12488fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
12489    if options.task_queue.trim().is_empty() {
12490        return Err(Error::InvalidChildWorkflowOptions(
12491            "task_queue must not be empty".to_string(),
12492        ));
12493    }
12494    for (name, value) in [
12495        (
12496            "execution_timeout_seconds",
12497            options.execution_timeout_seconds,
12498        ),
12499        ("run_timeout_seconds", options.run_timeout_seconds),
12500    ] {
12501        if value == Some(0) {
12502            return Err(Error::InvalidChildWorkflowOptions(format!(
12503                "{name} must be at least 1"
12504            )));
12505        }
12506    }
12507    if options
12508        .retry_policy
12509        .as_ref()
12510        .is_some_and(|policy| policy.max_attempts == Some(0))
12511    {
12512        return Err(Error::InvalidChildWorkflowOptions(
12513            "retry_policy.max_attempts must be at least 1".to_string(),
12514        ));
12515    }
12516    Ok(())
12517}
12518
12519fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
12520    ParallelShape::Group(
12521        operations
12522            .iter()
12523            .map(|operation| match operation {
12524                ParallelOperation::Group(children) => parallel_shape(children),
12525                _ => ParallelShape::Leaf,
12526            })
12527            .collect(),
12528    )
12529}
12530
12531fn parallel_descriptors(
12532    operations: Vec<ParallelOperation>,
12533    base_sequence: u64,
12534) -> Result<Vec<ParallelDescriptor>> {
12535    let size = parallel_leaf_count(&operations);
12536    let kind = parallel_group_kind(&operations).unwrap_or("activity");
12537    let mut descriptors = Vec::with_capacity(size);
12538    let mut cursor = 0;
12539
12540    for (index, operation) in operations.into_iter().enumerate() {
12541        match operation {
12542            ParallelOperation::Group(children) => {
12543                let child_base = base_sequence
12544                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12545                    .ok_or(Error::TimerDurationOverflow)?;
12546                for mut descriptor in parallel_descriptors(children, child_base)? {
12547                    let outer_index = cursor + descriptor.offset;
12548                    descriptor.group_path.insert(
12549                        0,
12550                        parallel_group_entry(base_sequence, size, outer_index, kind),
12551                    );
12552                    descriptor.member_path.insert(0, index);
12553                    descriptor.offset = outer_index;
12554                    descriptors.push(descriptor);
12555                }
12556                cursor = descriptors.len();
12557            }
12558            operation => {
12559                descriptors.push(ParallelDescriptor {
12560                    operation,
12561                    offset: cursor,
12562                    member_path: vec![index],
12563                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
12564                });
12565                cursor += 1;
12566            }
12567        }
12568    }
12569    Ok(descriptors)
12570}
12571
12572enum ParallelLeafCall {
12573    Activity(ActivityCall),
12574    ChildWorkflow(ChildWorkflowCall),
12575    Timer(TimerCall),
12576    Signal(SignalCall),
12577    Condition(ConditionWaitCall),
12578}
12579
12580fn parallel_leaf_call(
12581    ctx: &WorkflowContext,
12582    operation: ParallelOperation,
12583    parallel_group_path: Vec<ParallelGroupMetadata>,
12584) -> ParallelLeafCall {
12585    match operation {
12586        ParallelOperation::Activity {
12587            activity_type,
12588            options,
12589            arguments,
12590        } => ParallelLeafCall::Activity(ActivityCall {
12591            ctx: ctx.clone(),
12592            activity_type,
12593            options,
12594            worker_session: None,
12595            args: Some(arguments),
12596            scheduled: false,
12597            local: false,
12598            local_result: None,
12599            parallel_group_path,
12600        }),
12601        ParallelOperation::ChildWorkflow {
12602            workflow_type,
12603            options,
12604            arguments,
12605        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
12606            ctx: ctx.clone(),
12607            workflow_type,
12608            options,
12609            args: Some(arguments),
12610            scheduled: false,
12611            matched_pending: false,
12612            parallel_group_path,
12613        }),
12614        ParallelOperation::Timer(duration) => {
12615            let delay_seconds = duration
12616                .as_secs()
12617                .checked_add(u64::from(duration.subsec_nanos() > 0));
12618            ParallelLeafCall::Timer(TimerCall {
12619                ctx: ctx.clone(),
12620                delay_seconds,
12621                scheduled: false,
12622                matched_pending: false,
12623                parallel_group_path,
12624            })
12625        }
12626        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
12627            ctx: ctx.clone(),
12628            signal_name,
12629            runtime_reserved_allowed: false,
12630            opened_wait: false,
12631            matched_pending: false,
12632            parallel_group_path,
12633        }),
12634        ParallelOperation::Condition { options, predicate } => {
12635            ParallelLeafCall::Condition(ConditionWaitCall {
12636                ctx: ctx.clone(),
12637                options,
12638                predicate,
12639                occurrence_id: None,
12640                opened_wait: false,
12641                parallel_group_path,
12642            })
12643        }
12644        ParallelOperation::Group(_) => {
12645            unreachable!("parallel descriptors contain only durable leaves")
12646        }
12647    }
12648}
12649
12650impl ParallelLeafCall {
12651    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
12652        match self {
12653            Self::Activity(call) => Pin::new(call)
12654                .poll_avro_value(cx)
12655                .map_ok(ParallelAvroResult::Activity),
12656            Self::ChildWorkflow(call) => Pin::new(call)
12657                .poll_avro_value(cx)
12658                .map_ok(ParallelAvroResult::ChildWorkflow),
12659            Self::Timer(call) => Pin::new(call)
12660                .poll(cx)
12661                .map_ok(|()| ParallelAvroResult::Timer),
12662            Self::Signal(call) => Pin::new(call)
12663                .poll_avro_value(cx)
12664                .map_ok(ParallelAvroResult::Signal),
12665            Self::Condition(call) => Pin::new(call)
12666                .poll(cx)
12667                .map_ok(ParallelAvroResult::Condition),
12668        }
12669    }
12670}
12671
12672struct ParallelLeaf {
12673    call: ParallelLeafCall,
12674    sequence: u64,
12675    member_path: Vec<usize>,
12676    group_path: Vec<ParallelGroupMetadata>,
12677    result: Option<ParallelAvroResult>,
12678}
12679
12680/// Future returned by [`WorkflowContext::parallel`].
12681pub struct ParallelCall {
12682    ctx: WorkflowContext,
12683    operations: Option<Vec<ParallelOperation>>,
12684    shape: Option<ParallelShape>,
12685    leaves: Vec<ParallelLeaf>,
12686    pending_scope_delivery: bool,
12687    worker_session: Option<WorkerSessionOptions>,
12688}
12689
12690impl ParallelCall {
12691    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
12692        Self {
12693            ctx,
12694            operations: Some(operations),
12695            shape: None,
12696            leaves: Vec::new(),
12697            pending_scope_delivery: false,
12698            worker_session: None,
12699        }
12700    }
12701
12702    fn initialize(&mut self) -> Result<()> {
12703        if let Some(session) = &self.worker_session {
12704            session.to_wire()?;
12705        }
12706        let operations = self.operations.take().unwrap_or_default();
12707        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
12708        self.shape = Some(parallel_shape(&operations));
12709        if operations.is_empty() {
12710            return Ok(());
12711        }
12712
12713        let base_sequence = {
12714            let state = self
12715                .ctx
12716                .state
12717                .lock()
12718                .map_err(|_| Error::WorkflowStatePoisoned)?;
12719            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12720                recorded.sequence()
12721            } else {
12722                let last = state
12723                    .recorded_commands
12724                    .last()
12725                    .map(RecordedCommand::sequence)
12726                    .unwrap_or(0);
12727                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12728                    .and_then(|sequence| sequence.checked_add(1))
12729                    .ok_or_else(|| {
12730                        Error::InvalidParallelGroup(ParallelGroupError {
12731                            reason: "sequence_overflow",
12732                            member_path: Vec::new(),
12733                            message: "parallel group sequence identity overflowed u64".to_string(),
12734                        })
12735                    })?
12736            }
12737        };
12738
12739        let descriptors = parallel_descriptors(operations, base_sequence)?;
12740        {
12741            let mut state = self
12742                .ctx
12743                .state
12744                .lock()
12745                .map_err(|_| Error::WorkflowStatePoisoned)?;
12746            let cursor = state.command_cursor;
12747            self.ctx.validate_scope_membership(&mut state, cursor)?;
12748            if state.prepare_parallel_scope_cancellation(&descriptors)? {
12749                self.pending_scope_delivery = true;
12750                return Ok(());
12751            }
12752            state.expand_cancellation_group(&descriptors)?;
12753            state.prepare_group_cancellation(&descriptors)?;
12754        }
12755        self.leaves = descriptors
12756            .into_iter()
12757            .map(|descriptor| {
12758                let mut call = parallel_leaf_call(
12759                    &self.ctx,
12760                    descriptor.operation,
12761                    descriptor.group_path.clone(),
12762                );
12763                if let (Some(session), ParallelLeafCall::Activity(activity)) =
12764                    (&self.worker_session, &mut call)
12765                {
12766                    activity.worker_session = Some(session.clone());
12767                }
12768                ParallelLeaf {
12769                    call,
12770                    sequence: base_sequence + descriptor.offset as u64,
12771                    member_path: descriptor.member_path,
12772                    group_path: descriptor.group_path,
12773                    result: None,
12774                }
12775            })
12776            .collect();
12777        Ok(())
12778    }
12779
12780    fn poll_avro_value(
12781        mut self: Pin<&mut Self>,
12782        cx: &mut TaskContext<'_>,
12783    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
12784        if self.operations.is_some() {
12785            if let Err(error) = self.initialize() {
12786                return Poll::Ready(Err(error));
12787            }
12788        }
12789        if self.pending_scope_delivery {
12790            return Poll::Pending;
12791        }
12792        if self.leaves.is_empty() {
12793            return Poll::Ready(Ok(Vec::new()));
12794        }
12795
12796        let mut failures = Vec::new();
12797        let mut pending = false;
12798        for (index, leaf) in self.leaves.iter_mut().enumerate() {
12799            if leaf.result.is_some() {
12800                continue;
12801            }
12802            match leaf.call.poll_avro_value(cx) {
12803                Poll::Ready(Ok(result)) => leaf.result = Some(result),
12804                Poll::Ready(Err(error)) => failures.push((index, error)),
12805                Poll::Pending => pending = true,
12806            }
12807        }
12808
12809        if !failures.is_empty() {
12810            if let Some(position) = failures
12811                .iter()
12812                .position(|(_, error)| workflow_task_integrity_error(error))
12813            {
12814                return Poll::Ready(Err(failures.remove(position).1));
12815            }
12816            if self
12817                .ctx
12818                .state
12819                .lock()
12820                .map_err(|_| Error::WorkflowStatePoisoned)?
12821                .cancellation_delivery_intent
12822                .is_some()
12823            {
12824                return Poll::Pending;
12825            }
12826            if let Some(position) = failures
12827                .iter()
12828                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
12829            {
12830                return Poll::Ready(Err(failures.remove(position).1));
12831            }
12832            failures.sort_by_key(|(index, _)| *index);
12833            let (failed_index, cause) = failures.remove(0);
12834            let failed = &self.leaves[failed_index];
12835            let completed = self
12836                .leaves
12837                .iter()
12838                .filter_map(|leaf| {
12839                    leaf.result
12840                        .clone()
12841                        .and_then(|result| result.into_json_result().ok())
12842                        .map(|result| ParallelCompletion {
12843                            member_path: leaf.member_path.clone(),
12844                            result,
12845                        })
12846                })
12847                .collect();
12848            let group_id = failed
12849                .group_path
12850                .first()
12851                .map(|entry| entry.parallel_group_id.clone())
12852                .unwrap_or_default();
12853            let sequences = self
12854                .leaves
12855                .iter()
12856                .map(|leaf| leaf.sequence)
12857                .collect::<Vec<_>>();
12858            self.ctx
12859                .state
12860                .lock()
12861                .map_err(|_| Error::WorkflowStatePoisoned)?
12862                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12863            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12864                group_id,
12865                member_path: failed.member_path.clone(),
12866                group_path: failed.group_path.clone(),
12867                completed,
12868                cause: Box::new(cause),
12869            })));
12870        }
12871        if pending
12872            || self
12873                .ctx
12874                .state
12875                .lock()
12876                .map_err(|_| Error::WorkflowStatePoisoned)?
12877                .cancellation_delivery_intent
12878                .is_some()
12879        {
12880            return Poll::Pending;
12881        }
12882
12883        let mut flat_results = self
12884            .leaves
12885            .iter_mut()
12886            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12887            .collect::<Vec<_>>()
12888            .into_iter();
12889        let results = parallel_results_for_shape(
12890            self.shape.as_ref().expect("initialized parallel shape"),
12891            &mut flat_results,
12892        );
12893        let sequences = self
12894            .leaves
12895            .iter()
12896            .map(|leaf| leaf.sequence)
12897            .collect::<Vec<_>>();
12898        self.ctx
12899            .state
12900            .lock()
12901            .map_err(|_| Error::WorkflowStatePoisoned)?
12902            .advance_cancellation_sequences(&sequences, None);
12903        Poll::Ready(Ok(match results {
12904            ParallelAvroResult::Group(results) => results,
12905            ParallelAvroResult::Activity(_)
12906            | ParallelAvroResult::ChildWorkflow(_)
12907            | ParallelAvroResult::Timer
12908            | ParallelAvroResult::Signal(_)
12909            | ParallelAvroResult::Condition(_) => {
12910                unreachable!("root parallel shape is a group")
12911            }
12912        }))
12913    }
12914}
12915
12916fn parallel_results_for_shape(
12917    shape: &ParallelShape,
12918    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12919) -> ParallelAvroResult {
12920    match shape {
12921        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12922        ParallelShape::Group(children) => ParallelAvroResult::Group(
12923            children
12924                .iter()
12925                .map(|child| parallel_results_for_shape(child, flat_results))
12926                .collect(),
12927        ),
12928    }
12929}
12930
12931impl Future for ParallelCall {
12932    type Output = Result<Vec<ParallelResult>>;
12933
12934    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12935        self.poll_avro_value(cx)
12936            .map_ok(|results| {
12937                results
12938                    .into_iter()
12939                    .map(ParallelAvroResult::into_json_result)
12940                    .collect::<Result<Vec<_>>>()
12941            })
12942            .map_ok(|result| result)
12943            .flatten_result()
12944    }
12945}
12946
12947#[derive(Clone, Debug)]
12948struct SelectionMemberPlan {
12949    key: SelectionKey,
12950    index: usize,
12951    base_sequence: u64,
12952    size: usize,
12953    kind: String,
12954    shape: ParallelShape,
12955    leaf_start: usize,
12956}
12957
12958fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12959    match operation {
12960        ParallelOperation::Activity { .. } => "activity",
12961        ParallelOperation::ChildWorkflow { .. } => "child",
12962        ParallelOperation::Timer(_) => "timer",
12963        ParallelOperation::Signal(_) => "signal",
12964        ParallelOperation::Condition { .. } => "condition",
12965        ParallelOperation::Group(_) => "group",
12966    }
12967}
12968
12969fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12970    match operation {
12971        ParallelOperation::Group(children) => parallel_shape(children),
12972        _ => ParallelShape::Leaf,
12973    }
12974}
12975
12976fn selection_descriptors(
12977    operations: Vec<(SelectionKey, ParallelOperation)>,
12978    base_sequence: u64,
12979) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12980    if operations.is_empty() {
12981        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12982            reason: "selection_empty",
12983            member_path: Vec::new(),
12984            message: "durable selection requires at least one operation".to_string(),
12985        }));
12986    }
12987    let operation_refs = operations
12988        .iter()
12989        .map(|(_, operation)| operation)
12990        .collect::<Vec<_>>();
12991    let total_size = operation_refs
12992        .iter()
12993        .map(|operation| match operation {
12994            ParallelOperation::Group(children) => parallel_leaf_count(children),
12995            _ => 1,
12996        })
12997        .sum::<usize>();
12998    if total_size > MAX_PARALLEL_OPERATIONS {
12999        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13000            reason: "fan_out_limit_exceeded",
13001            member_path: Vec::new(),
13002            message: format!(
13003                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13004            ),
13005        }));
13006    }
13007    let group_kind = {
13008        let mut kind = None;
13009        for operation in &operation_refs {
13010            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
13011            match kind {
13012                None => kind = Some(operation_kind),
13013                Some(current) if current == operation_kind => {}
13014                Some(_) => {
13015                    kind = Some("mixed");
13016                    break;
13017                }
13018            }
13019        }
13020        kind.unwrap_or("mixed")
13021    };
13022
13023    let mut descriptors = Vec::with_capacity(total_size);
13024    let mut members = Vec::with_capacity(operations.len());
13025    let mut cursor = 0usize;
13026    let mut seen_keys: Vec<SelectionKey> = Vec::new();
13027    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
13028        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
13029            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13030                reason: "selection_key_invalid",
13031                member_path: vec![member_index],
13032                message: "selection member keys must be non-empty strings or non-negative integers"
13033                    .to_string(),
13034            }));
13035        }
13036        if seen_keys.contains(&key) {
13037            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13038                reason: "selection_key_duplicate",
13039                member_path: vec![member_index],
13040                message: format!("selection member key {key:?} is duplicated"),
13041            }));
13042        }
13043        seen_keys.push(key.clone());
13044        let member_size = match &operation {
13045            ParallelOperation::Group(children) => parallel_leaf_count(children),
13046            _ => 1,
13047        };
13048        if member_size == 0 {
13049            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13050                reason: "selection_member_empty",
13051                member_path: vec![member_index],
13052                message: "a selection member must contain at least one durable leaf".to_string(),
13053            }));
13054        }
13055        let member_base = base_sequence
13056            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13057            .ok_or(Error::TimerDurationOverflow)?;
13058        let member_kind = selection_operation_kind(&operation).to_string();
13059        let member_shape = selection_operation_shape(&operation);
13060        let leaf_start = descriptors.len();
13061        match operation {
13062            ParallelOperation::Group(children) => {
13063                validate_parallel_operations(&children, &mut vec![member_index], false)?;
13064                for mut descriptor in parallel_descriptors(children, member_base)? {
13065                    let flat_index = cursor + descriptor.offset;
13066                    descriptor.group_path.insert(
13067                        0,
13068                        selection_group_entry(
13069                            base_sequence,
13070                            total_size,
13071                            flat_index,
13072                            group_kind,
13073                            &SelectionMemberMetadata {
13074                                key: key.clone(),
13075                                index: member_index,
13076                                base_sequence: member_base,
13077                                size: member_size,
13078                                kind: member_kind.clone(),
13079                            },
13080                        ),
13081                    );
13082                    descriptor.member_path.insert(0, member_index);
13083                    descriptor.offset = flat_index;
13084                    descriptors.push(descriptor);
13085                }
13086            }
13087            operation => {
13088                validate_parallel_operations(
13089                    std::slice::from_ref(&operation),
13090                    &mut Vec::new(),
13091                    true,
13092                )?;
13093                descriptors.push(ParallelDescriptor {
13094                    operation,
13095                    offset: cursor,
13096                    member_path: vec![member_index],
13097                    group_path: vec![selection_group_entry(
13098                        base_sequence,
13099                        total_size,
13100                        cursor,
13101                        group_kind,
13102                        &SelectionMemberMetadata {
13103                            key: key.clone(),
13104                            index: member_index,
13105                            base_sequence: member_base,
13106                            size: member_size,
13107                            kind: member_kind.clone(),
13108                        },
13109                    )],
13110                });
13111            }
13112        }
13113        members.push(SelectionMemberPlan {
13114            key,
13115            index: member_index,
13116            base_sequence: member_base,
13117            size: member_size,
13118            kind: member_kind,
13119            shape: member_shape,
13120            leaf_start,
13121        });
13122        cursor += member_size;
13123    }
13124    Ok((descriptors, members))
13125}
13126
13127struct SelectionLeaf {
13128    call: ParallelLeafCall,
13129    outcome: Option<Result<ParallelAvroResult>>,
13130}
13131
13132/// Stable reference to one member of a durable selection group.
13133#[derive(Clone)]
13134pub struct DurableOperationHandle {
13135    ctx: WorkflowContext,
13136    pub key: SelectionKey,
13137    pub index: usize,
13138    pub kind: String,
13139    pub identity: String,
13140    pub base_sequence: u64,
13141    pub size: usize,
13142    pub selection_group_id: String,
13143    shape: ParallelShape,
13144}
13145
13146impl std::fmt::Debug for DurableOperationHandle {
13147    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13148        formatter
13149            .debug_struct("DurableOperationHandle")
13150            .field("key", &self.key)
13151            .field("index", &self.index)
13152            .field("kind", &self.kind)
13153            .field("identity", &self.identity)
13154            .field("base_sequence", &self.base_sequence)
13155            .field("size", &self.size)
13156            .field("selection_group_id", &self.selection_group_id)
13157            .finish()
13158    }
13159}
13160
13161impl DurableOperationHandle {
13162    /// Await this member after another member has already won the selection.
13163    pub fn await_result(&self) -> DurableOperationAwaitCall {
13164        DurableOperationAwaitCall {
13165            handle: self.clone(),
13166        }
13167    }
13168
13169    /// Request cancellation without affecting siblings. The future resolves
13170    /// to unit; only `SelectionOperationCancelled` history proves cancellation
13171    /// beat a concurrently committed terminal result.
13172    pub fn cancel(&self) -> CancelDurableOperationCall {
13173        CancelDurableOperationCall {
13174            handle: self.clone(),
13175            emitted: false,
13176        }
13177    }
13178}
13179
13180/// The one winner committed for a durable selection group.
13181#[derive(Debug)]
13182pub struct SelectionResult {
13183    pub key: SelectionKey,
13184    pub index: usize,
13185    pub kind: String,
13186    pub identity: String,
13187    pub value: Option<ParallelResult>,
13188    pub failure: Option<Error>,
13189    pub winner: DurableOperationHandle,
13190    pub handles: Vec<DurableOperationHandle>,
13191}
13192
13193impl SelectionResult {
13194    pub fn succeeded(&self) -> bool {
13195        self.failure.is_none()
13196    }
13197
13198    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13199        self.handles.iter().find(|handle| &handle.key == key)
13200    }
13201
13202    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13203        self.handles
13204            .iter()
13205            .filter(|handle| handle.index != self.index)
13206            .collect()
13207    }
13208
13209    pub fn into_result(self) -> Result<ParallelResult> {
13210        match (self.value, self.failure) {
13211            (Some(value), None) => Ok(value),
13212            (_, Some(error)) => Err(error),
13213            _ => Err(Error::WorkerLoop(
13214                "selection result contained neither a value nor a failure".to_string(),
13215            )),
13216        }
13217    }
13218}
13219
13220/// Future returned by [`WorkflowContext::select`].
13221pub struct SelectCall {
13222    ctx: WorkflowContext,
13223    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13224    members: Vec<SelectionMemberPlan>,
13225    leaves: Vec<SelectionLeaf>,
13226    group_id: Option<String>,
13227}
13228
13229impl SelectCall {
13230    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13231        Self {
13232            ctx,
13233            operations: Some(operations),
13234            members: Vec::new(),
13235            leaves: Vec::new(),
13236            group_id: None,
13237        }
13238    }
13239
13240    fn initialize(&mut self) -> Result<()> {
13241        let operations = self.operations.take().unwrap_or_default();
13242        let base_sequence = {
13243            let state = self
13244                .ctx
13245                .state
13246                .lock()
13247                .map_err(|_| Error::WorkflowStatePoisoned)?;
13248            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
13249                state.recorded_commands.get(state.command_cursor)
13250            {
13251                *sequence
13252            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
13253            {
13254                marker.selection_group_base_sequence
13255            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13256                recorded.sequence()
13257            } else {
13258                let last = state
13259                    .recorded_commands
13260                    .last()
13261                    .map(RecordedCommand::sequence)
13262                    .unwrap_or(0);
13263                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13264                    .and_then(|sequence| sequence.checked_add(1))
13265                    .ok_or(Error::TimerDurationOverflow)?
13266            }
13267        };
13268        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
13269        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
13270        {
13271            let mut state = self
13272                .ctx
13273                .state
13274                .lock()
13275                .map_err(|_| Error::WorkflowStatePoisoned)?;
13276            state.expand_cancellation_group(&descriptors)?;
13277            state.prepare_group_cancellation(&descriptors)?;
13278        }
13279        self.leaves = descriptors
13280            .into_iter()
13281            .map(|descriptor| SelectionLeaf {
13282                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
13283                outcome: None,
13284            })
13285            .collect();
13286        self.members = members;
13287        self.group_id = Some(group_id);
13288        Ok(())
13289    }
13290}
13291
13292impl Future for SelectCall {
13293    type Output = Result<SelectionResult>;
13294
13295    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13296        if self.operations.is_some() {
13297            if let Err(error) = self.initialize() {
13298                return Poll::Ready(Err(error));
13299            }
13300        }
13301
13302        for leaf in &mut self.leaves {
13303            if leaf.outcome.is_some() {
13304                continue;
13305            }
13306            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
13307                if outcome
13308                    .as_ref()
13309                    .err()
13310                    .is_some_and(workflow_task_integrity_error)
13311                {
13312                    return Poll::Ready(outcome.map(|_| unreachable!()));
13313                }
13314                leaf.outcome = Some(outcome);
13315            }
13316        }
13317
13318        if self
13319            .ctx
13320            .state
13321            .lock()
13322            .map_err(|_| Error::WorkflowStatePoisoned)?
13323            .cancellation_delivery_intent
13324            .is_some()
13325        {
13326            return Poll::Pending;
13327        }
13328
13329        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
13330            matches!(
13331                leaf.outcome,
13332                Some(Err(Error::CooperativeCancellationRequested(_)))
13333            )
13334        }) {
13335            return Poll::Ready(
13336                leaf.outcome
13337                    .take()
13338                    .expect("matched cancellation")
13339                    .map(|_| unreachable!()),
13340            );
13341        }
13342
13343        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
13344        let selection_member_range = self
13345            .members
13346            .first()
13347            .map(|member| member.base_sequence)
13348            .zip(self.leaves.len().try_into().ok())
13349            .map(|(base_sequence, size): (u64, u64)| {
13350                base_sequence..base_sequence.saturating_add(size)
13351            });
13352        let marker = {
13353            let mut state = match self.ctx.state.lock() {
13354                Ok(state) => state,
13355                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13356            };
13357            let marker = state
13358                .selection_markers
13359                .get(state.selection_marker_cursor)
13360                .cloned();
13361            if marker.is_none()
13362                && all_members_terminal
13363                && selection_member_range.as_ref().is_some_and(|member_range| {
13364                    state
13365                        .recorded_commands
13366                        .iter()
13367                        .any(|command| member_range.contains(&command.sequence()))
13368                })
13369            {
13370                // Terminal member history can be committed before the server's
13371                // SelectionResolved marker becomes visible to this task. That
13372                // marker is the durable barrier the selection is still waiting
13373                // on, so an otherwise commandless replay remains legitimately
13374                // pending instead of failing as an untracked yield.
13375                state.matched_recorded_pending = true;
13376            }
13377            marker
13378        };
13379        let Some(marker) = marker else {
13380            return Poll::Pending;
13381        };
13382        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
13383            || marker.selection_group_size != self.leaves.len()
13384            || self.members.first().map(|member| member.base_sequence)
13385                != Some(marker.selection_group_base_sequence)
13386        {
13387            return Poll::Ready(Err(invalid_recorded_history(
13388                "selection_group_shape_mismatch",
13389                marker.selection_group_base_sequence,
13390                self.group_id
13391                    .as_deref()
13392                    .unwrap_or("initialized selection group"),
13393                &marker.selection_group_id,
13394                "recorded selection group differs from current workflow code",
13395            )));
13396        }
13397        let Some(member_position) = self.members.iter().position(|member| {
13398            member.key == marker.member_key
13399                && member.index == marker.member_index
13400                && member.base_sequence == marker.member_base_sequence
13401                && member.size == marker.member_size
13402                && member.kind == marker.operation_kind
13403        }) else {
13404            return Poll::Ready(Err(invalid_recorded_history(
13405                "selection_member_shape_mismatch",
13406                marker.member_base_sequence,
13407                "winner member matching current workflow code",
13408                &format!("{:?}", marker.member_key),
13409                "recorded selection winner differs from the authored member identity",
13410            )));
13411        };
13412        let member = self.members[member_position].clone();
13413        let (handles, resolution_sequence) = {
13414            let mut state = match self.ctx.state.lock() {
13415                Ok(state) => state,
13416                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13417            };
13418            let identities = self
13419                .members
13420                .iter()
13421                .map(|candidate| {
13422                    selection_operation_identity(
13423                        &state,
13424                        &candidate.kind,
13425                        candidate.base_sequence,
13426                        candidate.size,
13427                    )
13428                })
13429                .collect::<Vec<_>>();
13430            if let Some((position, missing)) = identities
13431                .iter()
13432                .enumerate()
13433                .find(|(_, identity)| identity.is_empty())
13434                .map(|(position, identity)| (position, identity.clone()))
13435            {
13436                let candidate = &self.members[position];
13437                return Poll::Ready(Err(invalid_recorded_history(
13438                    "selection_operation_identity_missing",
13439                    candidate.base_sequence,
13440                    &format!(
13441                        "durable {} resource identity from scheduled/open history",
13442                        candidate.kind
13443                    ),
13444                    &missing,
13445                    "selection member history is missing its canonical durable identity",
13446                )));
13447            }
13448            let expected_winner_identity = &identities[member_position];
13449            let resolution_sequence = match validated_selection_resolution_sequence(
13450                &state,
13451                &marker,
13452                &member,
13453                expected_winner_identity,
13454            ) {
13455                Ok(sequence) => sequence,
13456                Err(error) => return Poll::Ready(Err(error)),
13457            };
13458            let handles = self
13459                .members
13460                .iter()
13461                .zip(identities)
13462                .map(|(member, identity)| DurableOperationHandle {
13463                    ctx: self.ctx.clone(),
13464                    key: member.key.clone(),
13465                    index: member.index,
13466                    kind: member.kind.clone(),
13467                    identity,
13468                    base_sequence: member.base_sequence,
13469                    size: member.size,
13470                    selection_group_id: marker.selection_group_id.clone(),
13471                    shape: member.shape.clone(),
13472                })
13473                .collect::<Vec<_>>();
13474            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
13475                return Poll::Ready(Err(error));
13476            }
13477            state.selection_marker_cursor += 1;
13478            (handles, resolution_sequence)
13479        };
13480
13481        let mut winner_failure = None;
13482        let mut flat_results = Vec::with_capacity(member.size);
13483        if marker.outcome == "failed" {
13484            let resolution_offset = match resolution_sequence
13485                .checked_sub(member.base_sequence)
13486                .and_then(|offset| usize::try_from(offset).ok())
13487            {
13488                Some(offset) if offset < member.size => offset,
13489                _ => {
13490                    return Poll::Ready(Err(invalid_recorded_history(
13491                        "selection_resolution_event_mismatch",
13492                        member.base_sequence,
13493                        "failure event within selected member bounds",
13494                        &resolution_sequence.to_string(),
13495                        "selection failure event is outside the authored member",
13496                    )))
13497                }
13498            };
13499            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
13500            match leaf.outcome.take() {
13501                Some(Err(error)) => winner_failure = Some(error),
13502                _ => {
13503                    return Poll::Ready(Err(invalid_recorded_history(
13504                        "selection_winner_outcome_mismatch",
13505                        member.base_sequence,
13506                        "exact failed terminal history referenced by SelectionResolved",
13507                        "missing or successful resolution event",
13508                        "selection winner marker disagrees with terminal operation history",
13509                    )))
13510                }
13511            }
13512        } else {
13513            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
13514                match leaf.outcome.take() {
13515                    Some(Ok(result)) => flat_results.push(result),
13516                    Some(Err(_)) => {
13517                        return Poll::Ready(Err(invalid_recorded_history(
13518                            "selection_winner_outcome_mismatch",
13519                            member.base_sequence,
13520                            "fully completed nested selection member",
13521                            "failed durable leaf",
13522                            "completed selection winner contains a failed leaf",
13523                        )))
13524                    }
13525                    None => {
13526                        return Poll::Ready(Err(invalid_recorded_history(
13527                            "selection_winner_unresolved",
13528                            member.base_sequence,
13529                            "terminal history for every completed winner leaf",
13530                            "pending member history",
13531                            "completed SelectionResolved member has an unfinished durable barrier",
13532                        )))
13533                    }
13534                }
13535            }
13536        }
13537        let value = if winner_failure.is_none() {
13538            let mut flat_results = flat_results.into_iter();
13539            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
13540            match value.into_json_result() {
13541                Ok(value) => Some(value),
13542                Err(error) => return Poll::Ready(Err(error)),
13543            }
13544        } else {
13545            None
13546        };
13547        let winner = handles[member_position].clone();
13548        self.ctx
13549            .state
13550            .lock()
13551            .map_err(|_| Error::WorkflowStatePoisoned)?
13552            .advance_cancellation_selection(&marker.selection_group_id);
13553        Poll::Ready(Ok(SelectionResult {
13554            key: winner.key.clone(),
13555            index: winner.index,
13556            kind: winner.kind.clone(),
13557            identity: winner.identity.clone(),
13558            value,
13559            failure: winner_failure,
13560            winner,
13561            handles,
13562        }))
13563    }
13564}
13565
13566fn selection_operation_identity(
13567    state: &WorkflowState,
13568    kind: &str,
13569    base_sequence: u64,
13570    size: usize,
13571) -> String {
13572    if kind == "group" {
13573        return format!("group:{base_sequence}:{size}");
13574    }
13575    let fields: &[&str] = match kind {
13576        "activity" => &["activity_execution_id"],
13577        "child" => &["child_workflow_run_id"],
13578        "timer" => &["timer_id"],
13579        "signal" => &["signal_wait_id"],
13580        "condition" => &["condition_wait_id"],
13581        _ => &[],
13582    };
13583    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
13584        for event in state
13585            .history_events
13586            .iter()
13587            .filter(|event| durable_event_sequence(event) == Some(sequence))
13588        {
13589            for field in fields {
13590                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
13591                    if !identity.is_empty() {
13592                        return identity.to_string();
13593                    }
13594                }
13595            }
13596        }
13597    }
13598    String::new()
13599}
13600
13601fn validated_selection_resolution_sequence(
13602    state: &WorkflowState,
13603    marker: &SelectionMarker,
13604    member: &SelectionMemberPlan,
13605    expected_identity: &str,
13606) -> Result<u64> {
13607    if expected_identity.is_empty() {
13608        return Err(invalid_recorded_history(
13609            "selection_operation_identity_missing",
13610            member.base_sequence,
13611            &format!(
13612                "durable {} resource identity from scheduled/open history",
13613                member.kind
13614            ),
13615            "missing operation identity",
13616            "selection member history is missing its canonical durable identity",
13617        ));
13618    }
13619    if marker.operation_identity != expected_identity {
13620        return Err(invalid_recorded_history(
13621            "selection_operation_identity_mismatch",
13622            member.base_sequence,
13623            expected_identity,
13624            &marker.operation_identity,
13625            "selection winner identity does not match durable scheduled/open history",
13626        ));
13627    }
13628
13629    let failure_types = [
13630        "ActivityFailed",
13631        "ActivityCancelled",
13632        "ActivityTimedOut",
13633        "ChildRunFailed",
13634        "ChildRunCancelled",
13635        "ChildRunTerminated",
13636    ];
13637    let success_types = [
13638        "ActivityCompleted",
13639        "ChildRunCompleted",
13640        "TimerFired",
13641        "SignalApplied",
13642        "ConditionWaitSatisfied",
13643        "ConditionWaitTimedOut",
13644    ];
13645    let terminal_types: &[&str] = if marker.outcome == "failed" {
13646        &failure_types
13647    } else {
13648        &success_types
13649    };
13650    let mut candidates = Vec::new();
13651    let member_commands = (member.base_sequence
13652        ..member.base_sequence.saturating_add(member.size as u64))
13653        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
13654        .map(|command| (command.sequence(), command))
13655        .collect::<BTreeMap<_, _>>();
13656    let mut resolved_conditions = BTreeSet::new();
13657    for event in state.history_events.iter() {
13658        let Some(sequence) = durable_event_sequence(event) else {
13659            continue;
13660        };
13661        let Some(command) = member_commands.get(&sequence) else {
13662            continue;
13663        };
13664        if !terminal_types.contains(&event.event_type.as_str()) {
13665            continue;
13666        }
13667        if matches!(command, RecordedCommand::ConditionWait { .. }) {
13668            if !matches!(
13669                event.event_type.as_str(),
13670                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
13671            ) && !(event.event_type == "TimerFired"
13672                && event.payload.get("timer_kind").and_then(Value::as_str)
13673                    == Some("condition_timeout"))
13674            {
13675                continue;
13676            }
13677            if !resolved_conditions.insert(sequence) {
13678                continue;
13679            }
13680        }
13681        let event_id = event
13682            .raw
13683            .get("id")
13684            .or_else(|| event.raw.get("event_id"))
13685            .and_then(Value::as_str)
13686            .filter(|value| !value.is_empty())
13687            .ok_or_else(|| {
13688                invalid_recorded_history(
13689                    "selection_resolution_event_id_missing",
13690                    member.base_sequence,
13691                    "terminal selection history with a durable event id",
13692                    &event.payload.to_string(),
13693                    "selection terminal history cannot be bound to its winner marker",
13694                )
13695            })?;
13696        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
13697    }
13698    let resolution = if marker.outcome == "failed" {
13699        candidates.first()
13700    } else {
13701        candidates.last()
13702    };
13703    let Some((event_id, event_type, sequence)) = resolution else {
13704        return Err(invalid_recorded_history(
13705            "selection_resolution_event_missing",
13706            member.base_sequence,
13707            "terminal history for the selected member",
13708            &format!("{:?}", marker.member_key),
13709            "selection winner marker has no matching durable terminal event",
13710        ));
13711    };
13712    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
13713        return Err(invalid_recorded_history(
13714            "selection_resolution_event_mismatch",
13715            member.base_sequence,
13716            &format!("{event_type}:{event_id}"),
13717            &format!(
13718                "{}:{}",
13719                marker.resolution_event_type, marker.resolution_event_id
13720            ),
13721            "selection winner marker does not reference the event that made its member terminal",
13722        ));
13723    }
13724    Ok(*sequence)
13725}
13726
13727fn selection_member_recorded_command(
13728    state: &WorkflowState,
13729    authored_sequence: u64,
13730) -> Option<&RecordedCommand> {
13731    let original = state
13732        .recorded_commands
13733        .iter()
13734        .find(|command| command.sequence() == authored_sequence)?;
13735    let RecordedCommand::ConditionWait {
13736        occurrence_id,
13737        parallel_group_path: Some(_),
13738        ..
13739    } = original
13740    else {
13741        return Some(original);
13742    };
13743    // Decoding proves each physical reopen has the same authored identity and
13744    // group path after a satisfied predecessor. Only its latest wait can make
13745    // this logical member terminal.
13746    state
13747        .recorded_commands
13748        .iter()
13749        .filter(|command| {
13750            matches!(command, RecordedCommand::ConditionWait {
13751                occurrence_id: candidate, ..
13752            } if candidate == occurrence_id)
13753        })
13754        .max_by_key(|command| command.sequence())
13755}
13756
13757fn recorded_selection_member_outcome(
13758    state: &WorkflowState,
13759    handle: &DurableOperationHandle,
13760) -> Result<Option<ParallelResult>> {
13761    for event in state.history_events.iter() {
13762        let Some(sequence) = durable_event_sequence(event) else {
13763            continue;
13764        };
13765        if sequence < handle.base_sequence
13766            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
13767            || !matches!(
13768                event.event_type.as_str(),
13769                "ActivityFailed"
13770                    | "ActivityCancelled"
13771                    | "ActivityTimedOut"
13772                    | "ChildRunFailed"
13773                    | "ChildRunCancelled"
13774                    | "ChildRunTerminated"
13775            )
13776        {
13777            continue;
13778        }
13779        let Some(command) = state
13780            .recorded_commands
13781            .iter()
13782            .find(|command| command.sequence() == sequence)
13783        else {
13784            continue;
13785        };
13786        match command {
13787            RecordedCommand::Activity {
13788                outcome: Some(Err(failure)),
13789                ..
13790            } => return Err(Error::ActivityFailed(failure.clone())),
13791            RecordedCommand::ChildWorkflow {
13792                outcome: Some(Err(failure)),
13793                ..
13794            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
13795            _ => {}
13796        }
13797    }
13798
13799    let mut results = Vec::with_capacity(handle.size);
13800    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13801        let Some(command) = selection_member_recorded_command(state, sequence) else {
13802            return Ok(None);
13803        };
13804        let result = match command {
13805            RecordedCommand::Activity { outcome, .. } => match outcome {
13806                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
13807                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
13808                None => return Ok(None),
13809            },
13810            RecordedCommand::Timer { fired, .. } => {
13811                if !fired {
13812                    return Ok(None);
13813                }
13814                ParallelAvroResult::Timer
13815            }
13816            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
13817                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
13818                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
13819                None => return Ok(None),
13820            },
13821            RecordedCommand::SignalWait { value, .. } => match value {
13822                Some(value) => ParallelAvroResult::Signal(value.clone()),
13823                None => return Ok(None),
13824            },
13825            RecordedCommand::ConditionWait { result, .. } => match result {
13826                Some(result) => ParallelAvroResult::Condition(*result),
13827                None => return Ok(None),
13828            },
13829            other => {
13830                return Err(command_mismatch(
13831                    other,
13832                    format!("selected {} member", handle.kind),
13833                ))
13834            }
13835        };
13836        results.push(result);
13837    }
13838    let mut results = results.into_iter();
13839    parallel_results_for_shape(&handle.shape, &mut results)
13840        .into_json_result()
13841        .map(Some)
13842}
13843
13844fn recorded_selection_member_is_terminal(
13845    state: &WorkflowState,
13846    handle: &DurableOperationHandle,
13847) -> bool {
13848    let mut completed = 0usize;
13849    let mut all_completed = true;
13850    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13851        let Some(command) = selection_member_recorded_command(state, sequence) else {
13852            all_completed = false;
13853            continue;
13854        };
13855        let terminal = match command {
13856            RecordedCommand::Activity {
13857                outcome: Some(Err(_)),
13858                ..
13859            }
13860            | RecordedCommand::ChildWorkflow {
13861                outcome: Some(Err(_)),
13862                ..
13863            } => return true,
13864            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13865            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13866            RecordedCommand::Timer { fired, .. } => *fired,
13867            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13868            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13869            RecordedCommand::SearchAttributes { .. }
13870            | RecordedCommand::CancellationScope { .. }
13871            | RecordedCommand::SideEffect { .. }
13872            | RecordedCommand::VersionMarker { .. }
13873            | RecordedCommand::Memo { .. }
13874            | RecordedCommand::CancellationBoundary { .. }
13875            | RecordedCommand::CancellationGroup { .. } => false,
13876        };
13877        if !terminal {
13878            all_completed = false;
13879            continue;
13880        }
13881        completed += 1;
13882    }
13883    all_completed && completed == handle.size
13884}
13885
13886fn selection_cancellation_for_handle(
13887    state: &WorkflowState,
13888    handle: &DurableOperationHandle,
13889) -> Result<bool> {
13890    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13891        recorded.selection_group_id == handle.selection_group_id
13892            && recorded.member_base_sequence == handle.base_sequence
13893    }) else {
13894        return Ok(false);
13895    };
13896    validate_selection_cancellation_marker(marker, handle)?;
13897    Ok(true)
13898}
13899
13900fn validate_selection_cancellations_for_handles(
13901    state: &WorkflowState,
13902    handles: &[DurableOperationHandle],
13903) -> Result<()> {
13904    let Some(group_id) = handles
13905        .first()
13906        .map(|handle| handle.selection_group_id.as_str())
13907    else {
13908        return Ok(());
13909    };
13910    for marker in state
13911        .cancelled_selection_members
13912        .iter()
13913        .filter(|marker| marker.selection_group_id == group_id)
13914    {
13915        let Some(handle) = handles
13916            .iter()
13917            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13918        else {
13919            return Err(invalid_recorded_history(
13920                "selection_cancellation_member_mismatch",
13921                marker.member_base_sequence,
13922                "SelectionOperationCancelled matching an authored selection handle",
13923                &format!("{marker:?}"),
13924                "selection cancellation member base does not name an authored member",
13925            ));
13926        };
13927        validate_selection_cancellation_marker(marker, handle)?;
13928    }
13929    Ok(())
13930}
13931
13932fn validate_selection_cancellation_marker(
13933    marker: &SelectionCancellation,
13934    handle: &DurableOperationHandle,
13935) -> Result<()> {
13936    if marker.selection_group_id != handle.selection_group_id
13937        || marker.member_key != handle.key
13938        || marker.member_index != handle.index
13939        || marker.member_base_sequence != handle.base_sequence
13940        || marker.member_size != handle.size
13941        || marker.operation_kind != handle.kind
13942        || marker.operation_identity != handle.identity
13943    {
13944        return Err(invalid_recorded_history(
13945            "selection_cancellation_member_mismatch",
13946            handle.base_sequence,
13947            "SelectionOperationCancelled matching the authored selection handle",
13948            &format!("{marker:?}"),
13949            "selection cancellation history targets different authored member metadata",
13950        ));
13951    }
13952    Ok(())
13953}
13954
13955/// Future returned by [`DurableOperationHandle::await_result`].
13956pub struct DurableOperationAwaitCall {
13957    handle: DurableOperationHandle,
13958}
13959
13960impl Future for DurableOperationAwaitCall {
13961    type Output = Result<ParallelResult>;
13962
13963    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13964        let mut state = match self.handle.ctx.state.lock() {
13965            Ok(state) => state,
13966            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13967        };
13968        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13969            return Poll::Ready(Err(error));
13970        }
13971        match state.prepare_selection_handle_cancellation(&self.handle) {
13972            Ok(true) => return Poll::Pending,
13973            Ok(false) => {}
13974            Err(error) => return Poll::Ready(Err(error)),
13975        }
13976        match selection_cancellation_for_handle(&state, &self.handle) {
13977            Err(error) => return Poll::Ready(Err(error)),
13978            Ok(false) => {}
13979            Ok(true) => {
13980                state.advance_cancellation_receipt(
13981                    &self.handle.selection_group_id,
13982                    self.handle.base_sequence,
13983                );
13984                return Poll::Ready(Err(Error::DurableOperationCancelled(
13985                    DurableOperationCancelled {
13986                        selection_group_id: self.handle.selection_group_id.clone(),
13987                        member_key: self.handle.key.clone(),
13988                        member_index: self.handle.index,
13989                        operation_kind: self.handle.kind.clone(),
13990                        operation_identity: self.handle.identity.clone(),
13991                    },
13992                )));
13993            }
13994        }
13995        match recorded_selection_member_outcome(&state, &self.handle) {
13996            Ok(Some(result)) => {
13997                state.advance_cancellation_handle(&self.handle, false);
13998                Poll::Ready(Ok(result))
13999            }
14000            Ok(None) => Poll::Pending,
14001            Err(error) => {
14002                if !workflow_task_integrity_error(&error) {
14003                    state.advance_cancellation_handle(&self.handle, true);
14004                }
14005                Poll::Ready(Err(error))
14006            }
14007        }
14008    }
14009}
14010
14011fn validate_selection_delivery_handle(
14012    state: &WorkflowState,
14013    handle: &DurableOperationHandle,
14014) -> Result<()> {
14015    let path = state
14016        .recorded_commands
14017        .iter()
14018        .find(|command| command.sequence() == handle.base_sequence)
14019        .and_then(|command| match command {
14020            RecordedCommand::Activity {
14021                parallel_group_path,
14022                ..
14023            }
14024            | RecordedCommand::ChildWorkflow {
14025                parallel_group_path,
14026                ..
14027            }
14028            | RecordedCommand::Timer {
14029                parallel_group_path,
14030                ..
14031            }
14032            | RecordedCommand::SignalWait {
14033                parallel_group_path,
14034                ..
14035            }
14036            | RecordedCommand::ConditionWait {
14037                parallel_group_path,
14038                ..
14039            } => parallel_group_path.as_ref(),
14040            _ => None,
14041        })
14042        .and_then(|path| path.first());
14043    let matches = path.is_some_and(|entry| {
14044        entry.parallel_group_mode.as_deref() == Some("select")
14045            && entry.parallel_group_id == handle.selection_group_id
14046            && entry.selection_member_key.as_ref() == Some(&handle.key)
14047            && entry.selection_member_index == Some(handle.index)
14048            && entry.selection_member_base_sequence == Some(handle.base_sequence)
14049            && entry.selection_member_size == Some(handle.size)
14050            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
14051    });
14052    if !matches
14053        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
14054            != handle.identity
14055    {
14056        return Err(invalid_recorded_history(
14057            "cooperative_cancellation_call_mismatch",
14058            handle.base_sequence,
14059            "selection handle matching its authored durable identity",
14060            &format!("{handle:?}"),
14061            "selection handle identity or member metadata changed before cancellation replay",
14062        ));
14063    }
14064    Ok(())
14065}
14066
14067/// Future returned by [`DurableOperationHandle::cancel`].
14068pub struct CancelDurableOperationCall {
14069    handle: DurableOperationHandle,
14070    emitted: bool,
14071}
14072
14073impl Future for CancelDurableOperationCall {
14074    type Output = Result<()>;
14075
14076    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14077        let ctx = self.handle.ctx.clone();
14078        let mut state = match ctx.state.lock() {
14079            Ok(state) => state,
14080            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14081        };
14082        match selection_cancellation_for_handle(&state, &self.handle) {
14083            Err(error) => return Poll::Ready(Err(error)),
14084            Ok(true) => {
14085                state.advance_cancellation_receipt(
14086                    &self.handle.selection_group_id,
14087                    self.handle.base_sequence,
14088                );
14089                return Poll::Ready(Ok(()));
14090            }
14091            Ok(false) => {}
14092        }
14093        if recorded_selection_member_is_terminal(&state, &self.handle) {
14094            return Poll::Ready(Ok(()));
14095        }
14096        if !self.emitted {
14097            state.commands.push(json!({
14098                "type": "cancel_selection_operation",
14099                "selection_group_id": self.handle.selection_group_id,
14100                "member_key": self.handle.key,
14101                "member_index": self.handle.index,
14102                "member_base_sequence": self.handle.base_sequence,
14103                "member_size": self.handle.size,
14104                "operation_kind": self.handle.kind,
14105                "operation_identity": self.handle.identity,
14106            }));
14107            self.emitted = true;
14108        }
14109        // The cancellation command is only a request. Do not expose workflow
14110        // state after cancel until committed SelectionOperationCancelled
14111        // history proves that the request won the race with member completion.
14112        Poll::Pending
14113    }
14114}
14115
14116trait PollNestedResultExt<T> {
14117    fn flatten_result(self) -> Poll<Result<T>>;
14118}
14119
14120impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
14121    fn flatten_result(self) -> Poll<Result<T>> {
14122        match self {
14123            Poll::Ready(Ok(result)) => Poll::Ready(result),
14124            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14125            Poll::Pending => Poll::Pending,
14126        }
14127    }
14128}
14129
14130struct SagaCompensation {
14131    activity_type: String,
14132    options: ActivityOptions,
14133    arguments: AvroValue,
14134    registration_order: usize,
14135}
14136
14137/// Workflow-local deterministic saga compensation helper.
14138///
14139/// Register each compensation only after its forward step succeeds. Passing
14140/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
14141/// reverse registration order after any failure, including cooperative
14142/// cancellation. Each compensation is an ordinary durable activity, so replay,
14143/// duplicate delivery, and worker restart use existing history semantics.
14144pub struct Saga {
14145    ctx: WorkflowContext,
14146    compensations: Vec<SagaCompensation>,
14147}
14148
14149impl Saga {
14150    fn new(ctx: WorkflowContext) -> Self {
14151        Self {
14152            ctx,
14153            compensations: Vec::new(),
14154        }
14155    }
14156
14157    pub fn add_compensation<T: Serialize>(
14158        &mut self,
14159        activity_type: impl Into<String>,
14160        args: T,
14161    ) -> Result<&mut Self> {
14162        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
14163    }
14164
14165    pub fn add_compensation_with_options<T: Serialize>(
14166        &mut self,
14167        activity_type: impl Into<String>,
14168        options: ActivityOptions,
14169        args: T,
14170    ) -> Result<&mut Self> {
14171        let activity_type = activity_type.into();
14172        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
14173            return Err(Error::Codec(
14174                "saga compensation activity type must be non-empty without surrounding whitespace"
14175                    .to_string(),
14176            ));
14177        }
14178        options.validate().map_err(Error::InvalidActivityOptions)?;
14179        let arguments = AvroValue::from_serialize(&args)?;
14180        let registration_order = self.compensations.len() + 1;
14181        self.compensations.push(SagaCompensation {
14182            activity_type,
14183            options,
14184            arguments,
14185            registration_order,
14186        });
14187        Ok(self)
14188    }
14189
14190    /// Compensate `initiating_failure` and return the failure that must remain.
14191    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14192        let _shield = match self.ctx.cancellation_shield() {
14193            Ok(shield) => shield,
14194            Err(error) => return error,
14195        };
14196        while let Some(compensation) = self.compensations.pop() {
14197            if let Err(compensation_failure) = self
14198                .ctx
14199                .activity_with_options(
14200                    compensation.activity_type.clone(),
14201                    compensation.options,
14202                    compensation.arguments,
14203                )
14204                .await
14205            {
14206                if workflow_task_integrity_error(&compensation_failure) {
14207                    return compensation_failure;
14208                }
14209                return Error::SagaCompensationFailed(SagaCompensationFailure {
14210                    initiating_failure: Box::new(initiating_failure),
14211                    compensation_failure: Box::new(compensation_failure),
14212                    compensation_activity_type: compensation.activity_type,
14213                    compensation_registration_order: compensation.registration_order,
14214                });
14215            }
14216        }
14217        initiating_failure
14218    }
14219
14220    /// Return a successful forward value or compensate and preserve its failure.
14221    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14222        match outcome {
14223            Ok(value) => Ok(value),
14224            Err(error) => Err(self.compensate(error).await),
14225        }
14226    }
14227}
14228
14229pub struct ActivityCall {
14230    ctx: WorkflowContext,
14231    activity_type: String,
14232    options: ActivityOptions,
14233    worker_session: Option<WorkerSessionOptions>,
14234    args: Option<Result<AvroValue>>,
14235    scheduled: bool,
14236    local: bool,
14237    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
14238    parallel_group_path: Vec<ParallelGroupMetadata>,
14239}
14240
14241impl ActivityCall {
14242    fn poll_avro_value(
14243        mut self: Pin<&mut Self>,
14244        _cx: &mut TaskContext<'_>,
14245    ) -> Poll<Result<AvroValue>> {
14246        let ctx = self.ctx.clone();
14247        let mut state = match ctx.state.lock() {
14248            Ok(state) => state,
14249            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14250        };
14251
14252        if let Some(result) = &self.local_result {
14253            return match result.lock() {
14254                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
14255                    Poll::Ready(result.map_err(Error::ActivityFailed))
14256                }),
14257                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14258            };
14259        }
14260        if self.scheduled {
14261            return Poll::Pending;
14262        }
14263
14264        let options = match self.options.validate() {
14265            Ok(options) => options,
14266            Err(error) => {
14267                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
14268            }
14269        };
14270        if self.local {
14271            if self.worker_session.is_some() {
14272                return Poll::Ready(Err(Error::WorkerLoop(
14273                    "local activities cannot use worker-session routing".into(),
14274                )));
14275            }
14276            if let Err(error) = local_activity::validate(&options) {
14277                return Poll::Ready(Err(error));
14278            }
14279        }
14280        let session = match self
14281            .worker_session
14282            .as_ref()
14283            .map(WorkerSessionOptions::to_wire)
14284            .transpose()
14285        {
14286            Ok(value) => value,
14287            Err(error) => return Poll::Ready(Err(error)),
14288        };
14289        let session_queue = session
14290            .as_ref()
14291            .and_then(|session| session["queue"].as_str());
14292        let task_queue = options
14293            .task_queue
14294            .clone()
14295            .or_else(|| session_queue.map(str::to_owned))
14296            .unwrap_or_else(|| state.task_queue.clone());
14297        if session_queue.is_some_and(|queue| queue != task_queue) {
14298            return Poll::Ready(Err(Error::WorkerLoop(
14299                "worker-session queue must match the activity task queue".into(),
14300            )));
14301        }
14302        let current_recorded_options = RecordedActivityOptions {
14303            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
14304            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
14305            retry_policy: current_activity_retry_snapshot(&options),
14306            worker_session: session,
14307        };
14308
14309        let cursor = state.command_cursor;
14310        let call_kind = if self.local {
14311            CancellationCallKind::LocalActivity
14312        } else {
14313            CancellationCallKind::Activity
14314        };
14315        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14316            return Poll::Ready(Err(error));
14317        }
14318        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
14319            Ok(recorded) => recorded,
14320            Err(error) => return Poll::Ready(Err(error)),
14321        };
14322        if let Some(recorded) = recorded {
14323            let sequence = recorded.sequence();
14324            match recorded {
14325                RecordedCommand::Activity {
14326                    activity_type,
14327                    cancellation_policy,
14328                    options: recorded_options,
14329                    outcome,
14330                    parallel_group_path,
14331                    ..
14332                } => {
14333                    let current_policy = options
14334                        .cancellation_policy
14335                        .unwrap_or(CancellationPolicy::TryCancel)
14336                        .as_str();
14337                    if cancellation_policy != current_policy {
14338                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14339                            ReplayFailure::new(
14340                                "activity_cancellation_policy_changed",
14341                                Some(sequence),
14342                                Some(cancellation_policy),
14343                                Some(current_policy.to_string()),
14344                                "Activity cancellation policy changed during replay",
14345                            ),
14346                        )));
14347                    }
14348                    if let Err(error) = ensure_parallel_path_matches(
14349                        sequence,
14350                        parallel_group_path.as_deref(),
14351                        &self.parallel_group_path,
14352                    ) {
14353                        return Poll::Ready(Err(error));
14354                    }
14355                    if let Some(recorded_type) = activity_type {
14356                        if recorded_type != self.activity_type {
14357                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14358                                ReplayFailure::new(
14359                                    "recorded_command_detail_mismatch",
14360                                    Some(sequence),
14361                                    Some(format!("activity:{recorded_type}")),
14362                                    Some(format!("activity:{}", self.activity_type)),
14363                                    "recorded activity type differs from the current workflow command",
14364                                ),
14365                            )));
14366                        }
14367                    }
14368                    if let Some(recorded_options) = recorded_options {
14369                        if recorded_options.worker_session
14370                            != current_recorded_options.worker_session
14371                        {
14372                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14373                                "activity_worker_session_mismatch", Some(sequence),
14374                                Some(activity_options_description(&recorded_options)),
14375                                Some(activity_options_description(&current_recorded_options)),
14376                                "recorded worker-session routing differs from the current activity",
14377                            ))));
14378                        }
14379                        if !recorded_options
14380                            .task_queue
14381                            .matches_current(&current_recorded_options.task_queue)
14382                        {
14383                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14384                                ReplayFailure::new(
14385                                    "activity_task_queue_mismatch",
14386                                    Some(sequence),
14387                                    Some(activity_options_description(&recorded_options)),
14388                                    Some(activity_options_description(&current_recorded_options)),
14389                                    "recorded activity task queue differs from the current workflow command",
14390                                ),
14391                            )));
14392                        }
14393                        if (self.local
14394                            && matches!(
14395                                recorded_options.execution_mode,
14396                                RecordedSnapshotValue::Unknown
14397                            ))
14398                            || !recorded_options
14399                                .execution_mode
14400                                .matches_current(&current_recorded_options.execution_mode)
14401                        {
14402                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14403                                ReplayFailure::new(
14404                                    "activity_execution_mode_mismatch",
14405                                    Some(sequence),
14406                                    Some(activity_options_description(&recorded_options)),
14407                                    Some(activity_options_description(&current_recorded_options)),
14408                                    "recorded activity execution mode differs from the current workflow command",
14409                                ),
14410                            )));
14411                        }
14412                        if !recorded_options
14413                            .retry_policy
14414                            .matches_current(&current_recorded_options.retry_policy)
14415                        {
14416                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14417                                ReplayFailure::new(
14418                                    "activity_retry_policy_mismatch",
14419                                    Some(sequence),
14420                                    Some(activity_options_description(&recorded_options)),
14421                                    Some(activity_options_description(&current_recorded_options)),
14422                                    "recorded activity retry policy differs from the current workflow command",
14423                                ),
14424                            )));
14425                        }
14426                    }
14427                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
14428                        return Poll::Ready(Err(error));
14429                    }
14430                    match state.prepare_scalar_cancellation(
14431                        cursor,
14432                        call_kind,
14433                        &self.parallel_group_path,
14434                    ) {
14435                        Ok(true) => {
14436                            self.scheduled = true;
14437                            return Poll::Pending;
14438                        }
14439                        Ok(false) => {}
14440                        Err(error) => return Poll::Ready(Err(error)),
14441                    }
14442                    state.command_cursor += 1;
14443                    if let Some(outcome) = outcome {
14444                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14445                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
14446                    }
14447                    state.matched_recorded_pending = true;
14448                    self.scheduled = true;
14449                    return Poll::Pending;
14450                }
14451                other => {
14452                    return Poll::Ready(Err(command_mismatch(
14453                        &other,
14454                        format!("activity:{}", self.activity_type),
14455                    )));
14456                }
14457            }
14458        }
14459
14460        if !self.scheduled {
14461            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14462                Ok(args) => args,
14463                Err(error) => return Poll::Ready(Err(error)),
14464            };
14465            let arguments = normalize_avro_arguments(args);
14466            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
14467                Ok(envelope) => envelope,
14468                Err(error) => return Poll::Ready(Err(error)),
14469            };
14470
14471            let mut command = serde_json::Map::from_iter([
14472                (
14473                    "type".to_string(),
14474                    json!(if self.local {
14475                        "record_local_activity"
14476                    } else {
14477                        "schedule_activity"
14478                    }),
14479                ),
14480                (
14481                    "activity_type".to_string(),
14482                    json!(self.activity_type.clone()),
14483                ),
14484                ("queue".to_string(), json!(task_queue)),
14485                ("arguments".to_string(), envelope),
14486            ]);
14487            for (field, value) in [
14488                ("start_to_close_timeout", options.start_to_close_timeout),
14489                (
14490                    "schedule_to_start_timeout",
14491                    options.schedule_to_start_timeout,
14492                ),
14493                (
14494                    "schedule_to_close_timeout",
14495                    options.schedule_to_close_timeout,
14496                ),
14497                ("heartbeat_timeout", options.heartbeat_timeout),
14498            ] {
14499                if let Some(value) = value {
14500                    command.insert(field.to_string(), json!(value));
14501                }
14502            }
14503            if let Some(retry_policy) = &options.retry_policy {
14504                command.insert("retry_policy".to_string(), retry_policy.clone());
14505            }
14506            if let Some(policy) = options.cancellation_policy {
14507                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
14508            }
14509            if let Some(session) = current_recorded_options.worker_session {
14510                command.insert("worker_session".into(), session);
14511            }
14512            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14513            ctx.apply_scope_membership(&mut command);
14514            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
14515                Ok(true) => {
14516                    self.scheduled = true;
14517                    return Poll::Pending;
14518                }
14519                Ok(false) => {}
14520                Err(error) => return Poll::Ready(Err(error)),
14521            }
14522            if self.local {
14523                command.remove("queue");
14524                command.insert("execution_mode".into(), json!("local"));
14525                let result = Arc::new(Mutex::new(None));
14526                let command_index = state.commands.len();
14527                state.local_activity_requests.push(local_activity::Request {
14528                    command_index,
14529                    options,
14530                    arguments,
14531                    result: result.clone(),
14532                });
14533                self.local_result = Some(result);
14534            }
14535            state.commands.push(Value::Object(command));
14536            self.scheduled = true;
14537        }
14538
14539        Poll::Pending
14540    }
14541}
14542
14543impl Future for ActivityCall {
14544    type Output = Result<Value>;
14545
14546    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14547        match self.poll_avro_value(cx) {
14548            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
14549            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14550            Poll::Pending => Poll::Pending,
14551        }
14552    }
14553}
14554
14555/// Future returned by [`WorkflowContext::sleep`].
14556pub struct TimerCall {
14557    ctx: WorkflowContext,
14558    delay_seconds: Option<u64>,
14559    scheduled: bool,
14560    matched_pending: bool,
14561    parallel_group_path: Vec<ParallelGroupMetadata>,
14562}
14563
14564impl Future for TimerCall {
14565    type Output = Result<()>;
14566
14567    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14568        if self.matched_pending {
14569            return Poll::Pending;
14570        }
14571
14572        let ctx = self.ctx.clone();
14573        let Some(requested_delay) = self.delay_seconds else {
14574            return Poll::Ready(Err(Error::TimerDurationOverflow));
14575        };
14576        let mut state = match ctx.state.lock() {
14577            Ok(state) => state,
14578            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14579        };
14580
14581        let cursor = state.command_cursor;
14582        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14583            return Poll::Ready(Err(error));
14584        }
14585        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
14586        {
14587            Ok(recorded) => recorded,
14588            Err(error) => return Poll::Ready(Err(error)),
14589        };
14590        if let Some(recorded) = recorded {
14591            match recorded {
14592                RecordedCommand::Timer {
14593                    sequence,
14594                    delay_seconds,
14595                    fired,
14596                    parallel_group_path,
14597                    ..
14598                } => {
14599                    if let Err(error) =
14600                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
14601                    {
14602                        return Poll::Ready(Err(error));
14603                    }
14604                    if let Err(error) = ensure_parallel_path_matches(
14605                        sequence,
14606                        parallel_group_path.as_deref(),
14607                        &self.parallel_group_path,
14608                    ) {
14609                        return Poll::Ready(Err(error));
14610                    }
14611                    if delay_seconds != requested_delay {
14612                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14613                            ReplayFailure::new(
14614                                "timer_delay_mismatch",
14615                                Some(sequence),
14616                                Some(format!("timer:{delay_seconds}s")),
14617                                Some(format!("timer:{requested_delay}s")),
14618                                "recorded timer delay differs from the current workflow command",
14619                            ),
14620                        )));
14621                    }
14622                    if let Err(error) =
14623                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
14624                    {
14625                        return Poll::Ready(Err(error));
14626                    }
14627                    match state.prepare_scalar_cancellation(
14628                        cursor,
14629                        CancellationCallKind::Timer,
14630                        &self.parallel_group_path,
14631                    ) {
14632                        Ok(true) => {
14633                            self.scheduled = true;
14634                            self.matched_pending = true;
14635                            return Poll::Pending;
14636                        }
14637                        Ok(false) => {}
14638                        Err(error) => return Poll::Ready(Err(error)),
14639                    }
14640                    state.command_cursor += 1;
14641                    if fired {
14642                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14643                        return Poll::Ready(Ok(()));
14644                    }
14645                    state.matched_recorded_pending = true;
14646                    self.scheduled = true;
14647                    self.matched_pending = true;
14648                    return Poll::Pending;
14649                }
14650                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
14651            }
14652        }
14653
14654        if !self.scheduled {
14655            let mut command = serde_json::Map::from_iter([
14656                ("type".to_string(), json!("start_timer")),
14657                ("delay_seconds".to_string(), json!(requested_delay)),
14658            ]);
14659            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
14660                Ok(Some(proof)) => {
14661                    command.insert("cancellation_cleanup".into(), proof);
14662                }
14663                Ok(None) => {}
14664                Err(error) => return Poll::Ready(Err(error)),
14665            }
14666            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14667            ctx.apply_scope_membership(&mut command);
14668            match state.prepare_scalar_cancellation(
14669                cursor,
14670                CancellationCallKind::Timer,
14671                &self.parallel_group_path,
14672            ) {
14673                Ok(true) => {
14674                    self.scheduled = true;
14675                    self.matched_pending = true;
14676                    return Poll::Pending;
14677                }
14678                Ok(false) => {}
14679                Err(error) => return Poll::Ready(Err(error)),
14680            }
14681            state.commands.push(Value::Object(command));
14682            self.scheduled = true;
14683        }
14684
14685        Poll::Pending
14686    }
14687}
14688
14689/// Future returned by [`WorkflowContext::wait_condition`].
14690pub struct ConditionWaitCall {
14691    ctx: WorkflowContext,
14692    options: ConditionWaitOptions,
14693    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
14694    occurrence_id: Option<String>,
14695    opened_wait: bool,
14696    parallel_group_path: Vec<ParallelGroupMetadata>,
14697}
14698
14699impl Future for ConditionWaitCall {
14700    type Output = Result<ConditionWaitResult>;
14701
14702    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14703        if self.opened_wait {
14704            return Poll::Pending;
14705        }
14706
14707        let options = match self.options.validate() {
14708            Ok(options) => options,
14709            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
14710        };
14711        let ctx = self.ctx.clone();
14712        let occurrence_id = match self.occurrence_id.as_ref() {
14713            Some(occurrence_id) => occurrence_id.clone(),
14714            None => {
14715                let mut state = match ctx.state.lock() {
14716                    Ok(state) => state,
14717                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14718                };
14719                let ordinal = state.condition_wait_occurrence_counter;
14720                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
14721                    Some(next) => next,
14722                    None => {
14723                        return Poll::Ready(Err(Error::WorkerLoop(
14724                            "condition wait occurrence counter overflowed".to_string(),
14725                        )))
14726                    }
14727                };
14728                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
14729                drop(state);
14730                self.occurrence_id = Some(occurrence_id.clone());
14731                occurrence_id
14732            }
14733        };
14734
14735        let recorded_result = {
14736            let mut state = match ctx.state.lock() {
14737                Ok(state) => state,
14738                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14739            };
14740            let initial_cursor = state.command_cursor;
14741            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
14742                return Poll::Ready(Err(error));
14743            }
14744            let recorded = match state
14745                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
14746            {
14747                Ok(recorded) => recorded,
14748                Err(error) => return Poll::Ready(Err(error)),
14749            };
14750            let Some(recorded) = recorded else {
14751                drop(state);
14752                return self.poll_new_condition(options);
14753            };
14754            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
14755                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
14756            }
14757
14758            let mut cursor = state.command_cursor;
14759            let mut result = None;
14760            let mut pending_delivery = false;
14761            loop {
14762                if cursor > initial_cursor
14763                    && matches!(
14764                        state.recorded_commands.get(cursor),
14765                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
14766                    )
14767                {
14768                    break;
14769                }
14770                let recorded = match state
14771                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
14772                {
14773                    Ok(recorded) => recorded,
14774                    Err(error) => return Poll::Ready(Err(error)),
14775                };
14776                let Some(RecordedCommand::ConditionWait {
14777                    sequence,
14778                    occurrence_id: ref recorded_occurrence_id,
14779                    ref condition_key,
14780                    ref predicate_identity,
14781                    timeout_seconds,
14782                    result: recorded_result,
14783                    ref parallel_group_path,
14784                    ..
14785                }) = recorded
14786                else {
14787                    break;
14788                };
14789
14790                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
14791                    break;
14792                }
14793                if let Err(error) = ensure_parallel_path_matches(
14794                    sequence,
14795                    parallel_group_path.as_deref(),
14796                    &self.parallel_group_path,
14797                ) {
14798                    return Poll::Ready(Err(error));
14799                }
14800                if let Err(error) = validate_recorded_condition_wait(
14801                    sequence,
14802                    recorded_occurrence_id,
14803                    condition_key.as_deref(),
14804                    predicate_identity,
14805                    timeout_seconds,
14806                    &occurrence_id,
14807                    &options,
14808                ) {
14809                    return Poll::Ready(Err(error));
14810                }
14811                if result == Some(ConditionWaitResult::TimedOut) {
14812                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14813                        "condition_wait_reopened_after_timeout",
14814                        Some(sequence),
14815                        Some("timed-out condition is terminal".to_string()),
14816                        Some("another physical wait-open".to_string()),
14817                        "condition history reopened one logical wait after its durable timeout",
14818                    ))));
14819                }
14820                if let Err(error) =
14821                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
14822                {
14823                    return Poll::Ready(Err(error));
14824                }
14825                match state.prepare_scalar_cancellation(
14826                    cursor,
14827                    CancellationCallKind::Condition,
14828                    &self.parallel_group_path,
14829                ) {
14830                    Ok(pending) => pending_delivery |= pending,
14831                    Err(error) => return Poll::Ready(Err(error)),
14832                }
14833                result = recorded_result;
14834                if result.is_some() {
14835                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14836                }
14837                cursor += 1;
14838            }
14839            state.command_cursor = cursor;
14840            if pending_delivery {
14841                self.opened_wait = true;
14842                return Poll::Pending;
14843            }
14844            result
14845        };
14846
14847        if let Some(result) = recorded_result {
14848            return Poll::Ready(Ok(result));
14849        }
14850
14851        self.poll_open_condition(options, true)
14852    }
14853}
14854
14855impl ConditionWaitCall {
14856    fn poll_new_condition(
14857        self: Pin<&mut Self>,
14858        options: ValidatedConditionWaitOptions,
14859    ) -> Poll<Result<ConditionWaitResult>> {
14860        self.poll_open_condition(options, false)
14861    }
14862
14863    fn poll_open_condition(
14864        mut self: Pin<&mut Self>,
14865        options: ValidatedConditionWaitOptions,
14866        recorded_wait: bool,
14867    ) -> Poll<Result<ConditionWaitResult>> {
14868        {
14869            let ctx = self.ctx.clone();
14870            let mut state = match ctx.state.lock() {
14871                Ok(state) => state,
14872                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14873            };
14874            let cursor = state.command_cursor;
14875            match state.prepare_scalar_cancellation(
14876                cursor,
14877                CancellationCallKind::Condition,
14878                &self.parallel_group_path,
14879            ) {
14880                Ok(true) => {
14881                    self.opened_wait = true;
14882                    return Poll::Pending;
14883                }
14884                Ok(false) => {}
14885                Err(error) => return Poll::Ready(Err(error)),
14886            }
14887        }
14888        let selection_member = self
14889            .parallel_group_path
14890            .first()
14891            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14892        match (self.predicate)() {
14893            Ok(true) if !selection_member || recorded_wait => {
14894                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14895            }
14896            Ok(_) => {}
14897            Err(error) => return Poll::Ready(Err(error)),
14898        }
14899        if options.timeout_seconds == Some(0) && !selection_member {
14900            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14901        }
14902
14903        let ctx = self.ctx.clone();
14904        let mut state = match ctx.state.lock() {
14905            Ok(state) => state,
14906            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14907        };
14908        let mut command = serde_json::Map::from_iter([
14909            ("type".to_string(), json!("open_condition_wait")),
14910            (
14911                "condition_wait_occurrence_id".to_string(),
14912                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14913            ),
14914            ("condition_key".to_string(), json!(options.condition_key)),
14915            (
14916                "condition_definition_fingerprint".to_string(),
14917                json!(options.predicate_identity),
14918            ),
14919        ]);
14920        if let Some(timeout_seconds) = options.timeout_seconds {
14921            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14922        }
14923        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14924        ctx.apply_scope_membership(&mut command);
14925        state.commands.push(Value::Object(command));
14926        drop(state);
14927        self.opened_wait = true;
14928        Poll::Pending
14929    }
14930}
14931
14932fn validate_recorded_condition_wait(
14933    sequence: u64,
14934    recorded_occurrence_id: &str,
14935    recorded_key: Option<&str>,
14936    recorded_predicate_identity: &str,
14937    recorded_timeout_seconds: Option<u64>,
14938    current_occurrence_id: &str,
14939    current: &ValidatedConditionWaitOptions,
14940) -> Result<()> {
14941    if recorded_occurrence_id != current_occurrence_id {
14942        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14943            "condition_wait_occurrence_mismatch",
14944            Some(sequence),
14945            Some(recorded_occurrence_id.to_string()),
14946            Some(current_occurrence_id.to_string()),
14947            "recorded condition occurrence differs from the current authored wait position",
14948        )));
14949    }
14950    if recorded_key != Some(current.condition_key.as_str()) {
14951        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14952            "condition_wait_key_mismatch",
14953            Some(sequence),
14954            recorded_key.map(str::to_string),
14955            Some(current.condition_key.clone()),
14956            "recorded condition identity differs from the current workflow wait",
14957        )));
14958    }
14959    if recorded_predicate_identity != current.predicate_identity {
14960        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14961            "condition_wait_predicate_mismatch",
14962            Some(sequence),
14963            Some(recorded_predicate_identity.to_string()),
14964            Some(current.predicate_identity.clone()),
14965            "recorded condition predicate behavior differs from current workflow code",
14966        )));
14967    }
14968    if recorded_timeout_seconds != current.timeout_seconds {
14969        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14970            "condition_wait_timeout_mismatch",
14971            Some(sequence),
14972            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14973            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14974            "recorded condition timeout differs from the current workflow wait",
14975        )));
14976    }
14977    Ok(())
14978}
14979
14980/// Future returned by [`WorkflowContext::start_child_workflow`].
14981pub struct ChildWorkflowCall {
14982    ctx: WorkflowContext,
14983    workflow_type: String,
14984    options: ChildWorkflowOptions,
14985    args: Option<Result<AvroValue>>,
14986    scheduled: bool,
14987    matched_pending: bool,
14988    parallel_group_path: Vec<ParallelGroupMetadata>,
14989}
14990
14991impl ChildWorkflowCall {
14992    fn poll_avro_value(
14993        mut self: Pin<&mut Self>,
14994        _cx: &mut TaskContext<'_>,
14995    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14996        if self.matched_pending {
14997            return Poll::Pending;
14998        }
14999
15000        let ctx = self.ctx.clone();
15001        let mut state = match ctx.state.lock() {
15002            Ok(state) => state,
15003            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15004        };
15005
15006        let cursor = state.command_cursor;
15007        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15008            return Poll::Ready(Err(error));
15009        }
15010        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
15011        {
15012            Ok(recorded) => recorded,
15013            Err(error) => return Poll::Ready(Err(error)),
15014        };
15015        if let Some(recorded) = recorded {
15016            let sequence = recorded.sequence();
15017            match recorded {
15018                RecordedCommand::ChildWorkflow {
15019                    workflow_type,
15020                    policies,
15021                    outcome,
15022                    parallel_group_path,
15023                    ..
15024                } => {
15025                    if let Err(error) = ensure_parallel_path_matches(
15026                        sequence,
15027                        parallel_group_path.as_deref(),
15028                        &self.parallel_group_path,
15029                    ) {
15030                        return Poll::Ready(Err(error));
15031                    }
15032                    if let Some(recorded_type) = workflow_type {
15033                        if recorded_type != self.workflow_type {
15034                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15035                                ReplayFailure::new(
15036                                    "recorded_command_detail_mismatch",
15037                                    Some(sequence),
15038                                    Some(format!("child workflow:{recorded_type}")),
15039                                    Some(format!("child workflow:{}", self.workflow_type)),
15040                                    "recorded child workflow type differs from the current workflow command",
15041                                ),
15042                            )));
15043                        }
15044                    }
15045                    if let Err(error) =
15046                        ensure_child_policies_match(sequence, &policies, &self.options)
15047                    {
15048                        return Poll::Ready(Err(error));
15049                    }
15050                    if let Err(error) =
15051                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
15052                    {
15053                        return Poll::Ready(Err(error));
15054                    }
15055                    match state.prepare_scalar_cancellation(
15056                        cursor,
15057                        CancellationCallKind::Child,
15058                        &self.parallel_group_path,
15059                    ) {
15060                        Ok(true) => {
15061                            self.scheduled = true;
15062                            self.matched_pending = true;
15063                            return Poll::Pending;
15064                        }
15065                        Ok(false) => {}
15066                        Err(error) => return Poll::Ready(Err(error)),
15067                    }
15068                    state.command_cursor += 1;
15069                    if let Some(outcome) = outcome {
15070                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15071                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
15072                    }
15073                    state.matched_recorded_pending = true;
15074                    self.scheduled = true;
15075                    self.matched_pending = true;
15076                    return Poll::Pending;
15077                }
15078                other => {
15079                    return Poll::Ready(Err(command_mismatch(
15080                        &other,
15081                        format!("child workflow:{}", self.workflow_type),
15082                    )));
15083                }
15084            }
15085        }
15086
15087        if !self.scheduled {
15088            if self.options.task_queue.trim().is_empty() {
15089                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15090                    "task_queue must not be empty".to_string(),
15091                )));
15092            }
15093            for (name, value) in [
15094                (
15095                    "execution_timeout_seconds",
15096                    self.options.execution_timeout_seconds,
15097                ),
15098                ("run_timeout_seconds", self.options.run_timeout_seconds),
15099            ] {
15100                if value == Some(0) {
15101                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
15102                        "{name} must be at least 1"
15103                    ))));
15104                }
15105            }
15106
15107            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15108                Ok(args) => args,
15109                Err(error) => return Poll::Ready(Err(error)),
15110            };
15111            let arguments = match encode_typed_envelope(
15112                &normalize_avro_arguments(args),
15113                &state.payload_codec,
15114            ) {
15115                Ok(arguments) => arguments,
15116                Err(error) => return Poll::Ready(Err(error)),
15117            };
15118            let mut command = json!({
15119                "type": "start_child_workflow",
15120                "workflow_type": self.workflow_type,
15121                "queue": self.options.task_queue,
15122                "parent_close_policy": self.options.parent_close_policy.as_str(),
15123                "arguments": arguments,
15124            });
15125            let object = command
15126                .as_object_mut()
15127                .expect("child workflow command is always an object");
15128            if self.options.cancellation_policy != CancellationPolicy::Abandon {
15129                object.insert(
15130                    "cancellation_policy".to_string(),
15131                    json!(self.options.cancellation_policy.as_str()),
15132                );
15133            }
15134            if let Some(policy) = &self.options.retry_policy {
15135                let mut retry_policy = serde_json::Map::new();
15136                if let Some(max_attempts) = policy.max_attempts {
15137                    if max_attempts == 0 {
15138                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15139                            "retry_policy.max_attempts must be at least 1".to_string(),
15140                        )));
15141                    }
15142                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
15143                }
15144                if !policy.backoff_seconds.is_empty() {
15145                    retry_policy
15146                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
15147                }
15148                if !policy.non_retryable_error_types.is_empty() {
15149                    retry_policy.insert(
15150                        "non_retryable_error_types".to_string(),
15151                        json!(policy.non_retryable_error_types),
15152                    );
15153                }
15154                if retry_policy.is_empty() {
15155                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15156                        "retry_policy must configure at least one field".to_string(),
15157                    )));
15158                }
15159                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
15160            }
15161            if let Some(seconds) = self.options.execution_timeout_seconds {
15162                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
15163            }
15164            if let Some(seconds) = self.options.run_timeout_seconds {
15165                object.insert("run_timeout_seconds".to_string(), json!(seconds));
15166            }
15167            apply_parallel_group_path(object, &self.parallel_group_path);
15168            ctx.apply_scope_membership(object);
15169            match state.prepare_scalar_cancellation(
15170                cursor,
15171                CancellationCallKind::Child,
15172                &self.parallel_group_path,
15173            ) {
15174                Ok(true) => {
15175                    self.scheduled = true;
15176                    self.matched_pending = true;
15177                    return Poll::Pending;
15178                }
15179                Ok(false) => {}
15180                Err(error) => return Poll::Ready(Err(error)),
15181            }
15182            state.commands.push(command);
15183            self.scheduled = true;
15184        }
15185
15186        Poll::Pending
15187    }
15188}
15189
15190impl Future for ChildWorkflowCall {
15191    type Output = Result<ChildWorkflowResult>;
15192
15193    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15194        match self.poll_avro_value(cx) {
15195            Poll::Ready(Ok(result)) => match result.result.into_json() {
15196                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15197                    parent: result.parent,
15198                    child: result.child,
15199                    child_workflow_type: result.child_workflow_type,
15200                    result: projected,
15201                })),
15202                Err(error) => Poll::Ready(Err(error)),
15203            },
15204            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15205            Poll::Pending => Poll::Pending,
15206        }
15207    }
15208}
15209
15210fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15211    Error::NonDeterministicReplay(ReplayFailure::new(
15212        "recorded_command_mismatch",
15213        Some(recorded.sequence()),
15214        Some(recorded.shape().to_string()),
15215        Some(actual.into()),
15216        "current workflow command does not match the recorded durable command sequence",
15217    ))
15218}
15219
15220pub struct SignalCall {
15221    ctx: WorkflowContext,
15222    signal_name: String,
15223    runtime_reserved_allowed: bool,
15224    opened_wait: bool,
15225    matched_pending: bool,
15226    parallel_group_path: Vec<ParallelGroupMetadata>,
15227}
15228
15229impl SignalCall {
15230    fn poll_avro_value(
15231        mut self: Pin<&mut Self>,
15232        _cx: &mut TaskContext<'_>,
15233    ) -> Poll<Result<Vec<AvroValue>>> {
15234        if self.matched_pending {
15235            return Poll::Pending;
15236        }
15237        if !self.runtime_reserved_allowed {
15238            if let Err(error) = validate_user_signal_name(&self.signal_name) {
15239                return Poll::Ready(Err(error));
15240            }
15241        }
15242
15243        let ctx = self.ctx.clone();
15244        let mut state = match ctx.state.lock() {
15245            Ok(state) => state,
15246            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15247        };
15248
15249        let cursor = state.command_cursor;
15250        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15251            return Poll::Ready(Err(error));
15252        }
15253        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
15254        {
15255            Ok(recorded) => recorded,
15256            Err(error) => return Poll::Ready(Err(error)),
15257        };
15258        if let Some(recorded) = recorded {
15259            match recorded {
15260                RecordedCommand::SignalWait {
15261                    sequence,
15262                    signal_name,
15263                    value,
15264                    parallel_group_path,
15265                } => {
15266                    if let Err(error) = ensure_parallel_path_matches(
15267                        sequence,
15268                        parallel_group_path.as_deref(),
15269                        &self.parallel_group_path,
15270                    ) {
15271                        return Poll::Ready(Err(error));
15272                    }
15273                    if signal_name != self.signal_name {
15274                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15275                            ReplayFailure::new(
15276                                "recorded_command_detail_mismatch",
15277                                Some(sequence),
15278                                Some(format!("signal wait:{signal_name}")),
15279                                Some(format!("signal wait:{}", self.signal_name)),
15280                                "recorded signal name differs from the current workflow command",
15281                            ),
15282                        )));
15283                    }
15284
15285                    if let Err(error) =
15286                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
15287                    {
15288                        return Poll::Ready(Err(error));
15289                    }
15290                    match state.prepare_scalar_cancellation(
15291                        cursor,
15292                        CancellationCallKind::Signal,
15293                        &self.parallel_group_path,
15294                    ) {
15295                        Ok(true) => {
15296                            self.opened_wait = true;
15297                            self.matched_pending = true;
15298                            return Poll::Pending;
15299                        }
15300                        Ok(false) => {}
15301                        Err(error) => return Poll::Ready(Err(error)),
15302                    }
15303                    state.command_cursor += 1;
15304                    if let Some(value) = value {
15305                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15306                        return Poll::Ready(Ok(value));
15307                    }
15308                    if state
15309                        .resume_signal
15310                        .as_ref()
15311                        .is_some_and(|signal| signal.signal_name == self.signal_name)
15312                    {
15313                        let signal = state
15314                            .resume_signal
15315                            .take()
15316                            .expect("matching resume signal is present");
15317                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
15318                        return Poll::Ready(Ok(signal.arguments));
15319                    }
15320
15321                    state.matched_recorded_pending = true;
15322                    self.opened_wait = true;
15323                    self.matched_pending = true;
15324                    return Poll::Pending;
15325                }
15326                other => {
15327                    return Poll::Ready(Err(command_mismatch(
15328                        &other,
15329                        format!("signal wait:{}", self.signal_name),
15330                    )));
15331                }
15332            }
15333        }
15334
15335        match state.prepare_scalar_cancellation(
15336            cursor,
15337            CancellationCallKind::Signal,
15338            &self.parallel_group_path,
15339        ) {
15340            Ok(true) => {
15341                self.opened_wait = true;
15342                self.matched_pending = true;
15343                return Poll::Pending;
15344            }
15345            Ok(false) => {}
15346            Err(error) => return Poll::Ready(Err(error)),
15347        }
15348
15349        if state
15350            .resume_signal
15351            .as_ref()
15352            .is_some_and(|signal| signal.signal_name == self.signal_name)
15353        {
15354            let signal = state
15355                .resume_signal
15356                .take()
15357                .expect("matching resume signal is present");
15358            state.unavailable_cancellation_boundary(&self.parallel_group_path);
15359            return Poll::Ready(Ok(signal.arguments));
15360        }
15361
15362        if !self.opened_wait {
15363            let mut command = serde_json::Map::from_iter([
15364                ("type".to_string(), json!("open_signal_wait")),
15365                ("signal_name".to_string(), json!(self.signal_name)),
15366            ]);
15367            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15368            ctx.apply_scope_membership(&mut command);
15369            state.commands.push(Value::Object(command));
15370            self.opened_wait = true;
15371        }
15372
15373        Poll::Pending
15374    }
15375}
15376
15377impl Future for SignalCall {
15378    type Output = Result<Vec<Value>>;
15379
15380    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15381        match self.poll_avro_value(cx) {
15382            Poll::Ready(Ok(values)) => Poll::Ready(
15383                values
15384                    .into_iter()
15385                    .map(AvroValue::into_json)
15386                    .collect::<Result<Vec<_>>>(),
15387            ),
15388            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15389            Poll::Pending => Poll::Pending,
15390        }
15391    }
15392}
15393
15394#[derive(Clone, Debug)]
15395pub struct ActivityContext {
15396    client: Client,
15397    pub task_id: String,
15398    pub activity_attempt_id: String,
15399    pub lease_owner: String,
15400    pub activity_type: String,
15401    pub attempt_number: u64,
15402    pub task_queue: String,
15403    pub worker_id: String,
15404    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
15405    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
15406    worker_session: Option<WorkerSession>,
15407}
15408
15409impl ActivityContext {
15410    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
15411        if let Some(heartbeats) = &self.local_heartbeats {
15412            return heartbeats
15413                .lock()
15414                .map_err(|_| Error::WorkflowStatePoisoned)?
15415                .record(details);
15416        }
15417        if let Some(guard) = &self.claim_guard {
15418            return guard.heartbeat(self, details).await;
15419        }
15420        if let Some(session) = &self.worker_session {
15421            if !session.active() {
15422                return Err(Error::ActivityExecutionAbandoned(
15423                    "worker-session lease or TTL is no longer active".into(),
15424                ));
15425            }
15426            let result = self
15427                .client
15428                .heartbeat_activity_task_value(
15429                    &self.task_id,
15430                    &self.activity_attempt_id,
15431                    &self.lease_owner,
15432                    details,
15433                )
15434                .await;
15435            return worker_session::settle_activity_heartbeat(
15436                session,
15437                result,
15438                &self.task_id,
15439                &self.activity_attempt_id,
15440                &self.lease_owner,
15441            );
15442        }
15443        self.client
15444            .heartbeat_activity_task(
15445                &self.task_id,
15446                &self.activity_attempt_id,
15447                &self.lease_owner,
15448                details,
15449            )
15450            .await
15451    }
15452}
15453
15454fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
15455    validate_payload_codec(codec)?;
15456    match value {
15457        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
15458            value, codec,
15459        )?)),
15460        None => Ok(AvroValue::Array(Vec::new())),
15461    }
15462}
15463
15464fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
15465    let Some(signal_name) = task
15466        .signal_name
15467        .as_deref()
15468        .filter(|value| !value.is_empty())
15469    else {
15470        return Ok(None);
15471    };
15472    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
15473    let AvroValue::Array(arguments) = decoded else {
15474        unreachable!("normalize_avro_arguments always returns an array");
15475    };
15476
15477    Ok(Some(ResumeSignal {
15478        signal_name: signal_name.to_string(),
15479        arguments,
15480    }))
15481}
15482
15483fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
15484    validate_payload_codec(&task.payload_codec)?;
15485    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
15486    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
15487    for event in &task.history_events {
15488        validate_history_event_payloads(event, &task.payload_codec)?;
15489    }
15490    Ok(())
15491}
15492
15493fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
15494    validate_payload_codec(&task.payload_codec)?;
15495    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
15496}
15497
15498fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
15499    validate_payload_codec(&task.payload_codec)?;
15500    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
15501    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
15502    for event in &task.history_events {
15503        validate_history_event_payloads(event, &task.payload_codec)?;
15504    }
15505
15506    let Some(export) = task.history_export.as_ref() else {
15507        return Ok(());
15508    };
15509    let export_codec = match export.get("payloads") {
15510        Some(payloads) => declared_payload_codec(payloads, "codec")?,
15511        None => None,
15512    }
15513    .unwrap_or(&task.payload_codec);
15514    validate_payload_codec(export_codec)?;
15515
15516    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
15517        for event in events {
15518            let event_type = event
15519                .get("event_type")
15520                .or_else(|| event.get("type"))
15521                .and_then(Value::as_str)
15522                .unwrap_or_default();
15523            if let Some(payload) = event.get("payload") {
15524                validate_history_payloads(event_type, payload, export_codec)?;
15525            }
15526        }
15527    }
15528    for signal in export
15529        .get("signals")
15530        .and_then(Value::as_array)
15531        .into_iter()
15532        .flatten()
15533    {
15534        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
15535        validate_payload_codec(codec)?;
15536        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
15537    }
15538    for activity in export
15539        .get("activities")
15540        .and_then(Value::as_array)
15541        .into_iter()
15542        .flatten()
15543    {
15544        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
15545        validate_payload_codec(codec)?;
15546        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
15547        validate_optional_inbound_payload(activity.get("result"), codec)?;
15548    }
15549    Ok(())
15550}
15551
15552fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
15553    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
15554}
15555
15556fn validate_history_payloads(
15557    event_type: &str,
15558    payload: &Value,
15559    fallback_codec: &str,
15560) -> Result<()> {
15561    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
15562    validate_payload_codec(codec)?;
15563    for field in history_payload_fields(event_type) {
15564        validate_optional_inbound_payload(payload.get(*field), codec)?;
15565    }
15566    Ok(())
15567}
15568
15569const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
15570
15571fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
15572    match event_type {
15573        "ActivityCompleted" => &["result"],
15574        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
15575        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
15576        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
15577        "ChildRunCompleted" => &["result", "output"],
15578        "WorkflowCompleted" => &["output"],
15579        "ServiceCallStarted"
15580        | "ServiceCallCompleted"
15581        | "ServiceCallFailed"
15582        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
15583        _ => &[],
15584    }
15585}
15586
15587fn signal_history_payload(payload: &Value) -> Option<&Value> {
15588    SIGNAL_HISTORY_PAYLOAD_FIELDS
15589        .iter()
15590        .find_map(|field| payload.get(*field))
15591}
15592
15593fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
15594    match value.get(field) {
15595        None => Ok(None),
15596        Some(Value::String(codec)) => Ok(Some(codec)),
15597        Some(_) => Err(invalid_payload_envelope()),
15598    }
15599}
15600
15601fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
15602    validate_payload_codec(codec)?;
15603    if let Some(value) = value.filter(|value| !value.is_null()) {
15604        decode_wire_avro_value(value, codec)?;
15605    }
15606    Ok(())
15607}
15608
15609fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
15610    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
15611        invalid_recorded_history(
15612            "parallel_group_metadata_invalid",
15613            sequence,
15614            "non-empty parallel_group_id",
15615            &payload.to_string(),
15616            "parallel-group history is missing its stable identity",
15617        )
15618    })?;
15619    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
15620        invalid_recorded_history(
15621            "parallel_group_metadata_invalid",
15622            sequence,
15623            "activity, child, timer, signal, condition, or mixed group kind",
15624            &payload.to_string(),
15625            "parallel-group history is missing its group kind",
15626        )
15627    })?;
15628    if !matches!(
15629        kind.as_str(),
15630        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
15631    ) {
15632        return Err(invalid_recorded_history(
15633            "parallel_group_metadata_invalid",
15634            sequence,
15635            "activity, child, timer, signal, condition, or mixed group kind",
15636            &kind,
15637            "parallel-group history contains an unsupported group kind",
15638        ));
15639    }
15640    let base_sequence = payload
15641        .get("parallel_group_base_sequence")
15642        .and_then(value_as_u64)
15643        .filter(|value| *value > 0)
15644        .ok_or_else(|| {
15645            invalid_recorded_history(
15646                "parallel_group_metadata_invalid",
15647                sequence,
15648                "positive parallel_group_base_sequence",
15649                &payload.to_string(),
15650                "parallel-group history contains an invalid base sequence",
15651            )
15652        })?;
15653    let size = payload
15654        .get("parallel_group_size")
15655        .and_then(value_as_u64)
15656        .and_then(|value| usize::try_from(value).ok())
15657        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
15658        .ok_or_else(|| {
15659            invalid_recorded_history(
15660                "parallel_group_metadata_invalid",
15661                sequence,
15662                "bounded positive parallel_group_size",
15663                &payload.to_string(),
15664                "parallel-group history contains an invalid group size",
15665            )
15666        })?;
15667    let index = payload
15668        .get("parallel_group_index")
15669        .and_then(value_as_u64)
15670        .and_then(|value| usize::try_from(value).ok())
15671        .filter(|value| *value < size)
15672        .ok_or_else(|| {
15673            invalid_recorded_history(
15674                "parallel_group_metadata_invalid",
15675                sequence,
15676                "parallel_group_index within group bounds",
15677                &payload.to_string(),
15678                "parallel-group history contains an invalid member index",
15679            )
15680        })?;
15681    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
15682        return Err(invalid_recorded_history(
15683            "parallel_group_metadata_invalid",
15684            sequence,
15685            "base sequence plus member index equals workflow sequence",
15686            &payload.to_string(),
15687            "parallel-group path does not preserve durable workflow position",
15688        ));
15689    }
15690    let mode = payload
15691        .get("parallel_group_mode")
15692        .and_then(Value::as_str)
15693        .unwrap_or("all");
15694    if !matches!(mode, "all" | "select") {
15695        return Err(invalid_recorded_history(
15696            "parallel_group_metadata_invalid",
15697            sequence,
15698            "parallel group mode all or select",
15699            mode,
15700            "parallel-group history contains an unsupported group mode",
15701        ));
15702    }
15703    let expected_id = if mode == "select" {
15704        format!("select-calls:{base_sequence}:{size}")
15705    } else {
15706        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
15707    };
15708    if group_id != expected_id {
15709        return Err(invalid_recorded_history(
15710            "parallel_group_metadata_invalid",
15711            sequence,
15712            &expected_id,
15713            &group_id,
15714            "parallel-group history contains an incompatible stable group ID",
15715        ));
15716    }
15717    let selection_member_key = if mode == "select" {
15718        Some(selection_key_from_value(
15719            payload.get("selection_member_key"),
15720            sequence,
15721        )?)
15722    } else {
15723        None
15724    };
15725    let selection_member_index = if mode == "select" {
15726        Some(required_parallel_usize(
15727            payload,
15728            "selection_member_index",
15729            sequence,
15730        )?)
15731    } else {
15732        None
15733    };
15734    let selection_member_base_sequence = if mode == "select" {
15735        Some(
15736            payload
15737                .get("selection_member_base_sequence")
15738                .and_then(value_as_u64)
15739                .filter(|value| *value >= base_sequence)
15740                .ok_or_else(|| {
15741                    invalid_recorded_history(
15742                        "parallel_group_metadata_invalid",
15743                        sequence,
15744                        "selection member base within its group",
15745                        &payload.to_string(),
15746                        "selection history contains an invalid member base sequence",
15747                    )
15748                })?,
15749        )
15750    } else {
15751        None
15752    };
15753    let selection_member_size = if mode == "select" {
15754        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
15755        if member_size == 0 {
15756            return Err(invalid_recorded_history(
15757                "parallel_group_metadata_invalid",
15758                sequence,
15759                "positive selection member size",
15760                &payload.to_string(),
15761                "selection history contains an invalid member size",
15762            ));
15763        }
15764        Some(member_size)
15765    } else {
15766        None
15767    };
15768    let selection_member_kind = if mode == "select" {
15769        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
15770            invalid_recorded_history(
15771                "parallel_group_metadata_invalid",
15772                sequence,
15773                "selection member operation kind",
15774                &payload.to_string(),
15775                "selection history is missing its authored member kind",
15776            )
15777        })?;
15778        if !matches!(
15779            kind.as_str(),
15780            "activity" | "child" | "timer" | "signal" | "condition" | "group"
15781        ) {
15782            return Err(invalid_recorded_history(
15783                "parallel_group_metadata_invalid",
15784                sequence,
15785                "activity, child, timer, signal, condition, or group selection member kind",
15786                &kind,
15787                "selection history contains an unsupported member kind",
15788            ));
15789        }
15790        Some(kind)
15791    } else {
15792        None
15793    };
15794    if let (Some(member_base), Some(member_size)) =
15795        (selection_member_base_sequence, selection_member_size)
15796    {
15797        let member_end = member_base
15798            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
15799            .ok_or_else(|| {
15800                invalid_recorded_history(
15801                    "parallel_group_metadata_invalid",
15802                    sequence,
15803                    "bounded selection member range",
15804                    &payload.to_string(),
15805                    "selection member range overflowed",
15806                )
15807            })?;
15808        let group_end = base_sequence
15809            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
15810            .unwrap_or(u64::MAX);
15811        if sequence < member_base || sequence >= member_end || member_end > group_end {
15812            return Err(invalid_recorded_history(
15813                "parallel_group_metadata_invalid",
15814                sequence,
15815                "workflow sequence within one bounded selection member",
15816                &payload.to_string(),
15817                "selection member range does not contain its durable leaf",
15818            ));
15819        }
15820    }
15821    Ok(ParallelGroupMetadata {
15822        parallel_group_id: group_id,
15823        parallel_group_kind: kind,
15824        parallel_group_base_sequence: base_sequence,
15825        parallel_group_size: size,
15826        parallel_group_index: index,
15827        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
15828        selection_member_key,
15829        selection_member_index,
15830        selection_member_base_sequence,
15831        selection_member_size,
15832        selection_member_kind,
15833    })
15834}
15835
15836fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
15837    payload
15838        .get(field)
15839        .and_then(value_as_u64)
15840        .and_then(|value| usize::try_from(value).ok())
15841        .ok_or_else(|| {
15842            invalid_recorded_history(
15843                "parallel_group_metadata_invalid",
15844                sequence,
15845                &format!("non-negative integer {field}"),
15846                &payload.to_string(),
15847                "selection history contains invalid member metadata",
15848            )
15849        })
15850}
15851
15852fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15853    match value {
15854        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15855        Some(value) => value_as_u64(value)
15856            .and_then(|value| usize::try_from(value).ok())
15857            .map(SelectionKey::Index)
15858            .ok_or_else(|| {
15859                invalid_recorded_history(
15860                    "selection_member_key_invalid",
15861                    sequence,
15862                    "non-empty string or non-negative integer member key",
15863                    &value.to_string(),
15864                    "selection history contains an invalid member key",
15865                )
15866            }),
15867        None => Err(invalid_recorded_history(
15868            "selection_member_key_missing",
15869            sequence,
15870            "selection_member_key",
15871            "<missing>",
15872            "selection history is missing its stable member key",
15873        )),
15874    }
15875}
15876
15877fn recorded_parallel_group_path(
15878    events: &[&HistoryEvent],
15879    sequence: u64,
15880) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15881    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15882    for event in events {
15883        let payload = &event.payload;
15884        let has_metadata = payload.get("parallel_group_path").is_some()
15885            || payload.get("parallel_group_id").is_some()
15886            || payload.get("parallel_group_kind").is_some()
15887            || payload.get("parallel_group_base_sequence").is_some()
15888            || payload.get("parallel_group_size").is_some()
15889            || payload.get("parallel_group_index").is_some()
15890            || payload.get("parallel_group_mode").is_some()
15891            || payload.get("selection_member_key").is_some();
15892        if !has_metadata {
15893            continue;
15894        }
15895
15896        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15897        let path = match payload.get("parallel_group_path") {
15898            None => vec![top_level.clone()],
15899            Some(Value::Array(entries)) if !entries.is_empty() => entries
15900                .iter()
15901                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15902                .collect::<Result<Vec<_>>>()?,
15903            Some(value) => {
15904                return Err(invalid_recorded_history(
15905                    "parallel_group_metadata_invalid",
15906                    sequence,
15907                    "non-empty parallel_group_path list",
15908                    &value.to_string(),
15909                    "parallel-group history contains an invalid group path",
15910                ));
15911            }
15912        };
15913        if path.last() != Some(&top_level) {
15914            return Err(invalid_recorded_history(
15915                "parallel_group_metadata_invalid",
15916                sequence,
15917                &serde_json::to_string(&path.last()).unwrap_or_default(),
15918                &serde_json::to_string(&top_level).unwrap_or_default(),
15919                "parallel-group top-level fields do not match the innermost path entry",
15920            ));
15921        }
15922        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15923            return Err(invalid_recorded_history(
15924                "parallel_group_history_conflict",
15925                sequence,
15926                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15927                &serde_json::to_string(&path).unwrap_or_default(),
15928                "parallel-group metadata changed between scheduling and resolution history",
15929            ));
15930        }
15931        recorded = Some(path);
15932    }
15933    Ok(recorded)
15934}
15935
15936fn recorded_commands(
15937    events: &[HistoryEvent],
15938    fallback_codec: &str,
15939    parent: WorkflowIdentity,
15940) -> Result<Vec<RecordedCommand>> {
15941    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15942    let mut last_new_sequence = None;
15943
15944    for event in events {
15945        let is_activity = matches!(
15946            event.event_type.as_str(),
15947            "ActivityScheduled"
15948                | "ActivityStarted"
15949                | "ActivityHeartbeatRecorded"
15950                | "ActivityRetryScheduled"
15951                | "ActivityCompleted"
15952                | "ActivityFailed"
15953                | "ActivityCancelled"
15954                | "ActivityTimedOut"
15955        );
15956        let is_workflow_timer = matches!(
15957            event.event_type.as_str(),
15958            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15959        ) && !is_internal_timer_event(event);
15960        let is_child_workflow = matches!(
15961            event.event_type.as_str(),
15962            "ChildWorkflowScheduled"
15963                | "ChildRunStarted"
15964                | "ChildRunCompleted"
15965                | "ChildRunFailed"
15966                | "ChildRunCancelled"
15967                | "ChildRunTerminated"
15968        );
15969        let is_signal_wait = is_recorded_signal_wait_event(event);
15970        let is_condition_wait = is_recorded_condition_wait_event(event);
15971        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15972        let is_side_effect = event.event_type == "SideEffectRecorded";
15973        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15974        let is_memo = event.event_type == "MemoUpserted";
15975        if !is_activity
15976            && !is_workflow_timer
15977            && !is_child_workflow
15978            && !is_signal_wait
15979            && !is_condition_wait
15980            && !is_search_attributes
15981            && !is_side_effect
15982            && !is_version_marker
15983            && !is_memo
15984        {
15985            continue;
15986        }
15987
15988        let sequence = durable_event_sequence(event).ok_or_else(|| {
15989            Error::NonDeterministicReplay(ReplayFailure::new(
15990                "durable_command_sequence_missing",
15991                None,
15992                Some("positive workflow sequence".to_string()),
15993                Some(event.event_type.clone()),
15994                "durable command history event has no workflow sequence",
15995            ))
15996        })?;
15997        if sequence == 0 {
15998            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15999                "durable_command_sequence_invalid",
16000                Some(sequence),
16001                Some("positive workflow sequence".to_string()),
16002                Some(sequence.to_string()),
16003                "durable command history uses an invalid workflow sequence",
16004            )));
16005        }
16006        if !events_by_sequence.contains_key(&sequence) {
16007            if let Some(previous) = last_new_sequence {
16008                if sequence < previous {
16009                    return Err(invalid_recorded_history(
16010                        "durable_command_sequence_mismatch",
16011                        sequence,
16012                        &format!("workflow sequence greater than {previous}"),
16013                        &sequence.to_string(),
16014                        "durable commands are not strictly ordered by their recorded workflow sequence",
16015                    ));
16016                }
16017            }
16018            last_new_sequence = Some(sequence);
16019        }
16020        events_by_sequence.entry(sequence).or_default().push(event);
16021    }
16022
16023    let commands: Vec<RecordedCommand> = events_by_sequence
16024        .into_iter()
16025        .map(|(sequence, sequence_events)| {
16026            let activity_events: Vec<_> = sequence_events
16027                .iter()
16028                .copied()
16029                .filter(|event| event.event_type.starts_with("Activity"))
16030                .collect();
16031            let timer_events: Vec<_> = sequence_events
16032                .iter()
16033                .copied()
16034                .filter(|event| event.event_type.starts_with("Timer"))
16035                .collect();
16036            let child_events: Vec<_> = sequence_events
16037                .iter()
16038                .copied()
16039                .filter(|event| {
16040                    event.event_type == "ChildWorkflowScheduled"
16041                        || event.event_type.starts_with("ChildRun")
16042                })
16043                .collect();
16044            let signal_wait_events: Vec<_> = sequence_events
16045                .iter()
16046                .copied()
16047                .filter(|event| is_recorded_signal_wait_event(event))
16048                .collect();
16049            let condition_wait_events: Vec<_> = sequence_events
16050                .iter()
16051                .copied()
16052                .filter(|event| is_recorded_condition_wait_event(event))
16053                .collect();
16054            let search_attribute_events: Vec<_> = sequence_events
16055                .iter()
16056                .copied()
16057                .filter(|event| event.event_type == "SearchAttributesUpserted")
16058                .collect();
16059            let side_effect_events: Vec<_> = sequence_events
16060                .iter()
16061                .copied()
16062                .filter(|event| event.event_type == "SideEffectRecorded")
16063                .collect();
16064            let version_marker_events: Vec<_> = sequence_events
16065                .iter()
16066                .copied()
16067                .filter(|event| event.event_type == "VersionMarkerRecorded")
16068                .collect();
16069            let memo_events: Vec<_> = sequence_events
16070                .iter()
16071                .copied()
16072                .filter(|event| event.event_type == "MemoUpserted")
16073                .collect();
16074
16075            let command_kind_count = usize::from(!activity_events.is_empty())
16076                + usize::from(!timer_events.is_empty())
16077                + usize::from(!child_events.is_empty())
16078                + usize::from(!signal_wait_events.is_empty())
16079                + usize::from(!condition_wait_events.is_empty())
16080                + usize::from(!search_attribute_events.is_empty())
16081                + usize::from(!side_effect_events.is_empty())
16082                + usize::from(!version_marker_events.is_empty())
16083                + usize::from(!memo_events.is_empty());
16084            if command_kind_count > 1 {
16085                let actual = [
16086                    (!activity_events.is_empty()).then_some("activity"),
16087                    (!timer_events.is_empty()).then_some("timer"),
16088                    (!child_events.is_empty()).then_some("child workflow"),
16089                    (!signal_wait_events.is_empty()).then_some("signal wait"),
16090                    (!condition_wait_events.is_empty()).then_some("condition wait"),
16091                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
16092                    (!side_effect_events.is_empty()).then_some("side effect"),
16093                    (!version_marker_events.is_empty()).then_some("version marker"),
16094                    (!memo_events.is_empty()).then_some("memo upsert"),
16095                ]
16096                .into_iter()
16097                .flatten()
16098                .collect::<Vec<_>>()
16099                .join(" and ");
16100                return Err(invalid_recorded_history(
16101                    "durable_command_sequence_collision",
16102                    sequence,
16103                    "one durable command kind",
16104                    &actual,
16105                    "one workflow sequence records more than one durable command kind",
16106                ));
16107            }
16108
16109            if !activity_events.is_empty() {
16110                let parallel_group_path =
16111                    recorded_parallel_group_path(&activity_events, sequence)?;
16112                let scheduled_count = activity_events
16113                    .iter()
16114                    .filter(|event| event.event_type == "ActivityScheduled")
16115                    .count();
16116                if scheduled_count > 1 {
16117                    return Err(invalid_recorded_history(
16118                        "duplicate_activity_schedule",
16119                        sequence,
16120                        "at most one ActivityScheduled event",
16121                        "multiple ActivityScheduled events",
16122                        "activity history schedules more than one command at one workflow sequence",
16123                    ));
16124                }
16125                let activity_type = activity_events.iter().find_map(|event| {
16126                    event
16127                        .payload
16128                        .get("activity_type")
16129                        .or_else(|| event.payload.get("activity_name"))
16130                        .and_then(Value::as_str)
16131                        .map(str::to_string)
16132                });
16133                if activity_events.iter().filter_map(|event| {
16134                    event
16135                        .payload
16136                        .get("activity_type")
16137                        .or_else(|| event.payload.get("activity_name"))
16138                        .and_then(Value::as_str)
16139                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
16140                    return Err(invalid_recorded_history(
16141                        "activity_identity_mismatch",
16142                        sequence,
16143                        activity_type.as_deref().unwrap_or("one activity identity"),
16144                        "conflicting activity identities",
16145                        "activity lifecycle events at one workflow sequence disagree on identity",
16146                    ));
16147                }
16148                let terminal: Vec<_> = activity_events
16149                    .iter()
16150                    .copied()
16151                    .filter(|event| {
16152                        matches!(
16153                            event.event_type.as_str(),
16154                            "ActivityCompleted"
16155                                | "ActivityFailed"
16156                                | "ActivityCancelled"
16157                                | "ActivityTimedOut"
16158                        )
16159                    })
16160                    .collect();
16161                let duplicate_delivery = terminal.first().is_some_and(|first| {
16162                    terminal.iter().all(|event| {
16163                        event.event_type == first.event_type && event.payload == first.payload
16164                    })
16165                });
16166                if terminal.len() > 1 && !duplicate_delivery {
16167                    return Err(invalid_recorded_history(
16168                        "duplicate_activity_terminal_event",
16169                        sequence,
16170                        "at most one terminal activity event",
16171                        "multiple terminal activity events",
16172                        "activity history settles one command more than once",
16173                    ));
16174                }
16175                let outcome = terminal
16176                    .first()
16177                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
16178                    .transpose()?;
16179                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
16180                let activity_snapshot = activity_events
16181                    .iter()
16182                    .find(|event| event.event_type == "ActivityScheduled")
16183                    .and_then(|event| event.payload.get("activity"))
16184                    .and_then(Value::as_object);
16185                let options = Some(match activity_snapshot {
16186                    Some(activity) => RecordedActivityOptions {
16187                        task_queue: recorded_optional_string(activity, "queue"),
16188                        execution_mode,
16189                        retry_policy: recorded_activity_retry_snapshot(
16190                            activity.get("retry_policy"),
16191                        ),
16192                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16193                    },
16194                    None => RecordedActivityOptions {
16195                        task_queue: RecordedSnapshotValue::Unknown,
16196                        execution_mode,
16197                        retry_policy: recorded_activity_retry_snapshot(None),
16198                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16199                    },
16200                });
16201                return Ok(RecordedCommand::Activity {
16202                    sequence,
16203                    activity_type,
16204                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
16205                    options,
16206                    outcome,
16207                    parallel_group_path,
16208                });
16209            }
16210
16211            if !child_events.is_empty() {
16212                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
16213                let scheduled: Vec<_> = child_events
16214                    .iter()
16215                    .copied()
16216                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
16217                    .collect();
16218                if scheduled.len() != 1 {
16219                    return Err(invalid_recorded_history(
16220                        "child_workflow_schedule_missing_or_duplicate",
16221                        sequence,
16222                        "one ChildWorkflowScheduled event",
16223                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
16224                        "child workflow replay requires exactly one recorded schedule event",
16225                    ));
16226                }
16227                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
16228                let workflow_type = child_events.iter().find_map(|event| {
16229                    event
16230                        .payload
16231                        .get("child_workflow_type")
16232                        .or_else(|| event.payload.get("workflow_type"))
16233                        .and_then(Value::as_str)
16234                        .filter(|value| !value.is_empty())
16235                        .map(str::to_string)
16236                });
16237                if child_events
16238                    .iter()
16239                    .filter_map(|event| {
16240                        event
16241                            .payload
16242                            .get("child_workflow_type")
16243                            .or_else(|| event.payload.get("workflow_type"))
16244                            .and_then(Value::as_str)
16245                    })
16246                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
16247                {
16248                    return Err(invalid_recorded_history(
16249                        "child_workflow_identity_mismatch",
16250                        sequence,
16251                        workflow_type
16252                            .as_deref()
16253                            .unwrap_or("one child workflow type"),
16254                        "conflicting child workflow types",
16255                        "child workflow lifecycle events at one sequence disagree on type",
16256                    ));
16257                }
16258                let mut outcomes = child_workflow_outcomes(
16259                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
16260                    fallback_codec,
16261                    parent.clone(),
16262                )?;
16263                let terminal_events = child_events
16264                    .iter()
16265                    .copied()
16266                    .filter(|event| event.event_type.starts_with("ChildRun"))
16267                    .collect::<Vec<_>>();
16268                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
16269                    terminal_events.iter().all(|event| {
16270                        event.event_type == first.event_type && event.payload == first.payload
16271                    })
16272                });
16273                if outcomes.len() > 1 && !duplicate_delivery {
16274                    return Err(invalid_recorded_history(
16275                        "duplicate_child_workflow_terminal_event",
16276                        sequence,
16277                        "at most one terminal child event",
16278                        "multiple terminal child events",
16279                        "child workflow history settles one command more than once",
16280                    ));
16281                }
16282                return Ok(RecordedCommand::ChildWorkflow {
16283                    sequence,
16284                    workflow_type,
16285                    policies,
16286                    outcome: outcomes.pop(),
16287                    parallel_group_path,
16288                });
16289            }
16290
16291            if !signal_wait_events.is_empty() {
16292                let opened: Vec<_> = signal_wait_events
16293                    .iter()
16294                    .copied()
16295                    .filter(|event| event.event_type == "SignalWaitOpened")
16296                    .collect();
16297                if opened.len() != 1 {
16298                    return Err(invalid_recorded_history(
16299                        "signal_wait_open_missing_or_duplicate",
16300                        sequence,
16301                        "one SignalWaitOpened event",
16302                        &format!("{} SignalWaitOpened events", opened.len()),
16303                        "signal replay requires exactly one canonical wait-open event",
16304                    ));
16305                }
16306
16307                let applied: Vec<_> = signal_wait_events
16308                    .iter()
16309                    .copied()
16310                    .filter(|event| event.event_type == "SignalApplied")
16311                    .collect();
16312                if applied.len() > 1 {
16313                    return Err(invalid_recorded_history(
16314                        "duplicate_signal_wait_apply",
16315                        sequence,
16316                        "at most one SignalApplied event",
16317                        "multiple SignalApplied events",
16318                        "signal history applies one durable wait more than once",
16319                    ));
16320                }
16321
16322                let signal_names = signal_wait_events
16323                    .iter()
16324                    .map(|event| required_signal_wait_name(event, sequence))
16325                    .collect::<Result<Vec<_>>>()?;
16326                let signal_name = signal_names
16327                    .first()
16328                    .expect("signal wait events are not empty")
16329                    .clone();
16330                if signal_names.iter().any(|candidate| candidate != &signal_name) {
16331                    return Err(invalid_recorded_history(
16332                        "signal_wait_identity_mismatch",
16333                        sequence,
16334                        &signal_name,
16335                        "conflicting signal names",
16336                        "signal wait lifecycle events at one workflow sequence disagree on identity",
16337                    ));
16338                }
16339                let value = applied
16340                    .first()
16341                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
16342                    .transpose()?;
16343                return Ok(RecordedCommand::SignalWait {
16344                    sequence,
16345                    signal_name,
16346                    value,
16347                    parallel_group_path: recorded_parallel_group_path(
16348                        &signal_wait_events,
16349                        sequence,
16350                    )?,
16351                });
16352            }
16353
16354            if !condition_wait_events.is_empty() {
16355                return recorded_condition_wait(
16356                    sequence,
16357                    &condition_wait_events,
16358                    events,
16359                );
16360            }
16361
16362            if !search_attribute_events.is_empty() {
16363                if search_attribute_events.len() != 1 {
16364                    return Err(invalid_recorded_history(
16365                        "duplicate_search_attribute_update",
16366                        sequence,
16367                        "one SearchAttributesUpserted event",
16368                        &format!(
16369                            "{} SearchAttributesUpserted events",
16370                            search_attribute_events.len()
16371                        ),
16372                        "search-attribute history records one workflow command more than once",
16373                    ));
16374                }
16375                let payload = &search_attribute_events[0].payload;
16376                let attributes = payload
16377                    .get("attributes")
16378                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
16379                    .cloned()
16380                    .ok_or_else(|| {
16381                        invalid_recorded_history(
16382                            "search_attribute_update_missing",
16383                            sequence,
16384                            "non-empty attributes object",
16385                            "missing or invalid attributes",
16386                            "search-attribute history is missing its recorded mutation",
16387                        )
16388                    })?;
16389                let attribute_types =
16390                    recorded_search_attribute_types(payload, &attributes, sequence)?;
16391                return Ok(RecordedCommand::SearchAttributes {
16392                    sequence,
16393                    attributes,
16394                    attribute_types,
16395                });
16396            }
16397
16398            if !side_effect_events.is_empty() {
16399                if side_effect_events.len() != 1 {
16400                    return Err(invalid_recorded_history(
16401                        "duplicate_side_effect_record",
16402                        sequence,
16403                        "one SideEffectRecorded event",
16404                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
16405                        "side-effect history records one workflow command more than once",
16406                    ));
16407                }
16408                let event = side_effect_events[0];
16409                let result = event.payload.get("result").ok_or_else(|| {
16410                    invalid_recorded_history(
16411                        "side_effect_result_missing",
16412                        sequence,
16413                        "recorded result payload",
16414                        "missing result",
16415                        "side-effect history is missing its recorded value",
16416                    )
16417                })?;
16418                let has_published_envelope = result.as_str().is_some()
16419                    || result.as_object().is_some_and(|envelope| {
16420                        envelope.get("codec").and_then(Value::as_str).is_some()
16421                            && envelope.get("blob").and_then(Value::as_str).is_some()
16422                    });
16423                if !has_published_envelope {
16424                    return Err(invalid_recorded_history(
16425                        "side_effect_payload_malformed",
16426                        sequence,
16427                        "payload blob or {codec, blob} envelope",
16428                        &result.to_string(),
16429                        "side-effect history result does not use a published payload envelope",
16430                    ));
16431                }
16432                let codec = event
16433                    .payload
16434                    .get("payload_codec")
16435                    .and_then(Value::as_str)
16436                    .unwrap_or(fallback_codec);
16437                let value = decode_wire_avro_value(result, codec).map_err(|error| {
16438                    if error.to_string().contains("unsupported_payload_codec") {
16439                        return error;
16440                    }
16441
16442                    invalid_recorded_history(
16443                        "side_effect_payload_incompatible",
16444                        sequence,
16445                        &format!("valid {codec} payload envelope"),
16446                        &error.to_string(),
16447                        "side-effect history payload cannot be decoded with its recorded codec",
16448                    )
16449                })?;
16450                return Ok(RecordedCommand::SideEffect { sequence, value });
16451            }
16452
16453            if !version_marker_events.is_empty() {
16454                if version_marker_events.len() != 1 {
16455                    return Err(invalid_recorded_history(
16456                        "duplicate_version_marker_record",
16457                        sequence,
16458                        "one VersionMarkerRecorded event",
16459                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
16460                        "version-marker history records one workflow command more than once",
16461                    ));
16462                }
16463                let payload = &version_marker_events[0].payload;
16464                let change_id = payload
16465                    .get("change_id")
16466                    .and_then(Value::as_str)
16467                    .filter(|value| !value.is_empty())
16468                    .map(str::to_string)
16469                    .ok_or_else(|| {
16470                        invalid_recorded_history(
16471                            "version_marker_field_missing",
16472                            sequence,
16473                            "non-empty change_id",
16474                            "missing or invalid change_id",
16475                            "version-marker history is missing its stable change ID",
16476                        )
16477                    })?;
16478                let version = required_version_i32(payload, "version", sequence)?;
16479                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
16480                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
16481                if min_supported > max_supported || version < min_supported || version > max_supported {
16482                    return Err(invalid_recorded_history(
16483                        "version_marker_history_range_invalid",
16484                        sequence,
16485                        "min_supported <= version <= max_supported",
16486                        &format!("{min_supported} <= {version} <= {max_supported}"),
16487                        "recorded version marker contains an internally incompatible range",
16488                    ));
16489                }
16490                return Ok(RecordedCommand::VersionMarker {
16491                    sequence,
16492                    change_id,
16493                    version,
16494                });
16495            }
16496
16497            if !memo_events.is_empty() {
16498                if memo_events.len() != 1 {
16499                    return Err(invalid_recorded_history(
16500                        "duplicate_memo_upsert_record",
16501                        sequence,
16502                        "one MemoUpserted event",
16503                        &format!("{} MemoUpserted events", memo_events.len()),
16504                        "memo history records one workflow update more than once",
16505                    ));
16506                }
16507                let payload = &memo_events[0].payload;
16508                let entries = payload.get("entries").cloned().ok_or_else(|| {
16509                    invalid_recorded_history(
16510                        "memo_entries_missing",
16511                        sequence,
16512                        "memo entries object",
16513                        "missing entries",
16514                        "MemoUpserted history is missing replay identity entries",
16515                    )
16516                })?;
16517                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
16518                    invalid_recorded_history(
16519                        "memo_entries_invalid",
16520                        sequence,
16521                        "valid canonical memo entries",
16522                        &error.to_string(),
16523                        "MemoUpserted history contains invalid replay identity entries",
16524                    )
16525                })?;
16526                let merged = payload.get("merged").cloned().ok_or_else(|| {
16527                    invalid_recorded_history(
16528                        "memo_merged_projection_missing",
16529                        sequence,
16530                        "merged memo projection",
16531                        "missing merged",
16532                        "MemoUpserted history is missing its merged projection",
16533                    )
16534                })?;
16535                decode_memo_history_map(&merged, false).map_err(|error| {
16536                    invalid_recorded_history(
16537                        "memo_merged_projection_invalid",
16538                        sequence,
16539                        "valid merged memo projection",
16540                        &error.to_string(),
16541                        "MemoUpserted history contains an invalid merged projection",
16542                    )
16543                })?;
16544
16545                return Ok(RecordedCommand::Memo { sequence, entries });
16546            }
16547            let scheduled: Vec<_> = timer_events
16548                .iter()
16549                .copied()
16550                .filter(|event| event.event_type == "TimerScheduled")
16551                .collect();
16552            let fired: Vec<_> = timer_events
16553                .iter()
16554                .copied()
16555                .filter(|event| event.event_type == "TimerFired")
16556                .collect();
16557            if scheduled.len() != 1 {
16558                return Err(invalid_recorded_history(
16559                    "timer_schedule_missing_or_duplicate",
16560                    sequence,
16561                    "one TimerScheduled event",
16562                    &format!("{} TimerScheduled events", scheduled.len()),
16563                    "timer replay requires exactly one recorded schedule event",
16564                ));
16565            }
16566            if fired.len() > 1 {
16567                return Err(invalid_recorded_history(
16568                    "duplicate_timer_fire",
16569                    sequence,
16570                    "at most one TimerFired event",
16571                    "multiple TimerFired events",
16572                    "timer history contains more than one fire event for a workflow sequence",
16573                ));
16574            }
16575
16576            let scheduled = scheduled[0];
16577            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16578            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16579            if let Some(fired) = fired.first() {
16580                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16581                if fired_timer_id != timer_id {
16582                    return Err(invalid_recorded_history(
16583                        "timer_identity_mismatch",
16584                        sequence,
16585                        &timer_id,
16586                        &fired_timer_id,
16587                        "TimerFired does not correspond to the recorded TimerScheduled event",
16588                    ));
16589                }
16590                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16591                if fired_delay != delay_seconds {
16592                    return Err(invalid_recorded_history(
16593                        "timer_history_delay_mismatch",
16594                        sequence,
16595                        &delay_seconds.to_string(),
16596                        &fired_delay.to_string(),
16597                        "TimerScheduled and TimerFired record different delays",
16598                    ));
16599                }
16600            }
16601
16602            Ok(RecordedCommand::Timer {
16603                sequence,
16604                delay_seconds,
16605                fired: !fired.is_empty(),
16606                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
16607            })
16608        })
16609        .collect::<Result<_>>()?;
16610
16611    let mut marker_decisions = HashMap::new();
16612    for command in &commands {
16613        if let RecordedCommand::VersionMarker {
16614            sequence,
16615            change_id,
16616            version,
16617        } = command
16618        {
16619            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
16620                if version != first_version {
16621                    return Err(invalid_recorded_history(
16622                        "version_marker_conflict",
16623                        *sequence,
16624                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
16625                        &format!("version {version} at sequence {sequence}"),
16626                        "workflow history contains conflicting decisions for one stable change ID",
16627                    ));
16628                }
16629            } else {
16630                marker_decisions.insert(change_id.clone(), (*version, *sequence));
16631            }
16632        }
16633    }
16634
16635    Ok(commands)
16636}
16637
16638fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
16639    payload
16640        .get(field)
16641        .and_then(Value::as_i64)
16642        .and_then(|value| i32::try_from(value).ok())
16643        .ok_or_else(|| {
16644            invalid_recorded_history(
16645                "version_marker_field_missing",
16646                sequence,
16647                &format!("integer {field}"),
16648                "missing or out-of-range integer",
16649                "version-marker history is missing a required integer field",
16650            )
16651        })
16652}
16653
16654fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
16655    event
16656        .payload
16657        .get("sequence")
16658        .or_else(|| event.payload.get("workflow_sequence"))
16659        .or_else(|| event.raw.get("sequence"))
16660        .or_else(|| event.raw.get("workflow_sequence"))
16661        .and_then(value_as_u64)
16662}
16663
16664fn is_internal_timer_event(event: &HistoryEvent) -> bool {
16665    matches!(
16666        event
16667            .payload
16668            .get("timer_kind")
16669            .or_else(|| event.raw.get("timer_kind"))
16670            .and_then(Value::as_str),
16671        Some("condition_timeout" | "signal_timeout")
16672    )
16673}
16674
16675fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
16676    matches!(
16677        event.event_type.as_str(),
16678        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16679    )
16680}
16681
16682fn recorded_condition_wait(
16683    sequence: u64,
16684    condition_events: &[&HistoryEvent],
16685    all_events: &[HistoryEvent],
16686) -> Result<RecordedCommand> {
16687    let opened = condition_events
16688        .iter()
16689        .copied()
16690        .filter(|event| event.event_type == "ConditionWaitOpened")
16691        .collect::<Vec<_>>();
16692    if opened.len() != 1 {
16693        return Err(invalid_recorded_history(
16694            "condition_wait_open_missing_or_duplicate",
16695            sequence,
16696            "one ConditionWaitOpened event",
16697            &format!("{} ConditionWaitOpened events", opened.len()),
16698            "condition replay requires exactly one canonical wait-open event",
16699        ));
16700    }
16701    let terminal = condition_events
16702        .iter()
16703        .copied()
16704        .filter(|event| {
16705            matches!(
16706                event.event_type.as_str(),
16707                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16708            )
16709        })
16710        .collect::<Vec<_>>();
16711    if terminal.len() > 1 {
16712        return Err(invalid_recorded_history(
16713            "duplicate_condition_wait_terminal_event",
16714            sequence,
16715            "at most one condition terminal event",
16716            "multiple condition terminal events",
16717            "condition history settles one durable wait more than once",
16718        ));
16719    }
16720
16721    let opened = opened[0];
16722    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
16723    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
16724    for event in condition_events
16725        .iter()
16726        .copied()
16727        .filter(|event| !std::ptr::eq(*event, opened))
16728    {
16729        let event_wait_id = required_condition_wait_id(event, sequence)?;
16730        if event_wait_id != condition_wait_id {
16731            return Err(invalid_recorded_history(
16732                "condition_wait_id_mismatch",
16733                sequence,
16734                &condition_wait_id,
16735                &event_wait_id,
16736                "condition lifecycle events at one sequence disagree on wait identity",
16737            ));
16738        }
16739        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
16740        if event_occurrence_id != occurrence_id {
16741            return Err(invalid_recorded_history(
16742                "condition_wait_occurrence_history_mismatch",
16743                sequence,
16744                &occurrence_id,
16745                &event_occurrence_id,
16746                "condition lifecycle events at one sequence disagree on authored occurrence identity",
16747            ));
16748        }
16749    }
16750
16751    let condition_key = optional_non_empty_history_string(opened, "condition_key");
16752    let predicate_identity = opened
16753        .payload
16754        .get("condition_definition_fingerprint")
16755        .and_then(Value::as_str)
16756        .filter(|value| !value.is_empty())
16757        .map(str::to_string)
16758        .ok_or_else(|| {
16759            invalid_recorded_history(
16760                "condition_wait_predicate_fingerprint_missing",
16761                sequence,
16762                "non-empty condition_definition_fingerprint",
16763                &opened.event_type,
16764                "canonical condition history is missing its predicate identity",
16765            )
16766        })?;
16767    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
16768    for event in condition_events
16769        .iter()
16770        .copied()
16771        .filter(|event| !std::ptr::eq(*event, opened))
16772    {
16773        for (field, opened_value) in [
16774            ("condition_key", condition_key.as_deref()),
16775            (
16776                "condition_definition_fingerprint",
16777                Some(predicate_identity.as_str()),
16778            ),
16779        ] {
16780            if let Some(value) = optional_non_empty_history_string(event, field) {
16781                if opened_value.is_some_and(|opened_value| opened_value != value) {
16782                    return Err(invalid_recorded_history(
16783                        "condition_wait_definition_history_mismatch",
16784                        sequence,
16785                        opened_value.unwrap_or_default(),
16786                        &value,
16787                        "condition lifecycle events disagree on the recorded definition",
16788                    ));
16789                }
16790            }
16791        }
16792        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
16793            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
16794                return Err(invalid_recorded_history(
16795                    "condition_wait_definition_history_mismatch",
16796                    sequence,
16797                    &format!("{}s", timeout_seconds.unwrap_or_default()),
16798                    &format!("{event_timeout}s"),
16799                    "condition lifecycle events disagree on the recorded timeout",
16800                ));
16801            }
16802        }
16803    }
16804
16805    let timeout_timer_events = all_events
16806        .iter()
16807        .filter(|event| {
16808            matches!(
16809                event.event_type.as_str(),
16810                "TimerScheduled" | "TimerCancelled" | "TimerFired"
16811            ) && event.payload.get("timer_kind").and_then(Value::as_str)
16812                == Some("condition_timeout")
16813                && event
16814                    .payload
16815                    .get("condition_wait_id")
16816                    .and_then(Value::as_str)
16817                    == Some(condition_wait_id.as_str())
16818        })
16819        .collect::<Vec<_>>();
16820    let scheduled = timeout_timer_events
16821        .iter()
16822        .copied()
16823        .filter(|event| event.event_type == "TimerScheduled")
16824        .collect::<Vec<_>>();
16825    let fired = timeout_timer_events
16826        .iter()
16827        .copied()
16828        .filter(|event| event.event_type == "TimerFired")
16829        .collect::<Vec<_>>();
16830    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
16831        return Err(invalid_recorded_history(
16832            "condition_wait_timeout_history_invalid",
16833            sequence,
16834            "one timeout schedule and at most one fire",
16835            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
16836            "condition timeout history has a missing or duplicate lifecycle event",
16837        ));
16838    }
16839    if let Some(scheduled) = scheduled.first() {
16840        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16841        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16842        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
16843            return Err(invalid_recorded_history(
16844                "condition_wait_timeout_delay_mismatch",
16845                sequence,
16846                &format!("{}s", timeout_seconds.unwrap_or_default()),
16847                &format!("{delay_seconds}s"),
16848                "condition timeout timer differs from the wait definition",
16849            ));
16850        }
16851        if let Some(fired) = fired.first() {
16852            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16853            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16854            if fired_timer_id != timer_id || fired_delay != delay_seconds {
16855                return Err(invalid_recorded_history(
16856                    "condition_wait_timeout_identity_mismatch",
16857                    sequence,
16858                    &format!("{timer_id}:{delay_seconds}s"),
16859                    &format!("{fired_timer_id}:{fired_delay}s"),
16860                    "condition timeout fire does not match its durable schedule",
16861                ));
16862            }
16863        }
16864    }
16865
16866    let result = terminal.first().map(|event| {
16867        if event.event_type == "ConditionWaitTimedOut" {
16868            ConditionWaitResult::TimedOut
16869        } else {
16870            ConditionWaitResult::Satisfied
16871        }
16872    });
16873    let result = if !fired.is_empty() {
16874        if result == Some(ConditionWaitResult::Satisfied) {
16875            return Err(invalid_recorded_history(
16876                "condition_wait_terminal_conflict",
16877                sequence,
16878                "one satisfied or timed-out outcome",
16879                "satisfied event and fired timeout",
16880                "condition history records conflicting terminal outcomes",
16881            ));
16882        }
16883        Some(ConditionWaitResult::TimedOut)
16884    } else {
16885        result
16886    };
16887
16888    Ok(RecordedCommand::ConditionWait {
16889        sequence,
16890        occurrence_id,
16891        condition_key,
16892        predicate_identity,
16893        timeout_seconds,
16894        result,
16895        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16896    })
16897}
16898
16899fn recorded_condition_group_path(
16900    condition_events: &[&HistoryEvent],
16901    all_events: &[HistoryEvent],
16902    sequence: u64,
16903) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16904    let opened = condition_events
16905        .iter()
16906        .copied()
16907        .find(|event| event.event_type == "ConditionWaitOpened")
16908        .expect("canonical condition opener is validated first");
16909    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16910    let previous_events = all_events
16911        .iter()
16912        .take_while(|event| !std::ptr::eq(*event, opened))
16913        .collect::<Vec<_>>();
16914    let originals = previous_events
16915        .iter()
16916        .copied()
16917        .filter(|event| event.event_type == "ConditionWaitOpened")
16918        .filter(|event| {
16919            event
16920                .payload
16921                .get("condition_wait_occurrence_id")
16922                .and_then(Value::as_str)
16923                == Some(occurrence.as_str())
16924        })
16925        .collect::<Vec<_>>();
16926    let Some(original) = originals.first().copied() else {
16927        return recorded_parallel_group_path(condition_events, sequence);
16928    };
16929    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16930    if authored_sequence == sequence {
16931        return recorded_parallel_group_path(condition_events, sequence);
16932    }
16933    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16934    if original_path.is_none() {
16935        return recorded_parallel_group_path(condition_events, sequence);
16936    }
16937    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16938    let identity_matches = [
16939        "condition_key",
16940        "condition_definition_fingerprint",
16941        "timeout_seconds",
16942    ]
16943    .iter()
16944    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16945    let previous = originals
16946        .iter()
16947        .copied()
16948        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16949        .max_by_key(|event| durable_event_sequence(event));
16950    let previously_satisfied = previous.is_some_and(|previous| {
16951        previous_events.iter().any(|event| {
16952            event.event_type == "ConditionWaitSatisfied"
16953                && event.payload.get("condition_wait_id")
16954                    == previous.payload.get("condition_wait_id")
16955                && event.payload.get("condition_wait_occurrence_id")
16956                    == previous.payload.get("condition_wait_occurrence_id")
16957                && durable_event_sequence(event) == durable_event_sequence(previous)
16958        })
16959    });
16960    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16961        return Err(invalid_recorded_history(
16962            "condition_wait_group_reopen_mismatch",
16963            sequence,
16964            "same authored condition and group path after a satisfied physical wait",
16965            &opened.payload.to_string(),
16966            "grouped condition reopen has no matching recorded predecessor",
16967        ));
16968    }
16969    Ok(reopened_path)
16970}
16971
16972fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16973    event
16974        .payload
16975        .get("condition_wait_occurrence_id")
16976        .and_then(Value::as_str)
16977        .filter(|value| !value.is_empty())
16978        .map(str::to_string)
16979        .ok_or_else(|| {
16980            invalid_recorded_history(
16981                "condition_wait_occurrence_id_missing",
16982                sequence,
16983                "non-empty condition_wait_occurrence_id",
16984                &event.event_type,
16985                "condition history is missing authored occurrence identity",
16986            )
16987        })
16988}
16989
16990fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16991    event
16992        .payload
16993        .get("condition_wait_id")
16994        .and_then(Value::as_str)
16995        .filter(|value| !value.is_empty())
16996        .map(str::to_string)
16997        .ok_or_else(|| {
16998            invalid_recorded_history(
16999                "condition_wait_id_missing",
17000                sequence,
17001                "non-empty condition_wait_id",
17002                &event.event_type,
17003                "canonical condition history is missing its durable wait identity",
17004            )
17005        })
17006}
17007
17008fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
17009    event
17010        .payload
17011        .get(field)
17012        .and_then(Value::as_str)
17013        .filter(|value| !value.is_empty())
17014        .map(str::to_string)
17015}
17016
17017fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
17018    match event.payload.get(field) {
17019        None | Some(Value::Null) => Ok(None),
17020        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
17021            invalid_recorded_history(
17022                "condition_wait_definition_invalid",
17023                sequence,
17024                &format!("non-negative integer {field}"),
17025                &value.to_string(),
17026                "condition history contains an invalid numeric definition field",
17027            )
17028        }),
17029    }
17030}
17031
17032fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
17033    event
17034        .payload
17035        .get("signal_name")
17036        .or_else(|| event.raw.get("signal_name"))
17037        .and_then(Value::as_str)
17038        .filter(|value| !value.is_empty())
17039        .map(str::to_string)
17040        .ok_or_else(|| {
17041            invalid_recorded_history(
17042                "signal_wait_name_missing",
17043                sequence,
17044                "non-empty signal_name",
17045                &event.event_type,
17046                "canonical signal-wait history is missing its signal identity",
17047            )
17048        })
17049}
17050
17051fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
17052    // Applying a buffered control-plane signal has no authored call sequence.
17053    // Its outer sequence orders history events and must not become a wait.
17054    if event.event_type == "SignalApplied"
17055        && event
17056            .payload
17057            .get("signal_wait_id")
17058            .and_then(Value::as_str)
17059            .is_some_and(|id| id.starts_with("signal-command:"))
17060        && event.payload.get("sequence").is_none()
17061        && event.payload.get("workflow_sequence").is_none()
17062    {
17063        return false;
17064    }
17065    matches!(
17066        event.event_type.as_str(),
17067        "SignalWaitOpened" | "SignalApplied"
17068    )
17069}
17070
17071fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
17072    event
17073        .payload
17074        .get(field)
17075        .and_then(Value::as_str)
17076        .filter(|value| !value.is_empty())
17077        .map(str::to_string)
17078        .ok_or_else(|| {
17079            invalid_recorded_history(
17080                "timer_history_field_missing",
17081                sequence,
17082                field,
17083                &event.event_type,
17084                "timer history is missing a required identity field",
17085            )
17086        })
17087}
17088
17089fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
17090    event
17091        .payload
17092        .get(field)
17093        .and_then(value_as_u64)
17094        .ok_or_else(|| {
17095            invalid_recorded_history(
17096                "timer_history_field_missing",
17097                sequence,
17098                field,
17099                &event.event_type,
17100                "timer history is missing a required numeric field",
17101            )
17102        })
17103}
17104
17105fn recorded_search_attribute_types(
17106    payload: &Value,
17107    attributes: &Value,
17108    sequence: u64,
17109) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
17110    let Some(raw_types) = payload.get("attribute_types") else {
17111        // This is the explicit compatibility rule for histories recorded
17112        // before typed identity was persisted. Values still constrain replay;
17113        // the unknown type snapshot does not assert a typed match.
17114        return Ok(RecordedSnapshotValue::Unknown);
17115    };
17116    let Some(raw_types) = raw_types.as_object() else {
17117        return Err(invalid_recorded_history(
17118            "search_attribute_types_malformed",
17119            sequence,
17120            "canonical attribute type map",
17121            &raw_types.to_string(),
17122            "search-attribute history contains malformed type identity",
17123        ));
17124    };
17125    let attribute_keys = attributes
17126        .as_object()
17127        .expect("recorded search attributes were validated as an object");
17128    let mut types = BTreeMap::new();
17129    for (key, value) in raw_types {
17130        let Some(attribute_type) = value.as_str() else {
17131            return Err(invalid_recorded_history(
17132                "search_attribute_types_malformed",
17133                sequence,
17134                "canonical string type name",
17135                &value.to_string(),
17136                "search-attribute history contains a non-string type identity",
17137            ));
17138        };
17139        if !attribute_keys.contains_key(key)
17140            || !matches!(
17141                attribute_type,
17142                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
17143            )
17144        {
17145            return Err(invalid_recorded_history(
17146                "search_attribute_types_malformed",
17147                sequence,
17148                "canonical types for keys present in attributes",
17149                &format!("{key}:{attribute_type}"),
17150                "search-attribute history contains unsupported or orphaned type identity",
17151            ));
17152        }
17153        types.insert(key.clone(), attribute_type.to_string());
17154    }
17155    Ok(RecordedSnapshotValue::Known(types))
17156}
17157
17158fn invalid_recorded_history(
17159    reason: &str,
17160    sequence: u64,
17161    expected: &str,
17162    actual: &str,
17163    message: &str,
17164) -> Error {
17165    Error::NonDeterministicReplay(ReplayFailure::new(
17166        reason,
17167        Some(sequence),
17168        Some(expected.to_string()),
17169        Some(actual.to_string()),
17170        message,
17171    ))
17172}
17173
17174type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
17175
17176fn activity_outcome(
17177    event: &HistoryEvent,
17178    fallback_codec: &str,
17179    recorded_activity_type: Option<String>,
17180) -> Result<ActivityOutcome> {
17181    if event.event_type == "ActivityCompleted" {
17182        let codec = event
17183            .payload
17184            .get("payload_codec")
17185            .and_then(Value::as_str)
17186            .unwrap_or(fallback_codec);
17187        return Ok(Ok(decode_wire_avro_value(
17188            event.payload.get("result").unwrap_or(&Value::Null),
17189            codec,
17190        )?));
17191    }
17192
17193    let payload = &event.payload;
17194    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
17195        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
17196        "ActivityCancelled" => (
17197            ActivityFailureKind::Cancelled,
17198            "cancelled",
17199            "activity was cancelled",
17200        ),
17201        "ActivityTimedOut" => (
17202            ActivityFailureKind::TimedOut,
17203            "timeout",
17204            "activity timed out",
17205        ),
17206        _ => unreachable!("activity_outcome is called only for terminal activity events"),
17207    };
17208    let exception = payload
17209        .get("exception")
17210        .filter(|value| !value.is_null())
17211        .cloned();
17212    let failure_category = payload_string(payload, "failure_category");
17213    let timeout_kind = payload_string(payload, "timeout_kind");
17214    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
17215        ActivityFailureKind::Failed => failure_category
17216            .clone()
17217            .unwrap_or_else(|| fallback_reason.to_string()),
17218        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
17219        ActivityFailureKind::TimedOut => timeout_kind
17220            .clone()
17221            .unwrap_or_else(|| fallback_reason.to_string()),
17222    });
17223    let message = payload_string(payload, "message")
17224        .or_else(|| {
17225            exception
17226                .as_ref()
17227                .and_then(|value| payload_string(value, "message"))
17228        })
17229        .unwrap_or_else(|| fallback_message.to_string());
17230
17231    Ok(Err(ActivityFailure {
17232        kind,
17233        reason,
17234        message,
17235        activity_execution_id: payload_string(payload, "activity_execution_id"),
17236        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
17237        activity_type: payload_string(payload, "activity_type")
17238            .or_else(|| payload_string(payload, "activity_name"))
17239            .or(recorded_activity_type),
17240        activity_class: payload_string(payload, "activity_class"),
17241        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
17242        failure_id: payload_string(payload, "failure_id"),
17243        failure_category,
17244        timeout_kind,
17245        non_retryable: payload
17246            .get("non_retryable")
17247            .and_then(Value::as_bool)
17248            .unwrap_or(false),
17249        exception_type: payload_string(payload, "exception_type").or_else(|| {
17250            exception
17251                .as_ref()
17252                .and_then(|value| payload_string(value, "type"))
17253        }),
17254        exception_class: payload_string(payload, "exception_class").or_else(|| {
17255            exception
17256                .as_ref()
17257                .and_then(|value| payload_string(value, "class"))
17258        }),
17259        code: payload
17260            .get("code")
17261            .filter(|value| !value.is_null())
17262            .cloned(),
17263        exception,
17264    }))
17265}
17266
17267type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
17268
17269fn child_workflow_outcomes(
17270    events: &[HistoryEvent],
17271    fallback_codec: &str,
17272    parent: WorkflowIdentity,
17273) -> Result<Vec<ChildWorkflowOutcome>> {
17274    let mut outcomes = Vec::new();
17275
17276    for event in events {
17277        let kind = match event.event_type.as_str() {
17278            "ChildRunCompleted" => None,
17279            "ChildRunFailed" => Some((
17280                ChildWorkflowFailureKind::Failed,
17281                "child_workflow",
17282                "child workflow failed",
17283            )),
17284            "ChildRunCancelled" => Some((
17285                ChildWorkflowFailureKind::Cancelled,
17286                "cancelled",
17287                "child workflow was cancelled",
17288            )),
17289            "ChildRunTerminated" => Some((
17290                ChildWorkflowFailureKind::Terminated,
17291                "terminated",
17292                "child workflow was terminated",
17293            )),
17294            _ => continue,
17295        };
17296        let payload = &event.payload;
17297        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
17298        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
17299        let child_workflow_type = payload_string(payload, "child_workflow_type");
17300
17301        if let Some((kind, reason, fallback_message)) = kind {
17302            let exception = payload
17303                .get("exception")
17304                .filter(|value| !value.is_null())
17305                .cloned();
17306            let message = payload_string(payload, "message")
17307                .or_else(|| {
17308                    exception
17309                        .as_ref()
17310                        .and_then(|value| payload_string(value, "message"))
17311                })
17312                .unwrap_or_else(|| fallback_message.to_string());
17313            let exception_type = payload_string(payload, "exception_type").or_else(|| {
17314                exception
17315                    .as_ref()
17316                    .and_then(|value| payload_string(value, "type"))
17317            });
17318            let exception_class = payload_string(payload, "exception_class").or_else(|| {
17319                exception
17320                    .as_ref()
17321                    .and_then(|value| payload_string(value, "class"))
17322            });
17323            outcomes.push(Err(ChildWorkflowFailure {
17324                kind,
17325                reason: reason.to_string(),
17326                message,
17327                parent_workflow_id: parent.workflow_id.clone(),
17328                parent_workflow_run_id: parent.run_id.clone(),
17329                child_workflow_id,
17330                child_workflow_run_id,
17331                child_workflow_type,
17332                failure_id: payload_string(payload, "failure_id"),
17333                failure_category: payload_string(payload, "failure_category"),
17334                exception_type,
17335                exception_class,
17336                non_retryable: payload
17337                    .get("non_retryable")
17338                    .and_then(Value::as_bool)
17339                    .unwrap_or(false),
17340                code: payload
17341                    .get("code")
17342                    .filter(|value| !value.is_null())
17343                    .cloned(),
17344                exception,
17345            }));
17346            continue;
17347        }
17348
17349        let codec = payload
17350            .get("payload_codec")
17351            .and_then(Value::as_str)
17352            .unwrap_or(fallback_codec);
17353        let result = payload
17354            .get("result")
17355            .or_else(|| payload.get("output"))
17356            .unwrap_or(&Value::Null);
17357        outcomes.push(Ok(ChildWorkflowAvroResult {
17358            parent: parent.clone(),
17359            child: WorkflowIdentity {
17360                workflow_id: child_workflow_id,
17361                run_id: child_workflow_run_id,
17362            },
17363            child_workflow_type,
17364            result: decode_wire_avro_value(result, codec)?,
17365        }));
17366    }
17367
17368    Ok(outcomes)
17369}
17370
17371fn payload_string(payload: &Value, key: &str) -> Option<String> {
17372    payload
17373        .get(key)
17374        .and_then(Value::as_str)
17375        .filter(|value| !value.is_empty())
17376        .map(str::to_string)
17377}
17378
17379fn recorded_activity_failure_boundary(
17380    ctx: &WorkflowContext,
17381    error: &Error,
17382) -> Option<(u64, String)> {
17383    let Error::ActivityFailed(failure) = error else {
17384        return None;
17385    };
17386    if failure.kind != ActivityFailureKind::Failed {
17387        return None;
17388    }
17389    let activity_execution_id = failure
17390        .activity_execution_id
17391        .as_deref()
17392        .filter(|value| !value.is_empty())?;
17393    let state = ctx.state.lock().ok()?;
17394    let mut matches = state.recorded_commands.iter().filter_map(|command| {
17395        let RecordedCommand::Activity {
17396            sequence,
17397            outcome: Some(Err(recorded_failure)),
17398            ..
17399        } = command
17400        else {
17401            return None;
17402        };
17403        (*sequence > 0 && recorded_failure == failure)
17404            .then_some((*sequence, activity_execution_id.to_string()))
17405    });
17406    let boundary = matches.next()?;
17407    matches.next().is_none().then_some(boundary)
17408}
17409
17410fn workflow_failure_command(
17411    error: &Error,
17412    failed_activity_boundary: Option<(u64, String)>,
17413) -> Value {
17414    let (exception_type, exception_class, properties) = match error {
17415        Error::ActivityFailed(failure) => (
17416            match failure.kind {
17417                ActivityFailureKind::Failed => "ActivityFailed",
17418                ActivityFailureKind::Cancelled => "ActivityCancelled",
17419                ActivityFailureKind::TimedOut => "ActivityTimedOut",
17420            },
17421            "durable_workflow::ActivityFailure",
17422            json!({
17423                "reason": failure.reason,
17424                "activity_execution_id": failure.activity_execution_id,
17425                "activity_attempt_id": failure.activity_attempt_id,
17426                "activity_type": failure.activity_type,
17427                "activity_class": failure.activity_class,
17428                "attempt_number": failure.attempt_number,
17429                "failure_id": failure.failure_id,
17430                "failure_category": failure.failure_category,
17431                "timeout_kind": failure.timeout_kind,
17432                "activity_non_retryable": failure.non_retryable,
17433                "activity_exception_type": failure.exception_type,
17434                "activity_exception_class": failure.exception_class,
17435                "activity_code": failure.code,
17436                "activity_exception": failure.exception,
17437            }),
17438        ),
17439        Error::ChildWorkflowFailed(failure) => (
17440            match failure.kind {
17441                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17442                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17443                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17444            },
17445            "durable_workflow::ChildWorkflowFailure",
17446            json!({
17447                "reason": failure.reason,
17448                "parent_workflow_id": failure.parent_workflow_id,
17449                "parent_workflow_run_id": failure.parent_workflow_run_id,
17450                "child_workflow_id": failure.child_workflow_id,
17451                "child_workflow_run_id": failure.child_workflow_run_id,
17452                "child_workflow_type": failure.child_workflow_type,
17453                "failure_id": failure.failure_id,
17454                "failure_category": failure.failure_category,
17455                "child_exception_type": failure.exception_type,
17456                "child_exception_class": failure.exception_class,
17457                "child_non_retryable": failure.non_retryable,
17458                "child_code": failure.code,
17459                "child_exception": failure.exception,
17460            }),
17461        ),
17462        Error::ParallelFailed(failure) => (
17463            "ParallelFailed",
17464            "durable_workflow::ParallelFailure",
17465            json!({
17466                "parallel_group_id": failure.group_id,
17467                "parallel_member_path": failure.member_path,
17468                "parallel_group_path": failure.group_path,
17469                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
17470                "cause_type": workflow_error_type(&failure.cause),
17471                "cause_message": failure.cause.to_string(),
17472            }),
17473        ),
17474        Error::SagaCompensationFailed(failure) => (
17475            "SagaCompensationFailed",
17476            "durable_workflow::SagaCompensationFailure",
17477            json!({
17478                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
17479                "initiating_failure_message": failure.initiating_failure.to_string(),
17480                "compensation_activity_type": failure.compensation_activity_type,
17481                "compensation_registration_order": failure.compensation_registration_order,
17482                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
17483                "compensation_failure_message": failure.compensation_failure.to_string(),
17484            }),
17485        ),
17486        Error::WorkflowCancellationRequested(_) => (
17487            "WorkflowCancellationRequested",
17488            "durable_workflow::WorkflowCancellationRequested",
17489            json!({"reason": "cancelled"}),
17490        ),
17491        Error::CooperativeCancellationRequested(cancellation) => (
17492            "WorkflowCancellationRequested",
17493            "durable_workflow::CooperativeCancellationRequested",
17494            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
17495                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
17496        ),
17497        Error::CancellationScopeRequested(cancellation) => (
17498            "WorkflowCancellationRequested",
17499            "durable_workflow::CancellationScopeRequested",
17500            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
17501                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
17502                "cancellation":cancellation.context.to_value()}),
17503        ),
17504        Error::NonDeterministicReplay(_) => (
17505            "NonDeterministicReplay",
17506            "durable_workflow::Error",
17507            Value::Null,
17508        ),
17509        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
17510    };
17511    let non_retryable = 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(_) => true,
17521        Error::NonDeterministicReplay(_) => true,
17522        _ => false,
17523    };
17524
17525    let mut command = json!({
17526        "type": "fail_workflow",
17527        "message": error.to_string(),
17528        "exception_type": exception_type,
17529        "exception_class": exception_class,
17530        "non_retryable": non_retryable,
17531        "exception": {
17532            "type": exception_type,
17533            "class": exception_class,
17534            "message": error.to_string(),
17535            "properties": properties,
17536        }
17537    });
17538
17539    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
17540        command["failed_step_sequence"] = json!(sequence);
17541        command["failed_activity_execution_id"] = json!(activity_execution_id);
17542    }
17543
17544    command
17545}
17546
17547fn workflow_error_type(error: &Error) -> &'static str {
17548    match error {
17549        Error::ActivityFailed(failure) => match failure.kind {
17550            ActivityFailureKind::Failed => "ActivityFailed",
17551            ActivityFailureKind::Cancelled => "ActivityCancelled",
17552            ActivityFailureKind::TimedOut => "ActivityTimedOut",
17553        },
17554        Error::ChildWorkflowFailed(failure) => match failure.kind {
17555            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17556            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17557            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17558        },
17559        Error::ParallelFailed(_) => "ParallelFailed",
17560        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
17561        Error::WorkflowCancellationRequested(_)
17562        | Error::CooperativeCancellationRequested(_)
17563        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
17564        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
17565        _ => "RustWorkflowError",
17566    }
17567}
17568
17569fn workflow_error_non_retryable(error: &Error) -> bool {
17570    match error {
17571        Error::ActivityFailed(failure) => failure.non_retryable,
17572        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17573        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17574        Error::SagaCompensationFailed(failure) => {
17575            workflow_error_non_retryable(&failure.compensation_failure)
17576        }
17577        Error::WorkflowCancellationRequested(_)
17578        | Error::CooperativeCancellationRequested(_)
17579        | Error::CancellationScopeRequested(_)
17580        | Error::NonDeterministicReplay(_) => true,
17581        _ => false,
17582    }
17583}
17584
17585fn workflow_task_integrity_error(error: &Error) -> bool {
17586    matches!(
17587        error,
17588        Error::NonDeterministicReplay(_)
17589            | Error::Protocol(_)
17590            | Error::CancellationScopeExecutionUnavailable
17591            | Error::MissingWorkflowCommandIdentity
17592            | Error::WorkflowStatePoisoned
17593    )
17594}
17595
17596fn decode_signal_event_arguments(
17597    event: &HistoryEvent,
17598    fallback_codec: &str,
17599) -> Result<Vec<AvroValue>> {
17600    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17601    validate_payload_codec(codec)?;
17602    let raw = signal_history_payload(&event.payload);
17603    let decoded = match raw.filter(|value| !value.is_null()) {
17604        Some(value) => decode_wire_avro_value(value, codec)?,
17605        None => AvroValue::Array(Vec::new()),
17606    };
17607    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17608        unreachable!("normalize_avro_arguments always returns an array");
17609    };
17610    Ok(arguments)
17611}
17612
17613fn decode_update_event_arguments(
17614    event: &HistoryEvent,
17615    fallback_codec: &str,
17616) -> Result<Vec<AvroValue>> {
17617    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17618    validate_payload_codec(codec)?;
17619    let decoded = match event
17620        .payload
17621        .get("arguments")
17622        .filter(|value| !value.is_null())
17623    {
17624        Some(value) => decode_wire_avro_value(value, codec)?,
17625        None => AvroValue::Array(Vec::new()),
17626    };
17627    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17628        unreachable!("normalize_avro_arguments always returns an array");
17629    };
17630    Ok(arguments)
17631}
17632
17633fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17634    let Some(export_events) = task
17635        .history_export
17636        .as_ref()
17637        .and_then(|export| export.get("history_events"))
17638        .and_then(Value::as_array)
17639    else {
17640        return Ok(());
17641    };
17642
17643    if export_events.len() > task.history_events.len() {
17644        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
17645    }
17646
17647    Ok(())
17648}
17649
17650fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17651    let Some(export) = task.history_export.as_ref() else {
17652        return Ok(());
17653    };
17654    let signals = export
17655        .get("signals")
17656        .and_then(Value::as_array)
17657        .cloned()
17658        .unwrap_or_default();
17659    let activities = export
17660        .get("activities")
17661        .and_then(Value::as_array)
17662        .cloned()
17663        .unwrap_or_default();
17664    let export_codec = export
17665        .get("payloads")
17666        .and_then(|payloads| payloads.get("codec"))
17667        .and_then(Value::as_str)
17668        .unwrap_or(&task.payload_codec)
17669        .to_string();
17670    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
17671
17672    for event in &mut task.history_events {
17673        if event.event_type == "ActivityCompleted" {
17674            let sequence = event
17675                .payload
17676                .get("sequence")
17677                .or_else(|| event.payload.get("workflow_sequence"))
17678                .and_then(value_as_u64);
17679            let Some(activity) = sequence.and_then(|sequence| {
17680                activities.iter().find(|activity| {
17681                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
17682                })
17683            }) else {
17684                continue;
17685            };
17686            let Some(payload) = event.payload.as_object_mut() else {
17687                continue;
17688            };
17689            if missing_payload(payload.get("result")) {
17690                if let Some(result) = activity
17691                    .get("result")
17692                    .filter(|value| !missing_payload(Some(value)))
17693                {
17694                    payload.insert("result".to_string(), result.clone());
17695                }
17696            }
17697            for field in ["payload_codec", "activity_type"] {
17698                if payload
17699                    .get(field)
17700                    .and_then(Value::as_str)
17701                    .unwrap_or_default()
17702                    .is_empty()
17703                {
17704                    if let Some(value) = activity.get(field) {
17705                        payload.insert(field.to_string(), value.clone());
17706                    }
17707                }
17708            }
17709            continue;
17710        }
17711
17712        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
17713            continue;
17714        }
17715        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17716        let command_id = event
17717            .payload
17718            .get("workflow_command_id")
17719            .or_else(|| event.raw.get("workflow_command_id"))
17720            .and_then(Value::as_str);
17721        let signal_name = event
17722            .payload
17723            .get("signal_name")
17724            .and_then(Value::as_str)
17725            .unwrap_or_default()
17726            .to_string();
17727        let matched = signals
17728            .iter()
17729            .find(|signal| {
17730                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
17731            })
17732            .or_else(|| {
17733                signals.iter().find(|signal| {
17734                    command_id.is_some()
17735                        && signal.get("command_id").and_then(Value::as_str) == command_id
17736                })
17737            })
17738            .or_else(|| {
17739                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
17740                let signal = signals
17741                    .iter()
17742                    .filter(|signal| {
17743                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
17744                    })
17745                    .nth(*offset);
17746                if signal.is_some() {
17747                    *offset += 1;
17748                }
17749                signal
17750            });
17751        let Some(signal) = matched else {
17752            continue;
17753        };
17754        let signal_codec = signal
17755            .get("payload_codec")
17756            .and_then(Value::as_str)
17757            .unwrap_or(&export_codec);
17758        let Some(payload) = event.payload.as_object_mut() else {
17759            continue;
17760        };
17761        if missing_payload(payload.get("arguments")) {
17762            if let Some(arguments) = signal
17763                .get("arguments")
17764                .filter(|value| !missing_payload(Some(value)))
17765            {
17766                let envelope = match arguments {
17767                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
17768                    other => other.clone(),
17769                };
17770                payload.insert("arguments".to_string(), envelope);
17771            }
17772        }
17773        if payload
17774            .get("payload_codec")
17775            .and_then(Value::as_str)
17776            .unwrap_or_default()
17777            .is_empty()
17778        {
17779            payload.insert("payload_codec".to_string(), json!(signal_codec));
17780        }
17781    }
17782
17783    Ok(())
17784}
17785
17786fn missing_payload(value: Option<&Value>) -> bool {
17787    match value {
17788        None | Some(Value::Null) => true,
17789        Some(Value::String(value)) => value.is_empty(),
17790        Some(_) => false,
17791    }
17792}
17793
17794fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
17795    history_signal_events(
17796        &task.history_events,
17797        task.history_export.as_ref(),
17798        &task.payload_codec,
17799    )
17800}
17801
17802fn history_signal_events(
17803    history_events: &[HistoryEvent],
17804    history_export: Option<&Value>,
17805    payload_codec: &str,
17806) -> Result<Vec<QuerySignal>> {
17807    let export_signals = history_export
17808        .and_then(|export| export.get("signals"))
17809        .and_then(Value::as_array)
17810        .cloned()
17811        .unwrap_or_default();
17812    let export_codec = history_export
17813        .and_then(|export| export.get("payloads"))
17814        .and_then(|payloads| payloads.get("codec"))
17815        .and_then(Value::as_str)
17816        .unwrap_or(payload_codec);
17817    let mut name_offsets: HashMap<String, usize> = HashMap::new();
17818    let mut signals: Vec<QuerySignal> = Vec::new();
17819    let mut signal_indices = HashMap::new();
17820    let mut command_indices = HashMap::new();
17821
17822    for event in history_events {
17823        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
17824            continue;
17825        }
17826
17827        let name = event
17828            .payload
17829            .get("signal_name")
17830            .and_then(Value::as_str)
17831            .unwrap_or_default();
17832        if name.is_empty() {
17833            continue;
17834        }
17835        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17836        let command_id = event
17837            .payload
17838            .get("workflow_command_id")
17839            .or_else(|| event.raw.get("workflow_command_id"))
17840            .and_then(Value::as_str);
17841        let matched_export = export_signals
17842            .iter()
17843            .find(|candidate| {
17844                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
17845            })
17846            .or_else(|| {
17847                export_signals.iter().find(|candidate| {
17848                    command_id.is_some()
17849                        && candidate.get("command_id").and_then(Value::as_str) == command_id
17850                })
17851            })
17852            .or_else(|| {
17853                let offset = name_offsets.entry(name.to_string()).or_default();
17854                let candidate = export_signals
17855                    .iter()
17856                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
17857                    .nth(*offset);
17858                if candidate.is_some() {
17859                    *offset += 1;
17860                }
17861                candidate
17862            });
17863        let codec = event
17864            .payload
17865            .get("payload_codec")
17866            .and_then(Value::as_str)
17867            .or_else(|| {
17868                matched_export
17869                    .and_then(|signal| signal.get("payload_codec"))
17870                    .and_then(Value::as_str)
17871            })
17872            .unwrap_or(export_codec);
17873        let raw_arguments = signal_history_payload(&event.payload)
17874            .filter(|value| !value.is_null())
17875            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
17876        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
17877        let workflow_sequence = event
17878            .payload
17879            .get("workflow_sequence")
17880            .and_then(value_as_u64)
17881            .or_else(|| {
17882                matched_export
17883                    .and_then(|signal| signal.get("workflow_sequence"))
17884                    .and_then(value_as_u64)
17885            });
17886
17887        let id = signal_id.or_else(|| {
17888            matched_export
17889                .and_then(|signal| signal.get("id"))
17890                .and_then(Value::as_str)
17891        });
17892        let command_id = command_id.or_else(|| {
17893            matched_export
17894                .and_then(|signal| signal.get("command_id"))
17895                .and_then(Value::as_str)
17896        });
17897        let duplicate = id
17898            .and_then(|id| signal_indices.get(id))
17899            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
17900            .copied();
17901        let index = duplicate.unwrap_or(signals.len());
17902        if let Some(index) = duplicate {
17903            let original = &mut signals[index];
17904            let same_arguments = if event.event_type == "SignalApplied" {
17905                if let Some(value) = event.payload.get("value") {
17906                    let expected = match original.avro_arguments.as_slice() {
17907                        [] => AvroValue::Boolean(true),
17908                        [value] => value.clone(),
17909                        values => AvroValue::Array(values.to_vec()),
17910                    };
17911                    let applied = decode_wire_avro_value(value, codec)?;
17912                    applied == expected
17913                        || applied == AvroValue::Array(original.avro_arguments.clone())
17914                } else {
17915                    original.avro_arguments == avro_arguments
17916                }
17917            } else {
17918                original.avro_arguments == avro_arguments
17919            };
17920            if original.name != name
17921                || !same_arguments
17922                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
17923            {
17924                return Err(Error::Codec("conflicting committed signal identity".into()));
17925            }
17926            if original.id.is_none() {
17927                original.id = id.map(str::to_string);
17928            }
17929            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
17930        } else {
17931            signals.push(QuerySignal {
17932                id: id.map(str::to_string),
17933                name: name.to_string(),
17934                arguments,
17935                avro_arguments,
17936                workflow_sequence,
17937            });
17938        }
17939        if let Some(id) = id {
17940            signal_indices.insert(id.to_string(), index);
17941        }
17942        if let Some(id) = command_id {
17943            command_indices.insert(id.to_string(), index);
17944        }
17945    }
17946
17947    if signals.is_empty() {
17948        for signal in export_signals {
17949            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17950                continue;
17951            }
17952            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17953                continue;
17954            };
17955            let codec = signal
17956                .get("payload_codec")
17957                .and_then(Value::as_str)
17958                .unwrap_or(export_codec);
17959            let (arguments, avro_arguments) =
17960                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17961            signals.push(QuerySignal {
17962                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17963                name: name.to_string(),
17964                arguments,
17965                avro_arguments,
17966                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17967            });
17968        }
17969        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17970    }
17971
17972    Ok(signals)
17973}
17974
17975fn decode_query_signal_arguments(
17976    raw: Option<&Value>,
17977    codec: &str,
17978) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17979    validate_payload_codec(codec)?;
17980    let decoded = match raw.filter(|value| !value.is_null()) {
17981        Some(value) => decode_wire_avro_value(value, codec)?,
17982        None => AvroValue::Array(Vec::new()),
17983    };
17984    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17985        unreachable!("normalize_avro_arguments always returns an array");
17986    };
17987    let arguments = avro_arguments
17988        .iter()
17989        .cloned()
17990        .map(AvroValue::into_json)
17991        .collect::<Result<Vec<_>>>()?;
17992    Ok((arguments, avro_arguments))
17993}
17994
17995fn value_as_u64(value: &Value) -> Option<u64> {
17996    value
17997        .as_u64()
17998        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17999}
18000
18001#[cfg(test)]
18002mod tests {
18003    use super::*;
18004    mod activity_cancellation_policies;
18005    mod cancellation_scope_admission;
18006    mod cancellation_scope_authoring;
18007    mod cancellation_scope_history;
18008    mod cancellation_scope_opening;
18009    mod cancellation_scope_replay;
18010    mod child_workflow_policies;
18011    mod cooperative_cancellation;
18012    mod local_activity;
18013    mod runtime_payloads;
18014    mod runtime_uploads;
18015    mod version_marker_contract;
18016    mod worker_session;
18017    use std::{
18018        fs,
18019        io::{Read, Write},
18020        net::{SocketAddr, TcpListener, TcpStream},
18021        process::Command as ProcessCommand,
18022        sync::atomic::AtomicUsize,
18023        thread,
18024    };
18025
18026    #[derive(Clone, Copy, Debug)]
18027    enum InvalidTaskPayloadCodec {
18028        Missing,
18029        Null,
18030        NonString,
18031    }
18032
18033    impl InvalidTaskPayloadCodec {
18034        fn label(self) -> &'static str {
18035            match self {
18036                Self::Missing => "missing",
18037                Self::Null => "null",
18038                Self::NonString => "non-string",
18039            }
18040        }
18041
18042        fn apply(self, task: &mut Value) {
18043            let task = task.as_object_mut().expect("task fixture object");
18044            match self {
18045                Self::Missing => {
18046                    task.remove("payload_codec");
18047                }
18048                Self::Null => {
18049                    task.insert("payload_codec".to_string(), Value::Null);
18050                }
18051                Self::NonString => {
18052                    task.insert("payload_codec".to_string(), json!(42));
18053                }
18054            }
18055        }
18056    }
18057
18058    fn fixture_envelope(value: Value) -> Value {
18059        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
18060    }
18061
18062    fn fixture_blob(value: Value) -> String {
18063        encode_payload(&value, DEFAULT_CODEC)
18064            .expect("encode Avro test fixture")
18065            .blob
18066    }
18067
18068    #[test]
18069    fn client_builder_rejects_the_sdk_owned_api_suffix() {
18070        for base_url in [
18071            "http://127.0.0.1:8080/api",
18072            "http://localhost:8080/api/",
18073            "https://runtime.example.test/namespaces/orders/api",
18074        ] {
18075            let error = Client::builder(base_url)
18076                .build()
18077                .expect_err("SDK-owned /api suffix must be rejected during build");
18078
18079            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
18080            assert!(
18081                error.to_string().contains("SDK appends /api automatically"),
18082                "the validation error must explain how to fix the endpoint"
18083            );
18084        }
18085    }
18086
18087    #[test]
18088    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
18089        for (base_url, expected) in [
18090            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
18091            (
18092                "http://localhost:8080/durable-workflow/",
18093                "http://localhost:8080/durable-workflow",
18094            ),
18095            (
18096                "https://runtime.example.test/namespaces/orders",
18097                "https://runtime.example.test/namespaces/orders",
18098            ),
18099            (
18100                "https://runtime.example.test/gateway/api/namespaces/orders",
18101                "https://runtime.example.test/gateway/api/namespaces/orders",
18102            ),
18103            (
18104                "https://api.example.test/runtime/orders/",
18105                "https://api.example.test/runtime/orders",
18106            ),
18107        ] {
18108            let client = Client::builder(base_url)
18109                .build()
18110                .expect("Server and Cloud runtime base URL must remain valid");
18111
18112            assert_eq!(client.base_url, expected);
18113        }
18114    }
18115
18116    #[test]
18117    fn workflow_completion_uses_the_additive_command_protocol_floor() {
18118        assert_eq!(
18119            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
18120            MINIMUM_WORKER_PROTOCOL_VERSION
18121        );
18122        assert_eq!(
18123            workflow_completion_protocol_version(&[json!({
18124                "type": "upsert_search_attributes",
18125                "attributes": {"OrderStatus": "waiting"},
18126            })]),
18127            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
18128        );
18129        assert_eq!(
18130            workflow_completion_protocol_version(&[json!({
18131                "type": "upsert_search_attributes",
18132                "attributes": {"OrderStatus": "waiting"},
18133                "attribute_types": {"OrderStatus": "keyword"},
18134            })]),
18135            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
18136        );
18137        assert_eq!(
18138            workflow_completion_protocol_version(&[
18139                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
18140                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18141            ]),
18142            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
18143        );
18144        assert_eq!(
18145            workflow_completion_protocol_version(&[
18146                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
18147                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18148            ]),
18149            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
18150        );
18151        assert_eq!(
18152            workflow_completion_protocol_version(&[json!({
18153                "type": "open_condition_wait",
18154                "condition_wait_occurrence_id": "rust:condition-wait:0",
18155                "condition_key": "ready",
18156            })]),
18157            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18158        );
18159        assert_eq!(
18160            workflow_completion_protocol_version_with_message_streams(
18161                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
18162                true,
18163            ),
18164            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
18165        );
18166        assert_eq!(
18167            workflow_completion_protocol_version_with_message_streams(
18168                &[json!({
18169                    "type": "open_condition_wait",
18170                    "condition_wait_occurrence_id": "rust:condition-wait:0",
18171                    "condition_key": "ready",
18172                })],
18173                true,
18174            ),
18175            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18176        );
18177    }
18178
18179    #[test]
18180    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
18181        let manifest = portable_worker_affinity_capability_manifest();
18182
18183        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
18184            assert_eq!(manifest[capability]["supported"], json!(false));
18185            assert_eq!(
18186                manifest[capability]["minimum_protocol_version"],
18187                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
18188            );
18189            assert!(manifest[capability]["reason"]
18190                .as_str()
18191                .is_some_and(|reason| !reason.is_empty()));
18192        }
18193    }
18194
18195    fn typed_fidelity_probe() -> AvroValue {
18196        AvroValue::Map(BTreeMap::from([
18197            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
18198            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
18199            (
18200                "numeric".to_string(),
18201                AvroValue::Map(BTreeMap::from([
18202                    ("0".to_string(), AvroValue::String("zero".to_string())),
18203                    ("1".to_string(), AvroValue::String("one".to_string())),
18204                ])),
18205            ),
18206            (
18207                "nested".to_string(),
18208                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
18209                    "enabled".to_string(),
18210                    AvroValue::Boolean(true),
18211                )]))]),
18212            ),
18213            (
18214                "projection_collisions".to_string(),
18215                AvroValue::Array(projection_collision_probe()),
18216            ),
18217        ]))
18218    }
18219
18220    fn projection_collision_probe() -> Vec<AvroValue> {
18221        vec![
18222            AvroValue::Map(BTreeMap::from([
18223                ("$type".to_string(), AvroValue::String("bytes".to_string())),
18224                (
18225                    "base64".to_string(),
18226                    AvroValue::String("ordinary user text".to_string()),
18227                ),
18228            ])),
18229            AvroValue::Map(BTreeMap::from([
18230                ("$type".to_string(), AvroValue::String("map".to_string())),
18231                (
18232                    "entries".to_string(),
18233                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
18234                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
18235                        (
18236                            "value".to_string(),
18237                            AvroValue::String("user map".to_string()),
18238                        ),
18239                    ]))]),
18240                ),
18241            ])),
18242        ]
18243    }
18244
18245    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18246    struct TypedContract {
18247        nested: TypedNested,
18248        mode: TypedMode,
18249        optional: Option<String>,
18250        absent: Option<String>,
18251        items: Vec<i64>,
18252        labels: BTreeMap<String, String>,
18253        bytes: serde_bytes::ByteBuf,
18254        signed: i64,
18255        finite: f64,
18256    }
18257
18258    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18259    struct TypedNested {
18260        enabled: bool,
18261    }
18262
18263    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18264    enum TypedMode {
18265        Detailed { label: String },
18266    }
18267
18268    fn typed_contract() -> TypedContract {
18269        TypedContract {
18270            nested: TypedNested { enabled: true },
18271            mode: TypedMode::Detailed {
18272                label: "compiler-checked".to_string(),
18273            },
18274            optional: Some("present".to_string()),
18275            absent: None,
18276            items: vec![i64::MIN, 0, i64::MAX],
18277            labels: BTreeMap::from([
18278                ("language".to_string(), "rust".to_string()),
18279                ("wire".to_string(), "avro".to_string()),
18280            ]),
18281            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
18282            signed: -9_223_372_036_854_775_000,
18283            finite: 12.5,
18284        }
18285    }
18286
18287    #[derive(Clone, Debug, Default, PartialEq)]
18288    struct ReplayCounterState {
18289        loaded: Option<String>,
18290        count: i64,
18291        finished: bool,
18292    }
18293
18294    fn replay_counter_worker() -> Worker {
18295        let client = Client::new("http://127.0.0.1:8080").expect("client");
18296        let mut worker = Worker::new(client, "rust-workers");
18297        worker.register_replayed_workflow(
18298            "replay-counter",
18299            ReplayCounterState::default,
18300            |ctx, _input, state| async move {
18301                let loaded = ctx.activity("load-counter", json!([])).await?;
18302                state.update(|current| {
18303                    current.loaded = loaded.as_str().map(str::to_string);
18304                })?;
18305                for _ in 0..2 {
18306                    let signal = ctx.wait_signal("increment").await?;
18307                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
18308                    state.update(|current| current.count += amount)?;
18309                }
18310                state.update(|current| current.finished = true)?;
18311                state.read(|current| Ok(json!(current.count)))?
18312            },
18313        );
18314        worker.register_replayed_query::<ReplayCounterState, _, _>(
18315            "replay-counter",
18316            "current",
18317            |_ctx, state, _args| async move {
18318                Ok(json!({
18319                    "loaded": state.loaded,
18320                    "count": state.count,
18321                    "finished": state.finished,
18322                }))
18323            },
18324        );
18325        worker.register_replayed_query::<ReplayCounterState, _, _>(
18326            "replay-counter",
18327            "detached-mutation",
18328            |_ctx, state, _args| async move {
18329                let mut detached = (*state).clone();
18330                detached.count = 999;
18331                Ok(json!(detached.count))
18332            },
18333        );
18334        worker.register_replayed_query::<ReplayCounterState, _, _>(
18335            "replay-counter",
18336            "failed-mutation",
18337            |_ctx, state, _args| async move {
18338                let mut detached = (*state).clone();
18339                detached.count = 999;
18340                Err(Error::WorkerLoop("query refused".to_string()))
18341            },
18342        );
18343        worker
18344    }
18345
18346    fn replay_counter_query(
18347        query_name: &str,
18348        history_events: Value,
18349        run_status: &str,
18350    ) -> QueryTask {
18351        let arguments = fixture_envelope(json!([]));
18352        serde_json::from_value(json!({
18353            "query_task_id": format!("query-{query_name}"),
18354            "workflow_type": "replay-counter",
18355            "query_name": query_name,
18356            "payload_codec": DEFAULT_CODEC,
18357            "workflow_arguments": arguments.clone(),
18358            "query_arguments": arguments,
18359            "history_events": history_events,
18360            "run_status": run_status,
18361        }))
18362        .expect("query task")
18363    }
18364
18365    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
18366        workflow_context_with_codec(history, DEFAULT_CODEC)
18367    }
18368
18369    fn workflow_context_with_codec(
18370        history: Vec<HistoryEvent>,
18371        payload_codec: &str,
18372    ) -> WorkflowContext {
18373        WorkflowContext {
18374            cancellation_scope_id: "root".into(),
18375            state: Arc::new(Mutex::new(
18376                WorkflowState::new_with_identity(
18377                    history,
18378                    None,
18379                    None,
18380                    "rust-workers".to_string(),
18381                    payload_codec.to_string(),
18382                    None,
18383                )
18384                .expect("valid workflow history"),
18385            )),
18386        }
18387    }
18388
18389    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
18390        HistoryEvent {
18391            event_type: event_type.to_string(),
18392            payload,
18393            raw: HashMap::new(),
18394        }
18395    }
18396
18397    fn parallel_path_entry(
18398        kind: &str,
18399        base: u64,
18400        size: usize,
18401        index: usize,
18402    ) -> ParallelGroupMetadata {
18403        parallel_group_entry(base, size, index, kind)
18404    }
18405
18406    fn parallel_history_event(
18407        event_type: &str,
18408        sequence: u64,
18409        identity_field: &str,
18410        identity: &str,
18411        path: Vec<ParallelGroupMetadata>,
18412        result: Option<Value>,
18413    ) -> HistoryEvent {
18414        let mut payload = serde_json::Map::from_iter([
18415            ("sequence".to_string(), json!(sequence)),
18416            (identity_field.to_string(), json!(identity)),
18417        ]);
18418        let inner = path.last().expect("parallel history path");
18419        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
18420        payload.insert("parallel_group_path".to_string(), json!(path));
18421        if let Some(result) = result {
18422            let field = if event_type == "ChildRunCompleted" {
18423                "result"
18424            } else {
18425                "result"
18426            };
18427            payload.insert(field.to_string(), fixture_envelope(result));
18428            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
18429        }
18430        history_event(event_type, Value::Object(payload))
18431    }
18432
18433    fn nested_parallel_operations() -> Vec<ParallelOperation> {
18434        vec![
18435            ParallelOperation::activity("first", json!([])),
18436            ParallelOperation::group(vec![
18437                ParallelOperation::child_workflow(
18438                    "second",
18439                    ChildWorkflowOptions::new("child-workers"),
18440                    json!([]),
18441                ),
18442                ParallelOperation::activity("third", json!([])),
18443            ]),
18444        ]
18445    }
18446
18447    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
18448        let outer = [
18449            parallel_path_entry("mixed", 1, 3, 0),
18450            parallel_path_entry("mixed", 1, 3, 1),
18451            parallel_path_entry("mixed", 1, 3, 2),
18452        ];
18453        [
18454            vec![outer[0].clone()],
18455            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
18456            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
18457        ]
18458    }
18459
18460    #[test]
18461    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
18462        let ctx = workflow_context(Vec::new());
18463        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18464        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18465
18466        assert!(matches!(
18467            call.as_mut().poll(&mut task_context),
18468            Poll::Pending
18469        ));
18470        let commands = ctx.take_commands().expect("parallel commands");
18471        assert_eq!(
18472            commands
18473                .iter()
18474                .map(|command| command["type"].as_str().unwrap_or_default())
18475                .collect::<Vec<_>>(),
18476            [
18477                "schedule_activity",
18478                "start_child_workflow",
18479                "schedule_activity"
18480            ]
18481        );
18482        let paths = nested_parallel_paths();
18483        for (command, path) in commands.iter().zip(paths) {
18484            assert_eq!(command["parallel_group_path"], json!(path));
18485            assert_eq!(
18486                command["parallel_group_id"],
18487                json!(path.last().expect("inner group").parallel_group_id)
18488            );
18489        }
18490    }
18491
18492    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
18493        let paths = nested_parallel_paths();
18494        let third = parallel_history_event(
18495            "ActivityCompleted",
18496            3,
18497            "activity_type",
18498            "third",
18499            paths[2].clone(),
18500            Some(json!("three")),
18501        );
18502        vec![
18503            parallel_history_event(
18504                "ActivityCompleted",
18505                1,
18506                "activity_type",
18507                "first",
18508                paths[0].clone(),
18509                Some(json!("one")),
18510            ),
18511            parallel_history_event(
18512                "ChildWorkflowScheduled",
18513                2,
18514                "child_workflow_type",
18515                "second",
18516                paths[1].clone(),
18517                None,
18518            ),
18519            parallel_history_event(
18520                "ChildRunCompleted",
18521                2,
18522                "child_workflow_type",
18523                "second",
18524                paths[1].clone(),
18525                Some(json!("two")),
18526            ),
18527            third.clone(),
18528            third,
18529        ]
18530    }
18531
18532    #[test]
18533    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
18534        for _restart_or_completed_replay in 0..2 {
18535            let ctx = workflow_context(completed_nested_parallel_history());
18536            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18537            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18538            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
18539                panic!("completed nested parallel history must replay");
18540            };
18541            assert_eq!(
18542                results,
18543                vec![
18544                    ParallelResult::Activity(json!("one")),
18545                    ParallelResult::Group(vec![
18546                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
18547                            parent: WorkflowIdentity {
18548                                workflow_id: None,
18549                                run_id: None,
18550                            },
18551                            child: WorkflowIdentity {
18552                                workflow_id: None,
18553                                run_id: None,
18554                            },
18555                            child_workflow_type: Some("second".to_string()),
18556                            result: json!("two"),
18557                        }),
18558                        ParallelResult::Activity(json!("three")),
18559                    ]),
18560                ]
18561            );
18562            assert!(ctx.take_commands().expect("commands").is_empty());
18563            ctx.ensure_history_consumed().expect("history consumed");
18564        }
18565    }
18566
18567    #[test]
18568    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
18569        let paths = nested_parallel_paths();
18570        let history = vec![
18571            parallel_history_event(
18572                "ActivityCompleted",
18573                1,
18574                "activity_type",
18575                "first",
18576                paths[0].clone(),
18577                Some(json!("one")),
18578            ),
18579            parallel_history_event(
18580                "ChildWorkflowScheduled",
18581                2,
18582                "child_workflow_type",
18583                "second",
18584                paths[1].clone(),
18585                None,
18586            ),
18587            parallel_history_event(
18588                "ChildRunFailed",
18589                2,
18590                "child_workflow_type",
18591                "second",
18592                paths[1].clone(),
18593                None,
18594            ),
18595            parallel_history_event(
18596                "ActivityCompleted",
18597                3,
18598                "activity_type",
18599                "third",
18600                paths[2].clone(),
18601                Some(json!("late")),
18602            ),
18603        ];
18604        let ctx = workflow_context(history);
18605        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18606        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18607        let outcome = call.as_mut().poll(&mut task_context);
18608        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
18609            panic!("one failed child must return a typed partial failure: {outcome:?}");
18610        };
18611        assert_eq!(failure.member_path, [1, 0]);
18612        assert_eq!(failure.group_id, "parallel-calls:1:3");
18613        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
18614        assert_eq!(
18615            failure
18616                .completed
18617                .iter()
18618                .map(|completion| completion.member_path.clone())
18619                .collect::<Vec<_>>(),
18620            [vec![0], vec![1, 1]]
18621        );
18622    }
18623
18624    #[test]
18625    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
18626        let paths = nested_parallel_paths();
18627        let history = vec![
18628            parallel_history_event(
18629                "ActivityScheduled",
18630                1,
18631                "activity_type",
18632                "first",
18633                paths[0].clone(),
18634                None,
18635            ),
18636            parallel_history_event(
18637                "ChildWorkflowScheduled",
18638                2,
18639                "child_workflow_type",
18640                "second",
18641                paths[1].clone(),
18642                None,
18643            ),
18644            parallel_history_event(
18645                "ActivityScheduled",
18646                3,
18647                "activity_type",
18648                "third",
18649                paths[2].clone(),
18650                None,
18651            ),
18652        ];
18653        for _restart in 0..2 {
18654            let ctx = workflow_context(history.clone());
18655            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18656            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18657            let outcome = call.as_mut().poll(&mut task_context);
18658            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
18659            assert!(ctx.take_commands().expect("commands").is_empty());
18660        }
18661    }
18662
18663    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
18664        vec![selection_group_entry(
18665            1,
18666            2,
18667            index,
18668            "activity",
18669            &SelectionMemberMetadata {
18670                key: SelectionKey::Name(key.to_string()),
18671                index,
18672                base_sequence: index as u64 + 1,
18673                size: 1,
18674                kind: "activity".to_string(),
18675            },
18676        )]
18677    }
18678
18679    fn selection_activity_event(
18680        event_type: &str,
18681        index: usize,
18682        key: &str,
18683        result: Option<Value>,
18684    ) -> HistoryEvent {
18685        let sequence = index as u64 + 1;
18686        let mut event = parallel_history_event(
18687            event_type,
18688            sequence,
18689            "activity_type",
18690            &format!("{key}-activity"),
18691            selection_path(index, key),
18692            result,
18693        );
18694        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
18695        event.raw.insert(
18696            "id".to_string(),
18697            json!(if event_type == "ActivityCompleted" {
18698                format!("event-{key}")
18699            } else {
18700                format!("{event_type}-{key}")
18701            }),
18702        );
18703        event
18704    }
18705
18706    fn selection_winner_marker() -> HistoryEvent {
18707        history_event(
18708            "SelectionResolved",
18709            json!({
18710                "selection_group_id": "select-calls:1:2",
18711                "selection_group_base_sequence": 1,
18712                "selection_group_size": 2,
18713                "member_key": "fast",
18714                "member_index": 1,
18715                "member_base_sequence": 2,
18716                "member_size": 1,
18717                "operation_kind": "activity",
18718                "operation_identity": "activity-fast",
18719                "outcome": "completed",
18720                "resolution_event_id": "event-fast",
18721                "resolution_event_type": "ActivityCompleted",
18722            }),
18723        )
18724    }
18725
18726    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
18727        ctx.select_keyed(vec![
18728            (
18729                "slow",
18730                ParallelOperation::activity_with_options(
18731                    "slow-activity",
18732                    ActivityOptions::new().task_queue("default"),
18733                    json!([]),
18734                ),
18735            ),
18736            (
18737                "fast",
18738                ParallelOperation::activity_with_options(
18739                    "fast-activity",
18740                    ActivityOptions::new().task_queue("default"),
18741                    json!([]),
18742                ),
18743            ),
18744        ])
18745    }
18746
18747    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
18748        let ctx = workflow_context(history);
18749        let mut call = Box::pin(keyed_activity_selection(&ctx));
18750        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18751        let selected = match call.as_mut().poll(&mut task_context) {
18752            Poll::Ready(Ok(selected)) => selected,
18753            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
18754            Poll::Pending => panic!("persisted selection winner must replay without pending"),
18755        };
18756        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
18757        assert_eq!(
18758            selected.value,
18759            Some(ParallelResult::Activity(json!("winner-value")))
18760        );
18761        let slow = selected
18762            .handle(&SelectionKey::Name("slow".to_string()))
18763            .expect("slow handle")
18764            .clone();
18765        let mut await_slow = Box::pin(slow.await_result());
18766        assert!(matches!(
18767            await_slow.as_mut().poll(&mut task_context),
18768            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
18769        ));
18770        assert!(ctx.take_commands().expect("commands").is_empty());
18771    }
18772
18773    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
18774
18775    fn canonical_selection_history() -> Vec<HistoryEvent> {
18776        const FIXTURE: &[u8] =
18777            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
18778        assert_eq!(
18779            format!("{:x}", Sha256::digest(FIXTURE)),
18780            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18781        );
18782        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
18783
18784        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
18785    }
18786
18787    #[test]
18788    fn selection_fresh_process_entrypoint() {
18789        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
18790            return;
18791        };
18792        let persisted = fs::read(path).expect("persisted selection history");
18793        assert_eq!(
18794            format!("{:x}", Sha256::digest(&persisted)),
18795            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18796        );
18797        let fixture: Value =
18798            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
18799        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
18800            .expect("valid persisted selection history");
18801
18802        assert_persisted_selection_replay(history);
18803    }
18804
18805    #[test]
18806    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
18807        let ctx = workflow_context(Vec::new());
18808        let mut call = Box::pin(keyed_activity_selection(&ctx));
18809        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18810
18811        assert!(matches!(
18812            call.as_mut().poll(&mut task_context),
18813            Poll::Pending
18814        ));
18815        let commands = ctx.take_commands().expect("selection commands");
18816        assert_eq!(commands.len(), 2);
18817        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
18818        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
18819        assert!(commands.iter().all(|command| {
18820            command["parallel_group_id"] == json!("select-calls:1:2")
18821                && command["parallel_group_mode"] == json!("select")
18822        }));
18823    }
18824
18825    #[test]
18826    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
18827        let ctx = workflow_context(Vec::new());
18828        let mut invalid = Box::pin(ctx.select_keyed(vec![(
18829            "",
18830            ParallelOperation::activity("invalid", json!([])),
18831        )]));
18832        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18833        assert!(matches!(
18834            invalid.as_mut().poll(&mut task_context),
18835            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
18836                reason: "selection_key_invalid",
18837                ..
18838            })))
18839        ));
18840
18841        for invalid_key in [json!(""), json!(-1)] {
18842            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
18843            event.payload["selection_member_key"] = invalid_key.clone();
18844            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
18845            assert!(matches!(
18846                WorkflowState::new_with_identity(
18847                    vec![event],
18848                    None,
18849                    None,
18850                    "rust-workers".to_string(),
18851                    DEFAULT_CODEC.to_string(),
18852                    None,
18853                ),
18854                Err(Error::NonDeterministicReplay(_))
18855            ));
18856        }
18857    }
18858
18859    #[test]
18860    fn selection_preserves_valid_named_and_numeric_keys() {
18861        let ctx = workflow_context(Vec::new());
18862        let mut selection = Box::pin(ctx.select_keyed(vec![
18863            (
18864                SelectionKey::Index(0),
18865                ParallelOperation::activity("numeric", json!([])),
18866            ),
18867            (
18868                SelectionKey::Name("named".to_string()),
18869                ParallelOperation::timer(Duration::from_secs(1)),
18870            ),
18871        ]));
18872        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18873
18874        assert!(matches!(
18875            selection.as_mut().poll(&mut task_context),
18876            Poll::Pending
18877        ));
18878        let commands = ctx.take_commands().expect("selection commands");
18879        assert_eq!(commands[0]["selection_member_key"], json!(0));
18880        assert_eq!(commands[1]["selection_member_key"], json!("named"));
18881    }
18882
18883    #[test]
18884    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
18885        let history = canonical_selection_history();
18886        assert_persisted_selection_replay(history.clone());
18887
18888        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18889            .join("tests/fixtures/durable_selection_runtime_history.json");
18890        let output =
18891            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
18892                .args([
18893                    "--exact",
18894                    "tests::selection_fresh_process_entrypoint",
18895                    "--nocapture",
18896                ])
18897                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
18898                .output()
18899                .expect("run fresh selection replay process");
18900
18901        assert!(
18902            output.status.success(),
18903            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
18904            String::from_utf8_lossy(&output.stdout),
18905            String::from_utf8_lossy(&output.stderr),
18906        );
18907    }
18908
18909    #[test]
18910    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
18911        let mut history = canonical_selection_history();
18912        history.retain(|event| event.event_type != "SelectionResolved");
18913        let ctx = workflow_context(history);
18914        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18915        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18916
18917        assert!(matches!(
18918            selection.as_mut().poll(&mut task_context),
18919            Poll::Pending
18920        ));
18921        assert!(ctx.take_commands().expect("commands").is_empty());
18922        assert!(
18923            ctx.matched_recorded_pending()
18924                .expect("selection pending state"),
18925            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
18926        );
18927    }
18928
18929    #[test]
18930    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
18931        for (terminal_event, predicate_satisfied, timeout_seconds) in [
18932            ("ConditionWaitSatisfied", true, None),
18933            ("ConditionWaitTimedOut", false, Some(0)),
18934        ] {
18935            let member = SelectionMemberMetadata {
18936                key: SelectionKey::Name("condition".to_string()),
18937                index: 0,
18938                base_sequence: 1,
18939                size: 1,
18940                kind: "condition".to_string(),
18941            };
18942            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
18943            let mut payload = json!({
18944                "sequence": 1,
18945                "condition_wait_id": "condition-1",
18946                "condition_wait_occurrence_id": "rust:condition-wait:0",
18947                "condition_key": "ready",
18948                "condition_definition_fingerprint": "sha256:ready-v1",
18949                "parallel_group_path": path,
18950            });
18951            payload
18952                .as_object_mut()
18953                .expect("condition history payload")
18954                .extend(
18955                    serde_json::to_value(&path[0])
18956                        .expect("condition selection metadata")
18957                        .as_object()
18958                        .expect("condition selection metadata object")
18959                        .clone(),
18960                );
18961            if let Some(timeout_seconds) = timeout_seconds {
18962                payload["timeout_seconds"] = json!(timeout_seconds);
18963            }
18964            let history = vec![
18965                history_event("ConditionWaitOpened", payload.clone()),
18966                history_event(terminal_event, payload),
18967            ];
18968            let ctx = workflow_context(history);
18969            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18970            if timeout_seconds.is_some() {
18971                options = options.timeout(Duration::ZERO);
18972            }
18973            let mut selection = Box::pin(ctx.select_keyed(vec![(
18974                "condition",
18975                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18976            )]));
18977            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18978
18979            assert!(matches!(
18980                selection.as_mut().poll(&mut task_context),
18981                Poll::Pending
18982            ));
18983            assert!(ctx.take_commands().expect("commands").is_empty());
18984            assert!(
18985                ctx.matched_recorded_pending()
18986                    .expect("condition selection pending state"),
18987                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18988            );
18989        }
18990    }
18991
18992    #[test]
18993    fn selection_immediate_condition_members_open_a_durable_wait() {
18994        for predicate_satisfied in [true, false] {
18995            let ctx = workflow_context(Vec::new());
18996            let mut selection = Box::pin(ctx.select_keyed(vec![(
18997                "condition",
18998                ParallelOperation::condition(
18999                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
19000                    move || Ok(predicate_satisfied),
19001                ),
19002            )]));
19003            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19004
19005            assert!(matches!(
19006                selection.as_mut().poll(&mut task_context),
19007                Poll::Pending
19008            ));
19009            let commands = ctx.take_commands().expect("condition selection command");
19010            assert_eq!(commands.len(), 1);
19011            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
19012            assert_eq!(commands[0]["timeout_seconds"], json!(0));
19013            assert_eq!(
19014                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
19015                json!("select")
19016            );
19017        }
19018    }
19019
19020    #[test]
19021    fn selection_loser_cancellation_is_explicit_and_idempotent() {
19022        let history = vec![
19023            selection_activity_event("ActivityScheduled", 0, "slow", None),
19024            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19025            selection_winner_marker(),
19026        ];
19027        let ctx = workflow_context(history.clone());
19028        let mut call = Box::pin(keyed_activity_selection(&ctx));
19029        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19030        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19031            panic!("winner must replay");
19032        };
19033        let slow = selected
19034            .handle(&SelectionKey::Name("slow".to_string()))
19035            .expect("slow handle")
19036            .clone();
19037        let mut cancel = Box::pin(slow.cancel());
19038        assert!(matches!(
19039            cancel.as_mut().poll(&mut task_context),
19040            Poll::Pending
19041        ));
19042        assert!(matches!(
19043            cancel.as_mut().poll(&mut task_context),
19044            Poll::Pending
19045        ));
19046        let commands = ctx.take_commands().expect("cancel command");
19047        assert_eq!(commands.len(), 1);
19048        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
19049        assert_eq!(commands[0]["member_key"], json!("slow"));
19050
19051        let mut cancelled_history = history;
19052        cancelled_history.push(history_event(
19053            "SelectionOperationCancelled",
19054            json!({
19055                "selection_group_id": "select-calls:1:2",
19056                "member_key": "slow",
19057                "member_index": 0,
19058                "member_base_sequence": 1,
19059                "member_size": 1,
19060                "operation_kind": "activity",
19061                "operation_identity": "activity-slow",
19062                "cancelled_at": "2026-08-27T00:00:00Z",
19063            }),
19064        ));
19065        let replayed = workflow_context(cancelled_history);
19066        let mut call = Box::pin(keyed_activity_selection(&replayed));
19067        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19068            panic!("winner must replay after cancellation");
19069        };
19070        let slow = selected
19071            .handle(&SelectionKey::Name("slow".to_string()))
19072            .expect("slow handle")
19073            .clone();
19074        let mut cancel = Box::pin(slow.cancel());
19075        assert!(matches!(
19076            cancel.as_mut().poll(&mut task_context),
19077            Poll::Ready(Ok(()))
19078        ));
19079        assert!(replayed.take_commands().expect("commands").is_empty());
19080    }
19081
19082    #[test]
19083    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
19084        let base_history = vec![
19085            selection_activity_event("ActivityScheduled", 0, "slow", None),
19086            selection_activity_event("ActivityScheduled", 1, "fast", None),
19087            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19088            selection_winner_marker(),
19089        ];
19090        for (field, corrupt) in [
19091            ("member_key", json!("fast")),
19092            ("member_index", json!(1)),
19093            ("member_base_sequence", json!(3)),
19094            ("member_size", json!(2)),
19095            ("operation_kind", json!("timer")),
19096            ("operation_identity", json!("forged")),
19097        ] {
19098            let mut cancellation = json!({
19099                "selection_group_id": "select-calls:1:2",
19100                "member_key": "slow",
19101                "member_index": 0,
19102                "member_base_sequence": 1,
19103                "member_size": 1,
19104                "operation_kind": "activity",
19105                "operation_identity": "activity-slow",
19106            });
19107            cancellation[field] = corrupt;
19108            let mut history = base_history.clone();
19109            history.push(history_event("SelectionOperationCancelled", cancellation));
19110            let ctx = workflow_context(history);
19111            let mut selection = Box::pin(keyed_activity_selection(&ctx));
19112            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19113
19114            assert!(matches!(
19115                selection.as_mut().poll(&mut task_context),
19116                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19117            ));
19118        }
19119    }
19120
19121    #[test]
19122    fn selection_child_identity_prefers_the_durable_run_id() {
19123        let ctx = workflow_context(vec![history_event(
19124            "ChildWorkflowScheduled",
19125            json!({
19126                "sequence": 1,
19127                "child_workflow_type": "child",
19128                "child_workflow_instance_id": "child-instance",
19129                "child_workflow_run_id": "child-run",
19130            }),
19131        )]);
19132        let state = ctx.state.lock().expect("workflow state");
19133
19134        assert_eq!(
19135            selection_operation_identity(&state, "child", 1, 1),
19136            "child-run"
19137        );
19138    }
19139
19140    #[test]
19141    fn selection_activity_identity_requires_canonical_execution_id() {
19142        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
19143        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
19144        let mut fast_completed =
19145            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
19146        for event in [&mut fast_open, &mut fast_completed] {
19147            event
19148                .payload
19149                .as_object_mut()
19150                .expect("activity payload")
19151                .remove("activity_execution_id");
19152            event.payload["activity_id"] = json!("forged-activity-id");
19153        }
19154        let mut marker = selection_winner_marker();
19155        marker.payload["operation_identity"] = json!("forged-activity-id");
19156        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
19157        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19158        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19159
19160        assert!(matches!(
19161            selection.as_mut().poll(&mut task_context),
19162            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19163        ));
19164    }
19165
19166    #[test]
19167    fn selection_completion_before_cancellation_remains_awaitable() {
19168        let history = vec![
19169            selection_activity_event("ActivityScheduled", 0, "slow", None),
19170            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19171            selection_winner_marker(),
19172            selection_activity_event(
19173                "ActivityCompleted",
19174                0,
19175                "slow",
19176                Some(json!("completed-first")),
19177            ),
19178        ];
19179        let ctx = workflow_context(history);
19180        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19181        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19182        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19183            panic!("winner must replay");
19184        };
19185        let slow = selected
19186            .handle(&SelectionKey::Name("slow".to_string()))
19187            .expect("slow handle")
19188            .clone();
19189        let mut cancel = Box::pin(slow.cancel());
19190        assert!(matches!(
19191            cancel.as_mut().poll(&mut task_context),
19192            Poll::Ready(Ok(()))
19193        ));
19194        let mut await_slow = Box::pin(slow.await_result());
19195        assert!(matches!(
19196            await_slow.as_mut().poll(&mut task_context),
19197            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
19198        ));
19199        let commands = ctx.take_commands().expect("commands");
19200        assert!(commands.is_empty());
19201    }
19202
19203    #[test]
19204    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
19205        let nested_member = SelectionMemberMetadata {
19206            key: SelectionKey::Name("nested".to_string()),
19207            index: 0,
19208            base_sequence: 1,
19209            size: 2,
19210            kind: "group".to_string(),
19211        };
19212        let deadline_member = SelectionMemberMetadata {
19213            key: SelectionKey::Name("deadline".to_string()),
19214            index: 1,
19215            base_sequence: 3,
19216            size: 1,
19217            kind: "timer".to_string(),
19218        };
19219        let nested_paths = [
19220            vec![
19221                selection_group_entry(1, 3, 0, "mixed", &nested_member),
19222                parallel_group_entry(1, 2, 0, "activity"),
19223            ],
19224            vec![
19225                selection_group_entry(1, 3, 1, "mixed", &nested_member),
19226                parallel_group_entry(1, 2, 1, "activity"),
19227            ],
19228        ];
19229        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
19230        let mut timer_fired = parallel_history_event(
19231            "TimerFired",
19232            3,
19233            "timer_id",
19234            "timer-3",
19235            deadline_path.clone(),
19236            None,
19237        );
19238        timer_fired.payload["delay_seconds"] = json!(0);
19239        timer_fired
19240            .raw
19241            .insert("id".to_string(), json!("timer-fired"));
19242        let mut timer_scheduled = parallel_history_event(
19243            "TimerScheduled",
19244            3,
19245            "timer_id",
19246            "timer-3",
19247            deadline_path,
19248            None,
19249        );
19250        timer_scheduled.payload["delay_seconds"] = json!(0);
19251        let history = vec![
19252            parallel_history_event(
19253                "ActivityScheduled",
19254                1,
19255                "activity_type",
19256                "nested-first",
19257                nested_paths[0].clone(),
19258                None,
19259            ),
19260            parallel_history_event(
19261                "ActivityScheduled",
19262                2,
19263                "activity_type",
19264                "nested-second",
19265                nested_paths[1].clone(),
19266                None,
19267            ),
19268            timer_scheduled,
19269            timer_fired,
19270            history_event(
19271                "SelectionResolved",
19272                json!({
19273                    "selection_group_id": "select-calls:1:3",
19274                    "selection_group_base_sequence": 1,
19275                    "selection_group_size": 3,
19276                    "member_key": "deadline",
19277                    "member_index": 1,
19278                    "member_base_sequence": 3,
19279                    "member_size": 1,
19280                    "operation_kind": "timer",
19281                    "operation_identity": "timer-3",
19282                    "outcome": "completed",
19283                    "resolution_event_id": "timer-fired",
19284                    "resolution_event_type": "TimerFired",
19285                }),
19286            ),
19287            parallel_history_event(
19288                "ActivityFailed",
19289                2,
19290                "activity_type",
19291                "nested-second",
19292                nested_paths[1].clone(),
19293                None,
19294            ),
19295        ];
19296        let ctx = workflow_context(history);
19297        let mut selection = Box::pin(ctx.select_keyed(vec![
19298            (
19299                "nested",
19300                ParallelOperation::group(vec![
19301                    ParallelOperation::activity("nested-first", json!([])),
19302                    ParallelOperation::activity("nested-second", json!([])),
19303                ]),
19304            ),
19305            ("deadline", ParallelOperation::timer(Duration::ZERO)),
19306        ]));
19307        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19308        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19309            panic!("deadline winner must replay");
19310        };
19311        let nested = selected
19312            .handle(&SelectionKey::Name("nested".to_string()))
19313            .expect("nested handle")
19314            .clone();
19315        let mut cancel = Box::pin(nested.cancel());
19316        assert!(matches!(
19317            cancel.as_mut().poll(&mut task_context),
19318            Poll::Ready(Ok(()))
19319        ));
19320        let mut await_nested = Box::pin(nested.await_result());
19321
19322        assert!(matches!(
19323            await_nested.as_mut().poll(&mut task_context),
19324            Poll::Ready(Err(Error::ActivityFailed(_)))
19325        ));
19326        assert!(ctx.take_commands().expect("commands").is_empty());
19327    }
19328
19329    #[test]
19330    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
19331        let ctx = workflow_context(Vec::new());
19332        let mut call = Box::pin(ctx.select(vec![
19333            ParallelOperation::child_workflow(
19334                "child",
19335                ChildWorkflowOptions::new("children"),
19336                json!([]),
19337            ),
19338            ParallelOperation::timer(Duration::from_secs(30)),
19339            ParallelOperation::signal("approval"),
19340            ParallelOperation::condition(
19341                ConditionWaitOptions::new("ready", "sha256:ready"),
19342                || Ok(false),
19343            ),
19344            ParallelOperation::group(vec![
19345                ParallelOperation::activity("nested-one", json!([])),
19346                ParallelOperation::activity("nested-two", json!([])),
19347            ]),
19348        ]));
19349        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19350        assert!(matches!(
19351            call.as_mut().poll(&mut task_context),
19352            Poll::Pending
19353        ));
19354        let commands = ctx.take_commands().expect("selection commands");
19355        assert_eq!(
19356            commands
19357                .iter()
19358                .map(|command| command["type"].as_str().unwrap_or_default())
19359                .collect::<Vec<_>>(),
19360            [
19361                "start_child_workflow",
19362                "start_timer",
19363                "open_signal_wait",
19364                "open_condition_wait",
19365                "schedule_activity",
19366                "schedule_activity",
19367            ]
19368        );
19369        assert!(commands.iter().all(|command| {
19370            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
19371        }));
19372        assert_eq!(
19373            commands[4]["parallel_group_path"].as_array().map(Vec::len),
19374            Some(2)
19375        );
19376        assert_eq!(
19377            commands[4]["parallel_group_path"][0]["selection_member_kind"],
19378            json!("group")
19379        );
19380        assert_eq!(
19381            commands[5]["parallel_group_path"][0]["selection_member_kind"],
19382            json!("group")
19383        );
19384
19385        let one_leaf_ctx = workflow_context(Vec::new());
19386        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
19387            ParallelOperation::activity("nested-only", json!([])),
19388        ])]));
19389        assert!(matches!(
19390            one_leaf.as_mut().poll(&mut task_context),
19391            Poll::Pending
19392        ));
19393        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
19394        assert_eq!(one_leaf_commands.len(), 1);
19395        assert_eq!(
19396            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
19397            json!("group")
19398        );
19399        assert_eq!(
19400            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
19401            json!(1)
19402        );
19403    }
19404
19405    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
19406        let mut saga = ctx.saga();
19407        let outcome = async {
19408            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19409            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19410            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
19411            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
19412            ctx.activity("trip.charge", json!([])).await?;
19413            Ok(json!({"status": "booked"}))
19414        }
19415        .await;
19416        saga.finish(outcome).await
19417    }
19418
19419    fn saga_activity(
19420        event_type: &str,
19421        sequence: u64,
19422        activity_type: &str,
19423        result: Option<Value>,
19424    ) -> HistoryEvent {
19425        let mut payload = json!({
19426            "sequence": sequence,
19427            "activity_type": activity_type,
19428            "message": format!("{activity_type} failed"),
19429            "exception_type": "PlannedFailure",
19430            "non_retryable": true,
19431        });
19432        if let Some(result) = result {
19433            payload["result"] = fixture_envelope(result);
19434        }
19435        history_event(event_type, payload)
19436    }
19437
19438    #[test]
19439    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
19440        let completed_hotel_compensation = saga_activity(
19441            "ActivityCompleted",
19442            4,
19443            "trip.cancel-hotel",
19444            Some(Value::Null),
19445        );
19446        let history = vec![
19447            saga_activity(
19448                "ActivityCompleted",
19449                1,
19450                "trip.reserve-flight",
19451                Some(json!("flight-1")),
19452            ),
19453            saga_activity(
19454                "ActivityCompleted",
19455                2,
19456                "trip.reserve-hotel",
19457                Some(json!("hotel-1")),
19458            ),
19459            saga_activity("ActivityFailed", 3, "trip.charge", None),
19460            completed_hotel_compensation.clone(),
19461            completed_hotel_compensation,
19462        ];
19463
19464        for _restart in 0..2 {
19465            let ctx = workflow_context(history.clone());
19466            let mut future = Box::pin(trip_saga(ctx.clone()));
19467            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19468            assert!(matches!(
19469                future.as_mut().poll(&mut task_context),
19470                Poll::Pending
19471            ));
19472            let commands = ctx.take_commands().expect("compensation command");
19473            assert_eq!(commands.len(), 1);
19474            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19475        }
19476    }
19477
19478    #[test]
19479    fn saga_compensation_failure_preserves_both_typed_failures() {
19480        let history = vec![
19481            saga_activity(
19482                "ActivityCompleted",
19483                1,
19484                "trip.reserve-flight",
19485                Some(json!("flight-1")),
19486            ),
19487            saga_activity(
19488                "ActivityCompleted",
19489                2,
19490                "trip.reserve-hotel",
19491                Some(json!("hotel-1")),
19492            ),
19493            saga_activity("ActivityFailed", 3, "trip.charge", None),
19494            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
19495        ];
19496        let ctx = workflow_context(history);
19497        let mut future = Box::pin(trip_saga(ctx));
19498        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19499        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
19500            future.as_mut().poll(&mut task_context)
19501        else {
19502            panic!("compensation failure must remain structured");
19503        };
19504        assert!(matches!(
19505            *failure.initiating_failure,
19506            Error::ActivityFailed(_)
19507        ));
19508        assert!(matches!(
19509            *failure.compensation_failure,
19510            Error::ActivityFailed(_)
19511        ));
19512        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
19513        assert_eq!(failure.compensation_registration_order, 2);
19514    }
19515
19516    #[test]
19517    fn saga_compensates_cooperative_cancellation() {
19518        let ctx = workflow_context(vec![saga_activity(
19519            "ActivityCompleted",
19520            1,
19521            "trip.reserve-flight",
19522            Some(json!("flight-1")),
19523        )]);
19524        ctx.state.lock().expect("state").cancel_requested = true;
19525        let run = {
19526            let ctx = ctx.clone();
19527            async move {
19528                let mut saga = ctx.saga();
19529                let outcome = async {
19530                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19531                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19532                    ctx.throw_if_cancellation_requested()?;
19533                    Ok(json!("unexpected"))
19534                }
19535                .await;
19536                saga.finish(outcome).await
19537            }
19538        };
19539        let mut future = Box::pin(run);
19540        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19541        assert!(matches!(
19542            future.as_mut().poll(&mut task_context),
19543            Poll::Pending
19544        ));
19545        let commands = ctx.take_commands().expect("cancellation compensation");
19546        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19547    }
19548
19549    fn workflow_task(
19550        workflow_type: &str,
19551        history_events: Vec<HistoryEvent>,
19552        payload_codec: &str,
19553    ) -> WorkflowTask {
19554        WorkflowTask {
19555            task_id: format!("wft-{workflow_type}"),
19556            workflow_command_id: None,
19557            workflow_id: Some(format!("wf-{workflow_type}")),
19558            run_id: Some(format!("run-{workflow_type}")),
19559            workflow_type: workflow_type.to_string(),
19560            cancel_requested: false,
19561            payload_codec: payload_codec.to_string(),
19562            arguments: Some(
19563                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
19564            ),
19565            total_history_events: Some(history_events.len() as u64),
19566            history_size_bytes: None,
19567            continue_as_new_recommended: None,
19568            history_budget_pressure: None,
19569            history_events,
19570            next_history_page_token: None,
19571            workflow_task_attempt: 1,
19572            workflow_signal_id: None,
19573            signal_name: None,
19574            signal_arguments: None,
19575            workflow_update_id: None,
19576            update_name: None,
19577            lease_owner: Some("rust-worker".to_string()),
19578        }
19579    }
19580
19581    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19582    struct SideEffectProbe {
19583        request_id: String,
19584        attempt: u32,
19585    }
19586
19587    #[test]
19588    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
19589        let calls = AtomicUsize::new(0);
19590        let ctx = workflow_context(Vec::new());
19591        let value = ctx
19592            .side_effect(|| {
19593                calls.fetch_add(1, Ordering::SeqCst);
19594                SideEffectProbe {
19595                    request_id: "request-42".to_string(),
19596                    attempt: 3,
19597                }
19598            })
19599            .expect("first side effect");
19600        assert_eq!(value.attempt, 3);
19601        assert_eq!(calls.load(Ordering::SeqCst), 1);
19602        let commands = ctx.take_commands().expect("commands");
19603        assert_eq!(commands.len(), 1);
19604        assert_eq!(commands[0]["type"], "record_side_effect");
19605        assert_eq!(
19606            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19607            serde_json::to_value(&value).expect("value")
19608        );
19609
19610        let replay = workflow_context(vec![history_event(
19611            "SideEffectRecorded",
19612            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19613        )]);
19614        let replayed: SideEffectProbe = replay
19615            .side_effect(|| {
19616                calls.fetch_add(1, Ordering::SeqCst);
19617                panic!("committed side-effect callbacks must not run during replay")
19618            })
19619            .expect("replayed side effect");
19620        assert_eq!(replayed, value);
19621        assert_eq!(calls.load(Ordering::SeqCst), 1);
19622        assert!(replay.take_commands().expect("commands").is_empty());
19623        replay.ensure_history_consumed().expect("history consumed");
19624    }
19625
19626    #[test]
19627    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
19628        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19629        let value = ctx
19630            .side_effect(|| SideEffectProbe {
19631                request_id: "avro-request".to_string(),
19632                attempt: 1,
19633            })
19634            .expect("Avro side effect");
19635        let uuid = ctx.uuid_v4().expect("deterministic UUID");
19636        let commands = ctx.take_commands().expect("commands");
19637        assert_eq!(commands.len(), 2);
19638        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
19639        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
19640        assert_eq!(
19641            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19642            serde_json::to_value(&value).expect("value")
19643        );
19644
19645        let replay = workflow_context_with_codec(
19646            vec![
19647                history_event(
19648                    "SideEffectRecorded",
19649                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19650                ),
19651                history_event(
19652                    "SideEffectRecorded",
19653                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
19654                ),
19655            ],
19656            DEFAULT_CODEC,
19657        );
19658        let replayed: SideEffectProbe = replay
19659            .side_effect(|| panic!("Avro callback must not run"))
19660            .expect("replayed Avro value");
19661        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
19662        assert_eq!(replayed, value);
19663        assert_eq!(replayed_uuid, uuid);
19664        assert!(replay.take_commands().expect("commands").is_empty());
19665    }
19666
19667    #[test]
19668    fn typed_side_effect_replay_preserves_bytes_and_maps() {
19669        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19670        let value = ctx
19671            .side_effect_avro_value(typed_fidelity_probe)
19672            .expect("typed side effect");
19673        let commands = ctx.take_commands().expect("side-effect command");
19674        assert_eq!(
19675            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19676                .expect("recorded side effect"),
19677            value
19678        );
19679
19680        let replay = workflow_context_with_codec(
19681            vec![history_event(
19682                "SideEffectRecorded",
19683                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19684            )],
19685            DEFAULT_CODEC,
19686        );
19687        assert_eq!(
19688            replay
19689                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
19690                .expect("replayed typed side effect"),
19691            value
19692        );
19693    }
19694
19695    #[test]
19696    fn ordered_side_effects_share_the_durable_command_stream() {
19697        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
19698        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
19699        let ctx = workflow_context(vec![
19700            history_event(
19701                "SideEffectRecorded",
19702                json!({"sequence": 1, "result": first}),
19703            ),
19704            history_event(
19705                "SideEffectRecorded",
19706                json!({"sequence": 2, "result": second}),
19707            ),
19708        ]);
19709        let first: String = ctx
19710            .side_effect(|| panic!("first callback must not run"))
19711            .expect("first replay");
19712        let second: i32 = ctx
19713            .side_effect(|| panic!("second callback must not run"))
19714            .expect("second replay");
19715        assert_eq!(first, "first");
19716        assert_eq!(second, 29);
19717        ctx.ensure_history_consumed().expect("ordered history");
19718
19719        let reordered = workflow_context(vec![history_event(
19720            "VersionMarkerRecorded",
19721            json!({
19722                "sequence": 1,
19723                "change_id": "before-side-effect",
19724                "version": 1,
19725                "min_supported": 1,
19726                "max_supported": 1,
19727            }),
19728        )]);
19729        let error = reordered
19730            .side_effect(|| "new".to_string())
19731            .expect_err("command reordering must fail");
19732        assert!(matches!(
19733            error,
19734            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19735                if reason == "recorded_command_mismatch"
19736        ));
19737    }
19738
19739    #[test]
19740    fn legacy_patch_preserves_pending_and_completed_activity_history() {
19741        for completed in [false, true] {
19742            let mut history = vec![history_event(
19743                "ActivityScheduled",
19744                json!({"sequence": 1, "activity_type": "old"}),
19745            )];
19746            if completed {
19747                history.push(history_event(
19748                    "ActivityCompleted",
19749                    json!({
19750                        "sequence": 1,
19751                        "activity_type": "old",
19752                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
19753                    }),
19754                ));
19755            }
19756            for _cold_replay in 0..2 {
19757                let ctx = workflow_context(history.clone());
19758                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
19759                assert!(!ctx.patched("added-step").expect("same frozen decision"));
19760                ctx.deprecate_patch("added-step")
19761                    .expect("retained boundary");
19762                let mut activity = Box::pin(ctx.activity("old", json!([])));
19763                let mut context = TaskContext::from_waker(noop_waker_ref());
19764                match activity.as_mut().poll(&mut context) {
19765                    Poll::Ready(result) => {
19766                        assert!(completed);
19767                        assert_eq!(result.expect("recorded result"), json!(41));
19768                        ctx.ensure_history_consumed().expect("old command retained");
19769                    }
19770                    Poll::Pending => assert!(!completed),
19771                }
19772                assert!(ctx.take_commands().expect("commands").is_empty());
19773            }
19774        }
19775    }
19776
19777    #[test]
19778    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
19779        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
19780        assert!(!ctx.patched("added-step").expect("legacy completed run"));
19781        ctx.deprecate_patch("added-step")
19782            .expect("same legacy decision");
19783        assert!(ctx.take_commands().expect("commands").is_empty());
19784        ctx.ensure_history_consumed().expect("completed history");
19785    }
19786
19787    #[test]
19788    fn legacy_patch_rejects_a_range_without_the_original_branch() {
19789        let ctx = workflow_context(vec![history_event(
19790            "ActivityScheduled",
19791            json!({"sequence": 1, "activity_type": "old"}),
19792        )]);
19793        let error = ctx
19794            .get_version("added-step", 0, 1)
19795            .expect_err("legacy is unsupported");
19796        assert!(matches!(
19797            error,
19798            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19799                if reason == "version_marker_incompatible_range"
19800        ));
19801        assert!(!ctx
19802            .patched("supported-step")
19803            .expect("failed check did not consume history"));
19804        assert!(ctx.take_commands().expect("commands").is_empty());
19805    }
19806
19807    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
19808        let mut event = history_event(
19809            "VersionMarkerRecorded",
19810            json!({
19811                "sequence": sequence,
19812                "change_id": "retained-patch",
19813                "version": version,
19814                "min_supported": -1,
19815                "max_supported": 1,
19816            }),
19817        );
19818        event.raw.insert("timestamp".into(), json!(time));
19819        event
19820    }
19821
19822    #[test]
19823    fn retained_patch_markers_preserve_each_original_boundary() {
19824        for completed in [false, true] {
19825            let mut history = vec![
19826                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19827                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19828                history_event(
19829                    "ActivityScheduled",
19830                    json!({"sequence": 3, "activity_type": "old"}),
19831                ),
19832            ];
19833            if completed {
19834                history.push(history_event(
19835                    "ActivityCompleted",
19836                    json!({
19837                        "sequence": 3,
19838                        "activity_type": "old",
19839                        "result": fixture_envelope(json!(41)),
19840                    }),
19841                ));
19842            }
19843            for _cold_replay in 0..2 {
19844                let ctx = workflow_context(history.clone());
19845                assert!(ctx.patched("retained-patch").unwrap());
19846                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19847                assert!(ctx.patched("retained-patch").unwrap());
19848                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19849                ctx.deprecate_patch("retained-patch").unwrap();
19850                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19851                let mut activity = Box::pin(ctx.activity("old", json!([])));
19852                let mut context = TaskContext::from_waker(noop_waker_ref());
19853                match activity.as_mut().poll(&mut context) {
19854                    Poll::Ready(result) => {
19855                        assert!(completed);
19856                        assert_eq!(result.unwrap(), json!(41));
19857                        ctx.ensure_history_consumed().unwrap();
19858                    }
19859                    Poll::Pending => assert!(!completed),
19860                }
19861                assert!(ctx.take_commands().unwrap().is_empty());
19862                let state = ctx.state.lock().unwrap();
19863                for (actual, original) in state.history_events.iter().zip(&history) {
19864                    assert_eq!(actual.payload, original.payload);
19865                    assert_eq!(actual.raw, original.raw);
19866                }
19867            }
19868        }
19869    }
19870
19871    #[test]
19872    fn retained_patch_aliases_do_not_skip_intervening_operations() {
19873        let ctx = workflow_context(vec![
19874            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19875            history_event(
19876                "SideEffectRecorded",
19877                json!({
19878                    "sequence": 2, "result": fixture_envelope(json!("between")),
19879                }),
19880            ),
19881            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
19882            history_event(
19883                "VersionMarkerRecorded",
19884                json!({
19885                    "sequence": 4, "change_id": "other-patch", "version": 1,
19886                    "min_supported": -1, "max_supported": 1,
19887                }),
19888            ),
19889        ]);
19890        assert!(ctx.patched("retained-patch").unwrap());
19891        assert!(ctx.patched("retained-patch").unwrap());
19892        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19893        assert_eq!(
19894            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19895            "between"
19896        );
19897        ctx.deprecate_patch("retained-patch").unwrap();
19898        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19899        ctx.deprecate_patch("retained-patch").unwrap();
19900        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19901        assert!(ctx.patched("other-patch").unwrap());
19902        ctx.ensure_history_consumed().unwrap();
19903        assert!(ctx.take_commands().unwrap().is_empty());
19904    }
19905
19906    #[test]
19907    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
19908        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19909        alias.payload["max_supported"] = json!(3);
19910        let ctx = workflow_context(vec![
19911            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19912            alias,
19913        ]);
19914        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
19915        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
19916        assert!(matches!(error,
19917            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19918                if reason == "version_marker_incompatible_range"));
19919        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19920        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
19921        ctx.ensure_history_consumed().unwrap();
19922        assert!(ctx.take_commands().unwrap().is_empty());
19923    }
19924
19925    #[test]
19926    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
19927        let ctx = workflow_context(Vec::new());
19928        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
19929        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
19930        assert!(ctx.patched("new-search").expect("patch"));
19931        ctx.deprecate_patch("new-search").expect("deprecate patch");
19932        let commands = ctx.take_commands().expect("commands");
19933        assert_eq!(commands.len(), 2);
19934        assert_eq!(commands[0]["type"], "record_version_marker");
19935        assert_eq!(commands[0]["version"], 2);
19936        assert_eq!(commands[1]["change_id"], "new-search");
19937
19938        let replay = workflow_context(vec![history_event(
19939            "VersionMarkerRecorded",
19940            json!({
19941                "sequence": 1,
19942                "change_id": "checkout-v2",
19943                "version": 2,
19944                "min_supported": 1,
19945                "max_supported": 2,
19946            }),
19947        )]);
19948        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
19949        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
19950        assert!(replay.take_commands().expect("commands").is_empty());
19951        replay.ensure_history_consumed().expect("history consumed");
19952    }
19953
19954    #[test]
19955    fn version_markers_reject_incompatible_or_malformed_history() {
19956        let incompatible = workflow_context(vec![history_event(
19957            "VersionMarkerRecorded",
19958            json!({
19959                "sequence": 1,
19960                "change_id": "checkout-v2",
19961                "version": 1,
19962                "min_supported": 1,
19963                "max_supported": 2,
19964            }),
19965        )]);
19966        let error = incompatible
19967            .get_version("checkout-v2", 2, 3)
19968            .expect_err("old version is unsupported");
19969        assert!(matches!(
19970            error,
19971            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19972                if reason == "version_marker_incompatible_range"
19973        ));
19974
19975        for (history, reason) in [
19976            (
19977                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
19978                "side_effect_result_missing",
19979            ),
19980            (
19981                vec![history_event(
19982                    "SideEffectRecorded",
19983                    json!({
19984                        "sequence": 1,
19985                        "result": {"codec": "avro", "blob": "not-base64"},
19986                    }),
19987                )],
19988                "side_effect_payload_incompatible",
19989            ),
19990            (
19991                vec![history_event(
19992                    "SideEffectRecorded",
19993                    json!({"sequence": 1, "result": {"unwrapped": true}}),
19994                )],
19995                "side_effect_payload_malformed",
19996            ),
19997            (
19998                vec![history_event(
19999                    "VersionMarkerRecorded",
20000                    json!({
20001                        "sequence": 1,
20002                        "change_id": "change",
20003                        "version": 1,
20004                        "min_supported": 2,
20005                        "max_supported": 1,
20006                    }),
20007                )],
20008                "version_marker_history_range_invalid",
20009            ),
20010        ] {
20011            let error = WorkflowState::new(
20012                history,
20013                "rust-workers".to_string(),
20014                DEFAULT_CODEC.to_string(),
20015                None,
20016            )
20017            .expect_err("malformed history must fail");
20018            assert!(matches!(
20019                error,
20020                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
20021                    if actual == reason
20022            ));
20023        }
20024    }
20025
20026    #[test]
20027    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
20028        let history = vec![history_event(
20029            "SearchAttributesUpserted",
20030            json!({
20031                "sequence": 1,
20032                "attributes": {"customer_tier": "gold"},
20033                "attribute_types": {"customer_tier": "keyword"},
20034                "merged": {"customer_tier": "gold"}
20035            }),
20036        )];
20037
20038        let matching = workflow_context(history.clone());
20039        matching
20040            .upsert_search_attributes(
20041                SearchAttributeUpdate::new()
20042                    .keyword("customer_tier", "gold")
20043                    .expect("keyword update"),
20044            )
20045            .expect("matching typed update must replay");
20046        matching
20047            .ensure_history_consumed()
20048            .expect("history consumed");
20049
20050        let changed_type = workflow_context(history.clone());
20051        let error = changed_type
20052            .upsert_search_attributes(
20053                SearchAttributeUpdate::new()
20054                    .string("customer_tier", "gold")
20055                    .expect("string update"),
20056            )
20057            .expect_err("same JSON value with a different declaration must be nondeterministic");
20058        let Error::NonDeterministicReplay(failure) = error else {
20059            panic!("typed identity drift must be a replay failure");
20060        };
20061        assert_eq!(failure.reason, "search_attribute_type_mismatch");
20062        assert_eq!(failure.sequence, Some(1));
20063
20064        let changed_value = workflow_context(history);
20065        let error = changed_value
20066            .upsert_search_attributes(
20067                SearchAttributeUpdate::new()
20068                    .keyword("customer_tier", "platinum")
20069                    .expect("keyword update"),
20070            )
20071            .expect_err("changed values must be nondeterministic");
20072        let Error::NonDeterministicReplay(failure) = error else {
20073            panic!("value drift must be a replay failure");
20074        };
20075        assert_eq!(failure.reason, "search_attribute_value_mismatch");
20076    }
20077
20078    #[test]
20079    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
20080        let history = vec![history_event(
20081            "SearchAttributesUpserted",
20082            json!({
20083                "sequence": 1,
20084                "attributes": {"customer_tier": "gold"},
20085                "merged": {"customer_tier": "gold"}
20086            }),
20087        )];
20088
20089        for update in [
20090            SearchAttributeUpdate::new()
20091                .keyword("customer_tier", "gold")
20092                .expect("keyword update"),
20093            SearchAttributeUpdate::new()
20094                .string("customer_tier", "gold")
20095                .expect("string update"),
20096        ] {
20097            let restarted = workflow_context(history.clone());
20098            restarted
20099                .upsert_search_attributes(update)
20100                .expect("legacy history constrains values but has unknown type identity");
20101            restarted
20102                .ensure_history_consumed()
20103                .expect("history consumed");
20104        }
20105    }
20106
20107    #[test]
20108    fn search_attribute_command_emits_canonical_types() {
20109        let ctx = workflow_context(Vec::new());
20110        ctx.upsert_search_attributes(
20111            SearchAttributeUpdate::new()
20112                .keyword("customer_tier", "gold")
20113                .expect("keyword update")
20114                .int("attempts", 3)
20115                .expect("int update")
20116                .delete("obsolete")
20117                .expect("delete update"),
20118        )
20119        .expect("valid search attributes");
20120
20121        assert_eq!(
20122            ctx.take_commands().expect("commands"),
20123            vec![json!({
20124                "type": "upsert_search_attributes",
20125                "attributes": {
20126                    "attempts": 3,
20127                    "customer_tier": "gold",
20128                    "obsolete": null
20129                },
20130                "attribute_types": {
20131                    "attempts": "int",
20132                    "customer_tier": "keyword"
20133                }
20134            })]
20135        );
20136    }
20137
20138    #[test]
20139    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
20140        let duplicate_side_effect = WorkflowState::new(
20141            vec![
20142                history_event(
20143                    "SideEffectRecorded",
20144                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
20145                ),
20146                history_event(
20147                    "SideEffectRecorded",
20148                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
20149                ),
20150            ],
20151            "rust-workers".to_string(),
20152            DEFAULT_CODEC.to_string(),
20153            None,
20154        )
20155        .expect_err("duplicate side effect");
20156        assert!(matches!(
20157            duplicate_side_effect,
20158            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20159                if reason == "duplicate_side_effect_record"
20160        ));
20161
20162        let marker = |sequence, version| {
20163            history_event(
20164                "VersionMarkerRecorded",
20165                json!({
20166                    "sequence": sequence,
20167                    "change_id": "same-change",
20168                    "version": version,
20169                    "min_supported": -1,
20170                    "max_supported": 1,
20171                }),
20172            )
20173        };
20174        let duplicate_marker = WorkflowState::new(
20175            vec![marker(1, 1), marker(3, -1)],
20176            "rust-workers".to_string(),
20177            DEFAULT_CODEC.to_string(),
20178            None,
20179        )
20180        .expect_err("conflicting marker");
20181        assert!(matches!(
20182            duplicate_marker,
20183            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20184                if reason == "version_marker_conflict"
20185        ));
20186    }
20187
20188    #[test]
20189    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
20190        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
20191        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20192        invalid_alias.payload["max_supported"] = json!(0);
20193        for (history, expected_reason) in [
20194            (
20195                vec![marker.clone(), marker.clone()],
20196                "duplicate_version_marker_record",
20197            ),
20198            (
20199                vec![marker, invalid_alias],
20200                "version_marker_history_range_invalid",
20201            ),
20202        ] {
20203            let error =
20204                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
20205                    .expect_err("invalid historical alias");
20206            assert!(matches!(error,
20207                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
20208                    if reason == expected_reason));
20209        }
20210    }
20211
20212    #[test]
20213    fn retained_patch_aliases_require_the_original_call_boundary() {
20214        let ctx = workflow_context(vec![
20215            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20216            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20217        ]);
20218        assert!(ctx.patched("retained-patch").unwrap());
20219        assert!(ctx.ensure_history_consumed().is_err());
20220        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20221        ctx.deprecate_patch("retained-patch").unwrap();
20222        ctx.ensure_history_consumed().unwrap();
20223        assert!(ctx.take_commands().unwrap().is_empty());
20224    }
20225
20226    #[test]
20227    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
20228        let ctx = workflow_context(vec![
20229            history_event(
20230                "SideEffectRecorded",
20231                json!({
20232                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
20233                }),
20234            ),
20235            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20236        ]);
20237        assert!(!ctx.patched("retained-patch").unwrap());
20238        assert_eq!(
20239            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20240            "old-operation"
20241        );
20242        let error = ctx.patched("retained-patch").unwrap_err();
20243        assert!(matches!(error,
20244            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20245                if reason == "version_marker_conflict"));
20246        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20247        assert!(ctx.take_commands().unwrap().is_empty());
20248    }
20249
20250    #[test]
20251    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
20252        let mut state = WorkflowState::new(
20253            Vec::new(),
20254            "rust-workers".to_string(),
20255            DEFAULT_CODEC.to_string(),
20256            None,
20257        )
20258        .expect("workflow state");
20259        state.workflow_command_identity = "command-7".to_string();
20260        let context = WorkflowContext {
20261            state: Arc::new(Mutex::new(state)),
20262            cancellation_scope_id: "root".into(),
20263        };
20264        let item =
20265            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
20266
20267        context
20268            .append_workflow_stream("output", &[item], Some(10))
20269            .expect("append command");
20270        context
20271            .error_workflow_stream("output", "producer failed", None)
20272            .expect("error command");
20273        let commands = context.take_commands().expect("commands");
20274
20275        assert_eq!(commands[0]["type"], "record_side_effect");
20276        assert_eq!(
20277            commands[0]["workflow_stream"]["command_identity"],
20278            "command-7"
20279        );
20280        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
20281        assert_eq!(
20282            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20283            "dw-stream:command-7:0:0"
20284        );
20285        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
20286
20287        let recorded = history_event(
20288            "SideEffectRecorded",
20289            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
20290        );
20291        let mut replay_state = WorkflowState::new(
20292            vec![recorded],
20293            "rust-workers".to_string(),
20294            DEFAULT_CODEC.to_string(),
20295            None,
20296        )
20297        .expect("replay state");
20298        replay_state.workflow_command_identity = "command-7".to_string();
20299        let replay_context = WorkflowContext {
20300            state: Arc::new(Mutex::new(replay_state)),
20301            cancellation_scope_id: "root".into(),
20302        };
20303        replay_context
20304            .append_workflow_stream(
20305                "output",
20306                &[WorkflowStreamAppendItem::from_reference(
20307                    "s3://bucket/item.avro",
20308                )],
20309                Some(10),
20310            )
20311            .expect("replayed append");
20312        assert!(replay_context
20313            .take_commands()
20314            .expect("replayed commands")
20315            .is_empty());
20316    }
20317
20318    #[test]
20319    fn workflow_stream_authoring_requires_server_durable_command_identity() {
20320        let context = workflow_context(Vec::new());
20321        let error = context
20322            .append_workflow_stream(
20323                "output",
20324                &[WorkflowStreamAppendItem::from_reference(
20325                    "s3://bucket/item.avro",
20326                )],
20327                None,
20328            )
20329            .expect_err("stream append without durable command identity must fail closed");
20330
20331        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
20332        assert!(context.take_commands().expect("commands").is_empty());
20333    }
20334
20335    #[test]
20336    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
20337        let client = Client::builder("http://localhost:8080").build().unwrap();
20338        let mut worker = Worker::new(client, "rust-workers");
20339        worker.register_workflow("streams.worker", |ctx, _| async move {
20340            ctx.append_workflow_stream(
20341                "output",
20342                &[WorkflowStreamAppendItem::new(json!("hello"))?],
20343                None,
20344            )?;
20345            ctx.close_workflow_stream("output", None)?;
20346            Ok(json!("done"))
20347        });
20348        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
20349            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20350            task.workflow_command_id = command_id.clone();
20351            let expected_identity = command_id
20352                .as_deref()
20353                .filter(|id| !id.is_empty())
20354                .unwrap_or(&task.task_id)
20355                .to_string();
20356            let commands = worker
20357                .execute_workflow_task(task)
20358                .expect("ordinary worker stream output");
20359            assert_eq!(commands.len(), 3);
20360            assert_eq!(
20361                commands[0]["workflow_stream"]["command_identity"],
20362                expected_identity
20363            );
20364            assert_eq!(
20365                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20366                format!("dw-stream:{expected_identity}:0:0")
20367            );
20368            assert_eq!(
20369                commands[1]["workflow_stream"]["command_identity"],
20370                expected_identity
20371            );
20372            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
20373            let history = commands[..2]
20374                .iter()
20375                .enumerate()
20376                .map(|(index, command)| {
20377                    history_event(
20378                        "SideEffectRecorded",
20379                        json!({"sequence":index + 1,"result":command["result"]}),
20380                    )
20381                })
20382                .collect();
20383            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
20384            replay.task_id = "replacement-task".to_string();
20385            let replayed = worker
20386                .execute_workflow_task(replay)
20387                .expect("replacement worker consumes recorded stream effects");
20388            assert_eq!(replayed.len(), 1);
20389            assert_eq!(replayed[0]["type"], "complete_workflow");
20390        }
20391        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20392        missing.task_id.clear();
20393        assert!(matches!(
20394            worker.execute_workflow_task(missing),
20395            Err(Error::MissingWorkflowCommandIdentity)
20396        ));
20397    }
20398
20399    #[test]
20400    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
20401        fn worker(calls: Arc<AtomicUsize>) -> Worker {
20402            let client = Client::new("http://127.0.0.1:8080").expect("client");
20403            let mut worker = Worker::new(client, "rust-workers");
20404            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
20405                let calls = Arc::clone(&calls);
20406                async move {
20407                    let captured = ctx.side_effect(|| {
20408                        calls.fetch_add(1, Ordering::SeqCst);
20409                        "captured-once".to_string()
20410                    })?;
20411                    let version = ctx.get_version("cold-restart", 1, 2)?;
20412                    Ok(json!({"captured": captured, "version": version}))
20413                }
20414            });
20415            worker
20416        }
20417
20418        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
20419            WorkflowTask {
20420                task_id: "wft-side-effect-version".to_string(),
20421                workflow_command_id: None,
20422                workflow_id: Some("wf-side-effect-version".to_string()),
20423                run_id: Some("run-side-effect-version".to_string()),
20424                workflow_type: "rust.side-effect-version".to_string(),
20425                cancel_requested: false,
20426                payload_codec: DEFAULT_CODEC.to_string(),
20427                arguments: Some(
20428                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
20429                ),
20430                history_events,
20431                total_history_events: None,
20432                history_size_bytes: None,
20433                continue_as_new_recommended: None,
20434                history_budget_pressure: None,
20435                next_history_page_token: None,
20436                workflow_task_attempt: 1,
20437                workflow_signal_id: None,
20438                signal_name: None,
20439                signal_arguments: None,
20440                workflow_update_id: None,
20441                update_name: None,
20442                lease_owner: Some("rust-worker".to_string()),
20443            }
20444        }
20445
20446        let calls = Arc::new(AtomicUsize::new(0));
20447        let initial = worker(Arc::clone(&calls))
20448            .execute_workflow_task(task(Vec::new()))
20449            .expect("initial execution");
20450        assert_eq!(
20451            initial
20452                .iter()
20453                .map(|command| &command["type"])
20454                .collect::<Vec<_>>(),
20455            vec![
20456                "record_side_effect",
20457                "record_version_marker",
20458                "complete_workflow"
20459            ]
20460        );
20461        assert_eq!(calls.load(Ordering::SeqCst), 1);
20462
20463        let restarted = worker(Arc::clone(&calls));
20464        let replayed = restarted
20465            .execute_workflow_task(task(vec![
20466                history_event(
20467                    "SideEffectRecorded",
20468                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
20469                ),
20470                history_event(
20471                    "VersionMarkerRecorded",
20472                    json!({
20473                        "sequence": 2,
20474                        "change_id": "cold-restart",
20475                        "version": 2,
20476                        "min_supported": 1,
20477                        "max_supported": 2,
20478                    }),
20479                ),
20480            ]))
20481            .expect("cold replay");
20482        assert_eq!(replayed.len(), 1);
20483        assert_eq!(replayed[0]["type"], "complete_workflow");
20484        assert_eq!(calls.load(Ordering::SeqCst), 1);
20485    }
20486
20487    #[test]
20488    fn side_effect_replay_rejects_changed_rust_value_type() {
20489        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
20490        let ctx = workflow_context(vec![history_event(
20491            "SideEffectRecorded",
20492            json!({"sequence": 1, "result": result}),
20493        )]);
20494        let error = ctx
20495            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
20496            .expect_err("changed type must fail replay");
20497        assert!(matches!(
20498            error,
20499            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20500                if reason == "side_effect_type_mismatch"
20501        ));
20502    }
20503
20504    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
20505        vec![
20506            history_event(
20507                "ActivityScheduled",
20508                json!({
20509                    "sequence": 1,
20510                    "activity_type": "flaky",
20511                    "activity_execution_id": "act-1",
20512                    "activity": {
20513                        "id": "act-1",
20514                        "sequence": 1,
20515                        "type": "flaky",
20516                        "queue": "critical-activities",
20517                        "execution_mode": null,
20518                        "retry_policy": {
20519                            "snapshot_version": 1,
20520                            "max_attempts": 3,
20521                            "backoff_seconds": [2, 4],
20522                            "start_to_close_timeout": 30,
20523                            "schedule_to_start_timeout": 5,
20524                            "schedule_to_close_timeout": 90,
20525                            "heartbeat_timeout": 10,
20526                            "non_retryable_error_types": ["PermanentError"]
20527                        }
20528                    }
20529                }),
20530            ),
20531            history_event(
20532                "ActivityStarted",
20533                json!({
20534                    "sequence": 1,
20535                    "activity_type": "flaky",
20536                    "activity_execution_id": "act-1",
20537                    "activity_attempt_id": "attempt-1",
20538                    "attempt_number": 1
20539                }),
20540            ),
20541            history_event(
20542                "ActivityRetryScheduled",
20543                json!({
20544                    "sequence": 1,
20545                    "activity_type": "flaky",
20546                    "activity_execution_id": "act-1",
20547                    "activity_attempt_id": "attempt-1",
20548                    "attempt_number": 1,
20549                    "retry_after_attempt": 1,
20550                    "retry_backoff_seconds": 2,
20551                    "failure_category": "activity",
20552                    "exception_type": "TransientError"
20553                }),
20554            ),
20555            history_event(
20556                "ActivityStarted",
20557                json!({
20558                    "sequence": 1,
20559                    "activity_type": "flaky",
20560                    "activity_execution_id": "act-1",
20561                    "activity_attempt_id": "attempt-2",
20562                    "attempt_number": 2
20563                }),
20564            ),
20565            history_event(
20566                "ActivityCompleted",
20567                json!({
20568                    "sequence": 1,
20569                    "activity_type": "flaky",
20570                    "activity_execution_id": "act-1",
20571                    "activity_attempt_id": "attempt-2",
20572                    "attempt_number": 2,
20573                    "payload_codec": DEFAULT_CODEC,
20574                    "result": fixture_envelope(json!({"status":"recovered"}))
20575                }),
20576            ),
20577        ]
20578    }
20579
20580    fn retry_activity_options() -> ActivityOptions {
20581        ActivityOptions::new()
20582            .task_queue("critical-activities")
20583            .retry_policy(
20584                ActivityRetryPolicy::new(3)
20585                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
20586                    .non_retryable_error_type("PermanentError"),
20587            )
20588            .start_to_close_timeout(Duration::from_secs(30))
20589            .schedule_to_start_timeout(Duration::from_secs(5))
20590            .schedule_to_close_timeout(Duration::from_secs(90))
20591            .heartbeat_timeout(Duration::from_secs(10))
20592    }
20593
20594    #[test]
20595    fn fixed_avro_value_round_trips_json_values() {
20596        let value = json!({"greeting": "hello", "count": 3, "ok": true});
20597        let envelope = PayloadEnvelope::avro(&value).expect("encode");
20598        assert_eq!(envelope.codec, DEFAULT_CODEC);
20599        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
20600    }
20601
20602    #[tokio::test]
20603    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
20604        let client = Client::new("http://127.0.0.1:8080").expect("client");
20605        let mut worker = Worker::new(client, "rust-workers");
20606        worker.register_typed_workflow(
20607            "typed.contract.workflow",
20608            |_ctx, input: TypedContract| async move { Ok(input) },
20609        );
20610        worker.register_typed_activity(
20611            "typed.contract.activity",
20612            |_ctx, input: TypedContract| async move { Ok(input) },
20613        );
20614
20615        let expected = typed_contract();
20616        let arguments = AvroValue::Array(vec![
20617            AvroValue::from_serialize(&expected).expect("typed request")
20618        ]);
20619        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
20620        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
20621        workflow.arguments = Some(envelope.clone());
20622        let commands = worker
20623            .execute_workflow_task(workflow)
20624            .expect("typed workflow task");
20625        let workflow_result: TypedContract =
20626            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20627                .expect("workflow result envelope")
20628                .deserialize()
20629                .expect("workflow result type");
20630        assert_eq!(workflow_result, expected);
20631
20632        let activity = ActivityTask {
20633            task_id: "typed-contract-activity".to_string(),
20634            activity_attempt_id: Some("typed-contract-attempt".to_string()),
20635            attempt_id: None,
20636            activity_type: "typed.contract.activity".to_string(),
20637            payload_codec: DEFAULT_CODEC.to_string(),
20638            arguments: Some(envelope),
20639            attempt_number: 1,
20640            lease_owner: Some("rust-worker".to_string()),
20641        };
20642        let activity_result: TypedContract = worker
20643            .execute_activity_task(activity)
20644            .await
20645            .expect("typed activity task")
20646            .deserialize()
20647            .expect("activity result type");
20648        assert_eq!(activity_result, expected);
20649    }
20650
20651    #[test]
20652    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
20653        let calls = Arc::new(AtomicUsize::new(0));
20654        let observed = Arc::clone(&calls);
20655        let client = Client::new("http://127.0.0.1:8080").expect("client");
20656        let mut worker = Worker::new(client.clone(), "rust-workers");
20657        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
20658            observed.fetch_add(1, Ordering::SeqCst);
20659            async move { Ok(input) }
20660        });
20661        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
20662        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
20663        let original = task.clone();
20664        let error = worker
20665            .execute_workflow_task(task)
20666            .expect_err("incompatible entry must refuse the task, not fail the run");
20667        assert_eq!(calls.load(Ordering::SeqCst), 0);
20668        assert!(error
20669            .to_string()
20670            .contains("workflow_entry_arguments_mismatch:"));
20671        assert!(!error.to_string().contains("private-original-value"));
20672
20673        let mut compatible = Worker::new(client, "rust-workers");
20674        compatible
20675            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
20676        let commands = compatible
20677            .execute_workflow_task(original)
20678            .expect("same recorded input");
20679        assert_eq!(commands[0]["type"], "complete_workflow");
20680        assert_eq!(
20681            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
20682            json!("private-original-value")
20683        );
20684    }
20685
20686    #[test]
20687    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
20688        let factories = Arc::new(AtomicUsize::new(0));
20689        let observed = Arc::clone(&factories);
20690        let client = Client::new("http://127.0.0.1:8080").expect("client");
20691        let mut worker = Worker::new(client, "rust-workers");
20692        worker.register_typed_replayed_workflow(
20693            "entry.replayed",
20694            move || {
20695                observed.fetch_add(1, Ordering::SeqCst);
20696                ()
20697            },
20698            |_ctx, _input: i64, _state| async move {
20699                panic!("body must not start");
20700                #[allow(unreachable_code)]
20701                Ok(0_i64)
20702            },
20703        );
20704        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
20705        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
20706        let error = worker
20707            .execute_workflow_task(task)
20708            .expect_err("entry refusal");
20709        assert_eq!(factories.load(Ordering::SeqCst), 0);
20710        assert!(error
20711            .to_string()
20712            .contains("workflow_entry_arguments_mismatch:"));
20713        assert!(!error.to_string().contains("private-replayed-value"));
20714
20715        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
20716        let Err(error) = replay(
20717            workflow_context(Vec::new()),
20718            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
20719        ) else {
20720            panic!("query replay must refuse before creating application state");
20721        };
20722        assert_eq!(factories.load(Ordering::SeqCst), 0);
20723        assert!(!error.to_string().contains("private-replayed-value"));
20724    }
20725
20726    #[test]
20727    fn typed_entry_deserializes_once_before_entering_application_code() {
20728        static DECODES: AtomicUsize = AtomicUsize::new(0);
20729        struct Counted(i64);
20730        impl<'de> Deserialize<'de> for Counted {
20731            fn deserialize<D: Deserializer<'de>>(
20732                deserializer: D,
20733            ) -> std::result::Result<Self, D::Error> {
20734                DECODES.fetch_add(1, Ordering::SeqCst);
20735                i64::deserialize(deserializer).map(Self)
20736            }
20737        }
20738        DECODES.store(0, Ordering::SeqCst);
20739        let client = Client::new("http://127.0.0.1:8080").expect("client");
20740        let mut worker = Worker::new(client, "rust-workers");
20741        worker.register_typed_workflow(
20742            "entry.once",
20743            |_ctx, input: Counted| async move { Ok(input.0) },
20744        );
20745        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
20746        task.arguments = Some(fixture_envelope(json!([7])));
20747        let commands = worker.execute_workflow_task(task).expect("typed result");
20748        assert_eq!(commands[0]["type"], "complete_workflow");
20749        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
20750    }
20751
20752    #[test]
20753    fn typed_entry_body_input_error_remains_a_business_failure() {
20754        let client = Client::new("http://127.0.0.1:8080").expect("client");
20755        let mut worker = Worker::new(client, "rust-workers");
20756        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
20757            Err::<i64, _>(handler_type_error::<i64>(
20758                HandlerKind::Workflow,
20759                "entry.body",
20760                HandlerValueKind::Input,
20761                "deliberate body error",
20762            ))
20763        });
20764        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
20765        task.arguments = Some(fixture_envelope(json!([7])));
20766        let commands = worker
20767            .execute_workflow_task(task)
20768            .expect("business failure command");
20769        assert_eq!(commands[0]["type"], "fail_workflow");
20770        assert!(commands[0]["message"]
20771            .as_str()
20772            .unwrap()
20773            .contains("deliberate body error"));
20774    }
20775
20776    #[test]
20777    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
20778        let client = Client::new("http://127.0.0.1:8080").expect("client");
20779        let mut worker = Worker::new(client, "rust-workers");
20780        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
20781            Err::<i64, _>(handler_type_error::<i64>(
20782                HandlerKind::Workflow,
20783                "entry.body.refusal",
20784                HandlerValueKind::Input,
20785                "workflow_entry_arguments_mismatch: deliberate body error",
20786            ))
20787        });
20788        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
20789        task.arguments = Some(fixture_envelope(json!([7])));
20790        let commands = worker
20791            .execute_workflow_task(task)
20792            .expect("business failure");
20793        assert_eq!(commands[0]["type"], "fail_workflow");
20794    }
20795
20796    #[tokio::test]
20797    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
20798        let client = Client::new("http://127.0.0.1:8080").expect("client");
20799        let mut worker = Worker::new(client, "rust-workers");
20800        worker.register_typed_workflow(
20801            "typed.shape.workflow",
20802            |_ctx, input: TypedContract| async move { Ok(input) },
20803        );
20804        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
20805            Ok(f64::NAN)
20806        });
20807
20808        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
20809        workflow.arguments = Some(
20810            encode_typed_envelope(
20811                &AvroValue::Array(vec![
20812                    AvroValue::String("first".to_string()),
20813                    AvroValue::String("second".to_string()),
20814                ]),
20815                DEFAULT_CODEC,
20816            )
20817            .expect("malformed typed arguments"),
20818        );
20819        let error = worker
20820            .execute_workflow_task(workflow)
20821            .expect_err("entry shape mismatch refuses the task");
20822        let message = error.to_string();
20823        assert!(message.contains("workflow_entry_arguments_mismatch:"));
20824        assert!(message.contains("typed.shape.workflow"));
20825        assert!(message.contains(type_name::<TypedContract>()));
20826
20827        let activity = ActivityTask {
20828            task_id: "typed-unsupported-activity".to_string(),
20829            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
20830            attempt_id: None,
20831            activity_type: "typed.unsupported.activity".to_string(),
20832            payload_codec: DEFAULT_CODEC.to_string(),
20833            arguments: Some(
20834                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20835                    .expect("unit arguments"),
20836            ),
20837            attempt_number: 1,
20838            lease_owner: Some("rust-worker".to_string()),
20839        };
20840        let Error::HandlerType {
20841            handler_kind,
20842            handler_name,
20843            value_kind,
20844            rust_type,
20845            message,
20846        } = worker
20847            .execute_activity_task(activity)
20848            .await
20849            .expect_err("non-finite handler output must fail")
20850        else {
20851            panic!("expected contextual handler type failure");
20852        };
20853        assert_eq!(handler_kind, HandlerKind::Activity);
20854        assert_eq!(handler_name, "typed.unsupported.activity");
20855        assert_eq!(value_kind, HandlerValueKind::Result);
20856        assert_eq!(rust_type, type_name::<f64>());
20857        assert!(message.contains("non_finite_float"));
20858    }
20859
20860    #[tokio::test]
20861    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
20862        #[derive(Clone, Default)]
20863        struct State {
20864            observed: Option<TypedContract>,
20865        }
20866
20867        let client = Client::new("http://127.0.0.1:8080").expect("client");
20868        let mut worker = Worker::new(client, "rust-workers");
20869        worker.register_typed_replayed_workflow(
20870            "typed.contract.replayed",
20871            State::default,
20872            |ctx, input: TypedContract, state| async move {
20873                let result: TypedContract =
20874                    ctx.activity_typed("typed.contract.activity", input).await?;
20875                state.update(|current| current.observed = Some(result.clone()))?;
20876                Ok(result)
20877            },
20878        );
20879        worker.register_replayed_query::<State, _, _>(
20880            "typed.contract.replayed",
20881            "observed",
20882            |_ctx, state, _args| async move {
20883                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
20884            },
20885        );
20886
20887        let expected = typed_contract();
20888        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
20889        let workflow_arguments =
20890            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
20891                .expect("workflow arguments");
20892        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
20893        let task = QueryTask {
20894            query_task_id: "typed-replay-query".to_string(),
20895            query_task_attempt: 1,
20896            lease_owner: Some("rust-worker".to_string()),
20897            workflow_id: Some("typed-replay".to_string()),
20898            run_id: Some("typed-replay-run".to_string()),
20899            workflow_type: "typed.contract.replayed".to_string(),
20900            query_name: "observed".to_string(),
20901            payload_codec: DEFAULT_CODEC.to_string(),
20902            workflow_arguments: Some(workflow_arguments),
20903            query_arguments: Some(
20904                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20905                    .expect("query arguments"),
20906            ),
20907            history_events: vec![
20908                history_event(
20909                    "ActivityScheduled",
20910                    json!({
20911                        "sequence": 1,
20912                        "activity_type": "typed.contract.activity"
20913                    }),
20914                ),
20915                history_event(
20916                    "ActivityCompleted",
20917                    json!({
20918                        "sequence": 1,
20919                        "activity_type": "typed.contract.activity",
20920                        "payload_codec": DEFAULT_CODEC,
20921                        "result": result
20922                    }),
20923                ),
20924            ],
20925            history_export: None,
20926            run_status: Some("completed".to_string()),
20927        };
20928
20929        assert_eq!(
20930            worker
20931                .execute_query_task(task)
20932                .await
20933                .expect("typed replay query")
20934                .deserialize::<i64>()
20935                .expect("query result"),
20936            expected.signed
20937        );
20938    }
20939
20940    #[tokio::test]
20941    async fn update_context_preserves_workflow_input_and_committed_signals() {
20942        let client = Client::new("http://127.0.0.1:8080").expect("client");
20943        let mut worker = Worker::new(client, "rust-workers");
20944        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20945        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
20946        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
20947        let expected_input = workflow_input.clone();
20948        let expected_signals = signal_arguments.clone();
20949        let handler = move |context: QueryContext, arguments: AvroValue| {
20950            let expected_input = expected_input.clone();
20951            let expected_signals = expected_signals.clone();
20952            async move {
20953                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
20954                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
20955                assert_eq!(context.workflow_input_avro_value(), &expected_input);
20956                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
20957                assert_eq!(
20958                    context.signals_avro_value("changed"),
20959                    vec![expected_signals.clone()]
20960                );
20961                assert_eq!(
20962                    context.signals("changed"),
20963                    vec![expected_signals
20964                        .into_iter()
20965                        .map(AvroValue::into_json)
20966                        .collect::<Result<Vec<_>>>()?]
20967                );
20968                assert_eq!(
20969                    context.signal_events()[0].id.as_deref(),
20970                    Some("signal-original")
20971                );
20972                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
20973                Ok(arguments)
20974            }
20975        };
20976        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
20977        worker.register_update_avro_value("snapshot", "inspect", handler);
20978        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
20979        let update_envelope =
20980            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
20981        let mut task = workflow_task(
20982            "snapshot",
20983            vec![
20984                history_event(
20985                    "SignalReceived",
20986                    json!({
20987                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
20988                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
20989                    }),
20990                ),
20991                history_event(
20992                    "UpdateAccepted",
20993                    json!({
20994                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
20995                    }),
20996                ),
20997            ],
20998            DEFAULT_CODEC,
20999        );
21000        task.arguments =
21001            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
21002        task.workflow_update_id = Some("update-original".into());
21003        task.update_name = Some("inspect".into());
21004        let query = QueryTask {
21005            query_task_id: "query-snapshot".into(),
21006            query_task_attempt: 1,
21007            lease_owner: None,
21008            workflow_id: task.workflow_id.clone(),
21009            run_id: task.run_id.clone(),
21010            workflow_type: task.workflow_type.clone(),
21011            query_name: "inspect".into(),
21012            payload_codec: DEFAULT_CODEC.into(),
21013            workflow_arguments: task.arguments.clone(),
21014            query_arguments: Some(update_envelope),
21015            history_events: task.history_events.clone(),
21016            history_export: None,
21017            run_status: Some("running".into()),
21018        };
21019        assert_eq!(
21020            worker
21021                .execute_query_task(query)
21022                .await
21023                .expect("query snapshot"),
21024            update_arguments
21025        );
21026        for _ in 0..2 {
21027            let commands = worker
21028                .execute_workflow_task(task.clone())
21029                .expect("cold update snapshot");
21030            assert_eq!(commands[0]["type"], "complete_update");
21031            assert_eq!(commands[0]["update_id"], "update-original");
21032            assert_eq!(
21033                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21034                    .expect("update result"),
21035                update_arguments
21036            );
21037        }
21038    }
21039
21040    #[test]
21041    fn committed_signal_snapshot_counts_identities_once() {
21042        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
21043        let received = history_event(
21044            "SignalReceived",
21045            json!({
21046                "signal_id": "signal-first", "workflow_command_id": "command-first",
21047                "signal_name": "changed", "arguments": arguments.clone(),
21048            }),
21049        );
21050        let applied = history_event(
21051            "SignalApplied",
21052            json!({
21053                "signal_id": "signal-first", "workflow_command_id": "command-first",
21054                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
21055            }),
21056        );
21057        let distinct = history_event(
21058            "SignalReceived",
21059            json!({
21060                "signal_id": "signal-second", "workflow_command_id": "command-second",
21061                "signal_name": "changed", "arguments": arguments,
21062            }),
21063        );
21064        let history = vec![received.clone(), applied.clone(), distinct];
21065        let signals =
21066            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
21067        assert_eq!(signals.len(), 2);
21068        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21069        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
21070        assert_eq!(signals[0].workflow_sequence, Some(1));
21071        assert_eq!(signals[0].arguments, signals[1].arguments);
21072        let mut command_only = received.clone();
21073        command_only
21074            .payload
21075            .as_object_mut()
21076            .expect("payload")
21077            .remove("signal_id");
21078        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
21079            .expect("command identity");
21080        assert_eq!(signals.len(), 1);
21081        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21082        let mut conflicting = applied;
21083        conflicting.payload["value"] =
21084            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
21085        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
21086    }
21087
21088    #[test]
21089    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
21090        for arguments in [
21091            vec![],
21092            vec![AvroValue::Array(vec![
21093                AvroValue::Long(1),
21094                AvroValue::Long(2),
21095            ])],
21096            vec![AvroValue::Bytes(vec![0, 255])],
21097            vec![AvroValue::Null],
21098            vec![AvroValue::Boolean(false)],
21099            vec![
21100                AvroValue::Long(1),
21101                AvroValue::Array(vec![AvroValue::Long(2)]),
21102            ],
21103        ] {
21104            let applied = match arguments.as_slice() {
21105                [] => AvroValue::Boolean(true),
21106                [value] => value.clone(),
21107                values => AvroValue::Array(values.to_vec()),
21108            };
21109            for applied in [applied, AvroValue::Array(arguments.clone())] {
21110                let events = vec![
21111                    history_event(
21112                        "SignalReceived",
21113                        json!({
21114                            "signal_id": "original", "signal_name": "changed",
21115                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
21116                        }),
21117                    ),
21118                    history_event(
21119                        "SignalApplied",
21120                        json!({
21121                            "signal_id": "original", "signal_name": "changed",
21122                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
21123                        }),
21124                    ),
21125                ];
21126                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
21127                    .expect("canonical signal snapshot");
21128                assert_eq!(signals.len(), 1);
21129                assert_eq!(signals[0].avro_arguments, arguments);
21130            }
21131        }
21132    }
21133
21134    #[tokio::test]
21135    async fn update_context_rejects_malformed_snapshot_before_handler() {
21136        let client = Client::new("http://127.0.0.1:8080").expect("client");
21137        let mut worker = Worker::new(client, "rust-workers");
21138        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21139        let calls = Arc::new(AtomicUsize::new(0));
21140        let observed = Arc::clone(&calls);
21141        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
21142            observed.fetch_add(1, Ordering::SeqCst);
21143            async { Ok(Value::Null) }
21144        });
21145        let mut task = workflow_task(
21146            "snapshot",
21147            vec![history_event(
21148                "UpdateAccepted",
21149                json!({
21150                    "update_id": "update-original", "update_name": "inspect",
21151                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
21152                }),
21153            )],
21154            DEFAULT_CODEC,
21155        );
21156        task.workflow_update_id = Some("update-original".into());
21157        task.update_name = Some("inspect".into());
21158        let mut bad_input = task.clone();
21159        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
21160        assert!(worker.execute_workflow_task(bad_input).is_err());
21161        task.history_events.insert(0, history_event("SignalReceived", json!({
21162            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
21163        })));
21164        assert!(worker.execute_workflow_task(task).is_err());
21165        assert_eq!(calls.load(Ordering::SeqCst), 0);
21166    }
21167
21168    #[tokio::test]
21169    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
21170        let client = Client::new("http://127.0.0.1:8080").expect("client");
21171        let mut worker = Worker::new(client, "rust-workers");
21172        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
21173        worker
21174            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
21175        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
21176            Ok(input)
21177        });
21178        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
21179            Ok(input)
21180        });
21181        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
21182            Ok(AvroValue::Array(
21183                ctx.wait_signal_avro_value("changed").await?,
21184            ))
21185        });
21186
21187        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
21188        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
21189
21190        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
21191        workflow.arguments = Some(envelope.clone());
21192        let commands = worker
21193            .execute_workflow_task(workflow)
21194            .expect("typed workflow task");
21195        assert_eq!(commands[0]["type"], "complete_workflow");
21196        assert_eq!(
21197            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21198                .expect("typed workflow result"),
21199            arguments
21200        );
21201
21202        let activity = ActivityTask {
21203            task_id: "activity-typed".to_string(),
21204            activity_attempt_id: Some("attempt-typed".to_string()),
21205            attempt_id: None,
21206            activity_type: "typed.activity".to_string(),
21207            payload_codec: DEFAULT_CODEC.to_string(),
21208            arguments: Some(envelope.clone()),
21209            attempt_number: 1,
21210            lease_owner: Some("rust-worker".to_string()),
21211        };
21212        assert_eq!(
21213            worker
21214                .execute_activity_task(activity)
21215                .await
21216                .expect("typed activity result"),
21217            arguments
21218        );
21219
21220        let query = QueryTask {
21221            query_task_id: "query-typed".to_string(),
21222            query_task_attempt: 1,
21223            lease_owner: Some("rust-worker".to_string()),
21224            workflow_id: Some("typed-1".to_string()),
21225            run_id: Some("run-typed".to_string()),
21226            workflow_type: "typed.echo".to_string(),
21227            query_name: "inspect".to_string(),
21228            payload_codec: DEFAULT_CODEC.to_string(),
21229            workflow_arguments: Some(
21230                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21231                    .expect("workflow input"),
21232            ),
21233            query_arguments: Some(envelope.clone()),
21234            history_events: Vec::new(),
21235            history_export: None,
21236            run_status: Some("running".to_string()),
21237        };
21238        assert_eq!(
21239            worker
21240                .execute_query_task(query)
21241                .await
21242                .expect("typed query result"),
21243            arguments
21244        );
21245
21246        let mut update = workflow_task(
21247            "typed.echo",
21248            vec![history_event(
21249                "UpdateAccepted",
21250                json!({
21251                    "update_id": "update-typed",
21252                    "update_name": "replace",
21253                    "arguments": envelope.clone(),
21254                }),
21255            )],
21256            DEFAULT_CODEC,
21257        );
21258        update.workflow_update_id = Some("update-typed".to_string());
21259        update.update_name = Some("replace".to_string());
21260        let commands = worker
21261            .execute_workflow_task(update)
21262            .expect("typed update task");
21263        assert_eq!(commands[0]["type"], "complete_update");
21264        assert_eq!(
21265            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21266                .expect("typed update result"),
21267            arguments
21268        );
21269
21270        let mut signal = workflow_task(
21271            "typed.signal",
21272            vec![history_event(
21273                "SignalReceived",
21274                json!({
21275                    "signal_id": "signal-typed",
21276                    "signal_name": "changed",
21277                    "arguments": envelope.clone(),
21278                }),
21279            )],
21280            DEFAULT_CODEC,
21281        );
21282        signal.workflow_signal_id = Some("signal-typed".to_string());
21283        signal.signal_name = Some("changed".to_string());
21284        signal.signal_arguments = Some(envelope);
21285        let commands = worker
21286            .execute_workflow_task(signal)
21287            .expect("typed signal resume");
21288        assert_eq!(
21289            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21290                .expect("typed signal result"),
21291            arguments
21292        );
21293    }
21294
21295    #[tokio::test]
21296    async fn typed_helpers_never_parse_json_inspection_projection() {
21297        let collision_values = projection_collision_probe();
21298        let expected = AvroValue::Array(collision_values.clone());
21299        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
21300
21301        let activity_context = workflow_context_with_codec(
21302            vec![history_event(
21303                "ActivityCompleted",
21304                json!({
21305                    "sequence": 1,
21306                    "activity_type": "collision.activity",
21307                    "payload_codec": DEFAULT_CODEC,
21308                    "result": envelope.clone(),
21309                }),
21310            )],
21311            DEFAULT_CODEC,
21312        );
21313        assert_eq!(
21314            activity_context
21315                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
21316                .await
21317                .expect("typed activity collision result"),
21318            expected
21319        );
21320
21321        let signal_context = workflow_context_with_codec(
21322            vec![
21323                history_event(
21324                    "SignalWaitOpened",
21325                    json!({"sequence": 1, "signal_name": "collision"}),
21326                ),
21327                history_event(
21328                    "SignalApplied",
21329                    json!({
21330                        "sequence": 1,
21331                        "signal_name": "collision",
21332                        "payload_codec": DEFAULT_CODEC,
21333                        "value": envelope.clone(),
21334                    }),
21335                ),
21336            ],
21337            DEFAULT_CODEC,
21338        );
21339        assert_eq!(
21340            signal_context
21341                .wait_signal_avro_value("collision")
21342                .await
21343                .expect("typed signal collision arguments"),
21344            collision_values
21345        );
21346
21347        let child_context = workflow_context_with_codec(
21348            vec![
21349                history_event(
21350                    "ChildWorkflowScheduled",
21351                    json!({
21352                        "sequence": 1,
21353                        "child_workflow_instance_id": "collision-child",
21354                        "child_workflow_run_id": "collision-run",
21355                        "child_workflow_type": "collision.child",
21356                    }),
21357                ),
21358                history_event(
21359                    "ChildRunCompleted",
21360                    json!({
21361                        "sequence": 1,
21362                        "child_workflow_instance_id": "collision-child",
21363                        "child_workflow_run_id": "collision-run",
21364                        "child_workflow_type": "collision.child",
21365                        "payload_codec": DEFAULT_CODEC,
21366                        "result": envelope,
21367                    }),
21368                ),
21369            ],
21370            DEFAULT_CODEC,
21371        );
21372        let child = child_context
21373            .start_child_workflow_avro_value(
21374                "collision.child",
21375                ChildWorkflowOptions::new("collision-workers"),
21376                AvroValue::Array(Vec::new()),
21377            )
21378            .await
21379            .expect("typed child collision result");
21380        assert_eq!(child.result, expected);
21381    }
21382
21383    #[tokio::test]
21384    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
21385        let client = Client::new("http://127.0.0.1:8080").expect("client");
21386        let mut worker = Worker::new(client, "rust-workers");
21387        worker.register_replayed_workflow_avro_value(
21388            "typed.replayed",
21389            || (),
21390            |_ctx, input, _state| async move { Ok(input) },
21391        );
21392        worker.register_replayed_query_avro_value::<(), _, _>(
21393            "typed.replayed",
21394            "inspect",
21395            |ctx, _state, args| async move {
21396                let mut signals = ctx.signals_avro_value("collision");
21397                let signal = signals
21398                    .pop()
21399                    .map(AvroValue::Array)
21400                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
21401                Ok(AvroValue::Array(vec![
21402                    ctx.workflow_input_avro_value().clone(),
21403                    signal,
21404                    args,
21405                ]))
21406            },
21407        );
21408        let arguments = AvroValue::Array(projection_collision_probe());
21409        let signal_arguments =
21410            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
21411        let task = QueryTask {
21412            query_task_id: "query-typed-replay".to_string(),
21413            query_task_attempt: 1,
21414            lease_owner: Some("rust-worker".to_string()),
21415            workflow_id: Some("typed-replay".to_string()),
21416            run_id: Some("run-typed-replay".to_string()),
21417            workflow_type: "typed.replayed".to_string(),
21418            query_name: "inspect".to_string(),
21419            payload_codec: DEFAULT_CODEC.to_string(),
21420            workflow_arguments: Some(
21421                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
21422            ),
21423            query_arguments: Some(
21424                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
21425            ),
21426            history_events: vec![history_event(
21427                "SignalReceived",
21428                json!({
21429                    "signal_id": "collision-signal",
21430                    "signal_name": "collision",
21431                    "workflow_sequence": 1,
21432                    "payload_codec": DEFAULT_CODEC,
21433                    "arguments": signal_arguments,
21434                }),
21435            )],
21436            history_export: None,
21437            run_status: Some("completed".to_string()),
21438        };
21439
21440        assert_eq!(
21441            worker
21442                .execute_query_task(task)
21443                .await
21444                .expect("typed replay query"),
21445            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
21446        );
21447    }
21448
21449    #[test]
21450    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
21451        let value = BTreeMap::from([(1_i32, "integer key")]);
21452        let error = PayloadEnvelope::avro(&value)
21453            .expect_err("integer map keys must fail")
21454            .to_string();
21455
21456        assert!(error.contains("invalid_map_key"));
21457    }
21458
21459    #[test]
21460    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
21461        let envelope = PayloadEnvelope {
21462            codec: "json".to_string(),
21463            blob: r#"{"greeting":"hello"}"#.to_string(),
21464        };
21465
21466        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
21467        let diagnostic = error.to_string();
21468        assert!(diagnostic.contains("unsupported_payload_codec"));
21469        assert!(diagnostic.contains("codec=\"avro\""));
21470        assert!(diagnostic.contains("HTTP document transport"));
21471    }
21472
21473    #[test]
21474    fn untagged_json_payload_value_fails_closed() {
21475        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
21476            .expect_err("untagged JSON payload values must fail");
21477        let diagnostic = error.to_string();
21478        assert!(diagnostic.contains("unsupported_payload_codec"));
21479        assert!(diagnostic.contains("untagged durable payload"));
21480        assert!(diagnostic.contains("HTTP document transport"));
21481    }
21482
21483    #[test]
21484    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
21485        let envelope = PayloadEnvelope {
21486            codec: DEFAULT_CODEC.to_string(),
21487            blob: BASE64.encode([0x01]),
21488        };
21489
21490        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
21491        assert!(error.to_string().contains("invalid_payload_framing"));
21492    }
21493
21494    #[tokio::test]
21495    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
21496        let server = MockWorkerServer::start();
21497        let client = Client::builder(server.base_url())
21498            .timeout(Duration::from_secs(2))
21499            .build()
21500            .expect("client");
21501        let invalid_commands = [
21502            json!({
21503                "type": "complete_workflow",
21504                "result": {"codec": "json", "blob": null}
21505            }),
21506            json!({
21507                "type": "schedule_activity",
21508                "arguments": {"codec": "yaml", "blob": "ignored"}
21509            }),
21510            json!({
21511                "type": "start_child_workflow",
21512                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
21513            }),
21514            json!({"type": "continue_as_new", "arguments": []}),
21515            json!({"type": "complete_update"}),
21516            json!({"type": "record_side_effect", "result": null}),
21517            json!({
21518                "type": "start_service_operation",
21519                "payload_codec": DEFAULT_CODEC,
21520                "request_payload": "raw-avro-bytes"
21521            }),
21522        ];
21523
21524        for command in invalid_commands {
21525            let error = client
21526                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
21527                .await
21528                .expect_err("invalid durable payload must fail locally");
21529            let diagnostic = error.to_string();
21530            assert!(
21531                diagnostic.contains("unsupported_payload_codec")
21532                    || diagnostic.contains("invalid_payload_envelope")
21533                    || diagnostic.contains("untagged durable payload"),
21534                "unexpected validation diagnostic: {diagnostic}"
21535            );
21536        }
21537
21538        assert_eq!(
21539            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
21540            0,
21541            "invalid command payloads must not reach HTTP transport"
21542        );
21543    }
21544
21545    #[test]
21546    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
21547        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
21548        let commands = [
21549            json!({"type": "complete_workflow", "result": envelope.clone()}),
21550            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
21551            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
21552            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
21553            json!({"type": "complete_update", "result": envelope.clone()}),
21554            json!({"type": "record_side_effect", "result": envelope.clone()}),
21555            json!({
21556                "type": "start_service_operation",
21557                "payload_codec": DEFAULT_CODEC,
21558                "request_payload": envelope.clone()
21559            }),
21560            json!({
21561                "type": "complete_workflow",
21562                "result": envelope,
21563                "metadata": {
21564                    "codec": "json",
21565                    "payload_codec": "customer-codec",
21566                    "result": {"codec": "yaml", "blob": null}
21567                }
21568            }),
21569        ];
21570
21571        validate_workflow_task_commands(&commands)
21572            .expect("customer metadata must not become a protocol codec declaration");
21573    }
21574
21575    #[test]
21576    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
21577        assert_eq!(
21578            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
21579            AvroValue::Array(Vec::new())
21580        );
21581        assert_eq!(
21582            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
21583            AvroValue::Array(Vec::new())
21584        );
21585
21586        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21587        signal.signal_name = Some("empty-signal".to_string());
21588        signal.signal_arguments = None;
21589        let decoded = decode_resume_signal(&signal)
21590            .expect("valid Avro signal")
21591            .expect("named signal resumes the workflow");
21592        assert!(decoded.arguments.is_empty());
21593    }
21594
21595    #[tokio::test]
21596    async fn malformed_task_level_codecs_become_pre_handler_failures() {
21597        let client = Client::new("http://127.0.0.1:8080").expect("client");
21598        let mut worker = Worker::new(client, "rust-workers");
21599        let handler_calls = Arc::new(AtomicUsize::new(0));
21600
21601        let calls = Arc::clone(&handler_calls);
21602        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21603            calls.fetch_add(1, Ordering::SeqCst);
21604            async move { Ok(Value::Null) }
21605        });
21606        let calls = Arc::clone(&handler_calls);
21607        worker.register_activity("codec.activity", move |_ctx, _args| {
21608            calls.fetch_add(1, Ordering::SeqCst);
21609            async move { Ok(Value::Null) }
21610        });
21611        let calls = Arc::clone(&handler_calls);
21612        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21613            calls.fetch_add(1, Ordering::SeqCst);
21614            async move { Ok(Value::Null) }
21615        });
21616
21617        let mut failures = Vec::new();
21618        for codec_case in [
21619            InvalidTaskPayloadCodec::Missing,
21620            InvalidTaskPayloadCodec::Null,
21621            InvalidTaskPayloadCodec::NonString,
21622        ] {
21623            let mut workflow = json!({
21624                "task_id": format!("workflow-{}", codec_case.label()),
21625                "workflow_type": "codec.workflow"
21626            });
21627            codec_case.apply(&mut workflow);
21628            match serde_json::from_value::<WorkflowTask>(workflow) {
21629                Ok(task) => match worker.execute_workflow_task(task) {
21630                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21631                    outcome => failures.push(format!(
21632                        "workflow {} codec returned {outcome:?}",
21633                        codec_case.label()
21634                    )),
21635                },
21636                Err(error) => failures.push(format!(
21637                    "workflow {} codec failed transport deserialization: {error}",
21638                    codec_case.label()
21639                )),
21640            }
21641
21642            let mut activity = json!({
21643                "task_id": format!("activity-{}", codec_case.label()),
21644                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
21645                "activity_type": "codec.activity",
21646                "attempt_number": 1
21647            });
21648            codec_case.apply(&mut activity);
21649            match serde_json::from_value::<ActivityTask>(activity) {
21650                Ok(task) => match worker.execute_activity_task(task).await {
21651                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21652                    outcome => failures.push(format!(
21653                        "activity {} codec returned {outcome:?}",
21654                        codec_case.label()
21655                    )),
21656                },
21657                Err(error) => failures.push(format!(
21658                    "activity {} codec failed transport deserialization: {error}",
21659                    codec_case.label()
21660                )),
21661            }
21662
21663            let mut query = json!({
21664                "query_task_id": format!("query-{}", codec_case.label()),
21665                "workflow_type": "codec.workflow",
21666                "query_name": "known"
21667            });
21668            codec_case.apply(&mut query);
21669            match serde_json::from_value::<QueryTask>(query) {
21670                Ok(task) => match worker.execute_query_task(task).await {
21671                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
21672                    outcome => failures.push(format!(
21673                        "query {} codec returned {outcome:?}",
21674                        codec_case.label()
21675                    )),
21676                },
21677                Err(error) => failures.push(format!(
21678                    "query {} codec failed transport deserialization: {error}",
21679                    codec_case.label()
21680                )),
21681            }
21682        }
21683
21684        assert!(failures.is_empty(), "{}", failures.join("\n"));
21685        assert_eq!(
21686            handler_calls.load(Ordering::SeqCst),
21687            0,
21688            "invalid task codecs must not invoke a handler"
21689        );
21690    }
21691
21692    #[tokio::test]
21693    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
21694        for codec_case in [
21695            InvalidTaskPayloadCodec::Missing,
21696            InvalidTaskPayloadCodec::Null,
21697            InvalidTaskPayloadCodec::NonString,
21698        ] {
21699            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
21700            let client = Client::builder(server.base_url())
21701                .timeout(Duration::from_secs(2))
21702                .build()
21703                .expect("client");
21704            let mut worker = Worker::new(client, "rust-workers")
21705                .worker_id("codec-worker")
21706                .poll_timeout(Duration::from_millis(10));
21707            let handler_calls = Arc::new(AtomicUsize::new(0));
21708
21709            let calls = Arc::clone(&handler_calls);
21710            worker.register_workflow("codec.workflow", move |_ctx, _args| {
21711                calls.fetch_add(1, Ordering::SeqCst);
21712                async move { Ok(Value::Null) }
21713            });
21714            let calls = Arc::clone(&handler_calls);
21715            worker.register_activity("codec.activity", move |_ctx, _args| {
21716                calls.fetch_add(1, Ordering::SeqCst);
21717                async move { Ok(Value::Null) }
21718            });
21719            let calls = Arc::clone(&handler_calls);
21720            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21721                calls.fetch_add(1, Ordering::SeqCst);
21722                async move { Ok(Value::Null) }
21723            });
21724
21725            assert_eq!(
21726                worker.run_once().await.expect("invalid tasks are settled"),
21727                3,
21728                "all {} codec tasks must be handled",
21729                codec_case.label()
21730            );
21731            assert_eq!(
21732                handler_calls.load(Ordering::SeqCst),
21733                0,
21734                "{} task codecs must fail before every handler",
21735                codec_case.label()
21736            );
21737
21738            for path in [
21739                "/api/worker/workflow-tasks/codec-workflow/fail",
21740                "/api/worker/activity-tasks/codec-activity/fail",
21741                "/api/worker/query-tasks/codec-query/fail",
21742            ] {
21743                let body = server.request_body(path);
21744                assert!(
21745                    body["failure"]["message"]
21746                        .as_str()
21747                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
21748                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
21749                    codec_case.label()
21750                );
21751            }
21752            assert_eq!(
21753                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
21754                    ["reason"],
21755                "query_payload_decode_failed"
21756            );
21757            for path in [
21758                "/api/worker/workflow-tasks/codec-workflow/complete",
21759                "/api/worker/activity-tasks/codec-activity/complete",
21760                "/api/worker/query-tasks/codec-query/complete",
21761            ] {
21762                assert_eq!(
21763                    server.request_count(path),
21764                    0,
21765                    "invalid {} codec task reached {path}",
21766                    codec_case.label()
21767                );
21768            }
21769        }
21770    }
21771
21772    #[tokio::test]
21773    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
21774        let client = Client::new("http://127.0.0.1:8080").expect("client");
21775        let mut worker = Worker::new(client, "rust-workers");
21776        let handler_calls = Arc::new(AtomicUsize::new(0));
21777
21778        let calls = Arc::clone(&handler_calls);
21779        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21780            calls.fetch_add(1, Ordering::SeqCst);
21781            async move { Ok(Value::Null) }
21782        });
21783        let calls = Arc::clone(&handler_calls);
21784        worker.register_activity("codec.activity", move |_ctx, _args| {
21785            calls.fetch_add(1, Ordering::SeqCst);
21786            async move { Ok(Value::Null) }
21787        });
21788        let calls = Arc::clone(&handler_calls);
21789        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
21790            calls.fetch_add(1, Ordering::SeqCst);
21791            async move { Ok(Value::Null) }
21792        });
21793        let calls = Arc::clone(&handler_calls);
21794        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21795            calls.fetch_add(1, Ordering::SeqCst);
21796            async move { Ok(Value::Null) }
21797        });
21798
21799        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21800        workflow.payload_codec = "json".to_string();
21801        workflow.arguments = None;
21802        let error = worker
21803            .execute_workflow_task(workflow)
21804            .expect_err("task codec must be checked before workflow invocation");
21805        assert!(error.to_string().contains("unsupported_payload_codec"));
21806
21807        let activity = ActivityTask {
21808            task_id: "activity-invalid-codec".to_string(),
21809            activity_attempt_id: None,
21810            attempt_id: None,
21811            activity_type: "codec.activity".to_string(),
21812            payload_codec: "unknown".to_string(),
21813            arguments: None,
21814            attempt_number: 1,
21815            lease_owner: None,
21816        };
21817        let error = worker
21818            .execute_activity_task(activity)
21819            .await
21820            .expect_err("task codec must be checked before activity invocation");
21821        assert!(error.to_string().contains("unsupported_payload_codec"));
21822
21823        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21824        update.workflow_update_id = Some("update-invalid-codec".to_string());
21825        update.update_name = Some("known".to_string());
21826        update.history_events.push(history_event(
21827            "UpdateAccepted",
21828            json!({
21829                "update_id": "update-invalid-codec",
21830                "update_name": "known",
21831                "arguments": {"codec": "json", "blob": null}
21832            }),
21833        ));
21834        let error = worker
21835            .execute_workflow_task(update)
21836            .expect_err("nested update codec must be checked before handler lookup");
21837        assert!(error.to_string().contains("unsupported_payload_codec"));
21838
21839        let query: QueryTask = serde_json::from_value(json!({
21840            "query_task_id": "query-invalid-codec",
21841            "workflow_type": "codec.workflow",
21842            "query_name": "known",
21843            "payload_codec": DEFAULT_CODEC,
21844            "workflow_arguments": null,
21845            "query_arguments": null,
21846            "history_export": {
21847                "payloads": {"codec": DEFAULT_CODEC},
21848                "signals": [{
21849                    "name": "empty",
21850                    "payload_codec": "json",
21851                    "arguments": null
21852                }]
21853            }
21854        }))
21855        .expect("query task");
21856        let failure = worker
21857            .execute_query_task(query)
21858            .await
21859            .expect_err("exported signal codec must be checked before query invocation");
21860        assert_eq!(failure.reason, "query_payload_decode_failed");
21861        assert!(failure.message.contains("unsupported_payload_codec"));
21862
21863        let exported_history: QueryTask = serde_json::from_value(json!({
21864            "query_task_id": "query-invalid-history-codec",
21865            "workflow_type": "codec.workflow",
21866            "query_name": "known",
21867            "payload_codec": DEFAULT_CODEC,
21868            "history_export": {
21869                "payloads": {"codec": DEFAULT_CODEC},
21870                "history_events": [{
21871                    "type": "ActivityCompleted",
21872                    "payload": {"payload_codec": "unknown", "result": null}
21873                }]
21874            }
21875        }))
21876        .expect("query task");
21877        let failure = worker
21878            .execute_query_task(exported_history)
21879            .await
21880            .expect_err("exported history codec must be checked before query invocation");
21881        assert_eq!(failure.reason, "query_payload_decode_failed");
21882        assert!(failure.message.contains("unsupported_payload_codec"));
21883        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
21884
21885        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21886        unknown_workflow.arguments = None;
21887        unknown_workflow.history_events.push(history_event(
21888            "SignalReceived",
21889            json!({
21890                "signal_name": "empty",
21891                "payload_codec": "json",
21892                "arguments": null
21893            }),
21894        ));
21895        let error = worker
21896            .execute_workflow_task(unknown_workflow)
21897            .expect_err("history codec must precede unknown workflow outcome");
21898        assert!(error.to_string().contains("unsupported_payload_codec"));
21899
21900        let unknown_activity = ActivityTask {
21901            task_id: "activity-unknown".to_string(),
21902            activity_attempt_id: None,
21903            attempt_id: None,
21904            activity_type: "missing".to_string(),
21905            payload_codec: "json".to_string(),
21906            arguments: None,
21907            attempt_number: 1,
21908            lease_owner: None,
21909        };
21910        let error = worker
21911            .execute_activity_task(unknown_activity)
21912            .await
21913            .expect_err("codec must precede unknown activity outcome");
21914        assert!(error.to_string().contains("unsupported_payload_codec"));
21915
21916        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21917        unknown_update.payload_codec = "json".to_string();
21918        unknown_update.arguments = None;
21919        unknown_update.workflow_update_id = Some("update-unknown".to_string());
21920        unknown_update.update_name = Some("missing".to_string());
21921        let error = worker
21922            .execute_workflow_task(unknown_update)
21923            .expect_err("codec must precede fail_update shortcut");
21924        assert!(error.to_string().contains("unsupported_payload_codec"));
21925
21926        let unknown_query: QueryTask = serde_json::from_value(json!({
21927            "query_task_id": "query-unknown",
21928            "workflow_type": "missing",
21929            "query_name": "missing",
21930            "payload_codec": "json",
21931            "workflow_arguments": null,
21932            "query_arguments": null
21933        }))
21934        .expect("query task");
21935        let failure = worker
21936            .execute_query_task(unknown_query)
21937            .await
21938            .expect_err("codec must precede unknown query outcome");
21939        assert_eq!(failure.reason, "query_payload_decode_failed");
21940        assert!(failure.message.contains("unsupported_payload_codec"));
21941    }
21942
21943    #[tokio::test]
21944    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
21945        let client = Client::new("http://127.0.0.1:8080").expect("client");
21946        let worker = Worker::new(client, "rust-workers");
21947
21948        for event_type in ["SignalReceived", "SignalApplied"] {
21949            for (payload_field, codec) in [
21950                ("value", "json"),
21951                ("input", "unknown"),
21952                ("arguments", "json"),
21953            ] {
21954                let payload = json!({
21955                    "signal_name": "empty",
21956                    payload_field: {"codec": codec, "blob": null}
21957                });
21958                let workflow = workflow_task(
21959                    "missing",
21960                    vec![history_event(event_type, payload.clone())],
21961                    DEFAULT_CODEC,
21962                );
21963                let error = worker
21964                    .execute_workflow_task(workflow)
21965                    .expect_err("signal payload codec must precede unknown workflow outcome");
21966                assert!(
21967                    error.to_string().contains("unsupported_payload_codec"),
21968                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
21969                );
21970
21971                let query: QueryTask = serde_json::from_value(json!({
21972                    "query_task_id": format!("query-{event_type}-{payload_field}"),
21973                    "workflow_type": "missing",
21974                    "query_name": "missing",
21975                    "payload_codec": DEFAULT_CODEC,
21976                    "workflow_arguments": null,
21977                    "query_arguments": null,
21978                    "history_events": [{
21979                        "event_type": event_type,
21980                        "payload": payload
21981                    }]
21982                }))
21983                .expect("query task");
21984                let failure = worker
21985                    .execute_query_task(query)
21986                    .await
21987                    .expect_err("signal payload codec must precede unknown query outcome");
21988                assert_eq!(
21989                    failure.reason, "query_payload_decode_failed",
21990                    "{event_type}.{payload_field} returned an unrelated query outcome"
21991                );
21992                assert!(
21993                    failure.message.contains("unsupported_payload_codec"),
21994                    "{event_type}.{payload_field} returned an unrelated query error: {}",
21995                    failure.message
21996                );
21997            }
21998        }
21999    }
22000
22001    #[test]
22002    fn workflow_context_schedules_activity_until_completion_is_in_history() {
22003        let ctx = WorkflowContext {
22004            cancellation_scope_id: "root".into(),
22005            state: Arc::new(Mutex::new(
22006                WorkflowState::new_with_identity(
22007                    Vec::new(),
22008                    Some("wf-parent".to_string()),
22009                    Some("run-parent".to_string()),
22010                    "rust-workers".to_string(),
22011                    DEFAULT_CODEC.to_string(),
22012                    None,
22013                )
22014                .expect("workflow state"),
22015            )),
22016        };
22017
22018        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
22019        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22020        assert!(matches!(
22021            call.as_mut().poll(&mut task_context),
22022            Poll::Pending
22023        ));
22024
22025        let commands = ctx.take_commands().expect("commands");
22026        assert_eq!(commands[0]["type"], "schedule_activity");
22027        assert_eq!(commands[0]["activity_type"], "hello.activity");
22028    }
22029
22030    #[test]
22031    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
22032        let ctx = workflow_context(Vec::new());
22033        let options = ActivityOptions::new()
22034            .task_queue("payments")
22035            .retry_policy(
22036                ActivityRetryPolicy::new(4)
22037                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
22038                    .non_retryable_error_type("ValidationError"),
22039            )
22040            .start_to_close_timeout(Duration::from_secs(120))
22041            .schedule_to_start_timeout(Duration::from_secs(10))
22042            .schedule_to_close_timeout(Duration::from_secs(300))
22043            .heartbeat_timeout(Duration::from_secs(15));
22044        let mut call = Box::pin(ctx.activity_with_options(
22045            "charge-card",
22046            options,
22047            json!([{"order_id": "o-1"}]),
22048        ));
22049        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22050
22051        assert!(matches!(
22052            call.as_mut().poll(&mut task_context),
22053            Poll::Pending
22054        ));
22055        assert!(matches!(
22056            call.as_mut().poll(&mut task_context),
22057            Poll::Pending
22058        ));
22059
22060        let commands = ctx.take_commands().expect("activity command");
22061        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
22062        assert_eq!(commands[0]["queue"], "payments");
22063        assert_eq!(
22064            commands[0]["retry_policy"],
22065            json!({
22066                "max_attempts": 4,
22067                "backoff_seconds": [1, 3, 9],
22068                "non_retryable_error_types": ["ValidationError"],
22069            })
22070        );
22071        assert_eq!(commands[0]["start_to_close_timeout"], 120);
22072        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
22073        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
22074        assert_eq!(commands[0]["heartbeat_timeout"], 15);
22075    }
22076
22077    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
22078        vec![
22079            history_event(
22080                "ActivityScheduled",
22081                json!({"sequence":1,"activity_type":"render",
22082                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
22083            ),
22084            history_event(
22085                "ActivityCompleted",
22086                json!({"sequence":1,"activity_type":"render",
22087                "payload_codec":DEFAULT_CODEC,
22088                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
22089            ),
22090        ]
22091    }
22092
22093    #[test]
22094    fn worker_session_activity_routes_to_session_queue_once() {
22095        let ctx = workflow_context(Vec::new());
22096        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22097        let mut call = Box::pin(
22098            ctx.activity("render", json!([]))
22099                .in_worker_session(session.clone()),
22100        );
22101        let mut cx = TaskContext::from_waker(noop_waker_ref());
22102        assert!(call.as_mut().poll(&mut cx).is_pending());
22103        assert!(call.as_mut().poll(&mut cx).is_pending());
22104        let commands = ctx.take_commands().unwrap();
22105        assert_eq!(commands.len(), 1);
22106        assert_eq!(commands[0]["queue"], "gpu-workers");
22107        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
22108    }
22109
22110    #[tokio::test]
22111    async fn worker_session_cold_replay_uses_recorded_avro_result() {
22112        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22113        for _replacement in 0..2 {
22114            let ctx = workflow_context(completed_worker_session_history(&session));
22115            let result: i64 = ctx
22116                .activity("render", json!([]))
22117                .in_worker_session(session.clone())
22118                .typed()
22119                .await
22120                .unwrap();
22121            assert_eq!(result, 42);
22122            assert!(ctx.take_commands().unwrap().is_empty());
22123        }
22124    }
22125
22126    #[test]
22127    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
22128        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22129        for changed in [
22130            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
22131            Some(original.clone().ttl_seconds(60)),
22132            Some(original.clone().requirements(["gpu:l4"])),
22133            None,
22134        ] {
22135            let ctx = workflow_context(completed_worker_session_history(&original));
22136            let mut call = ctx.activity_with_options(
22137                "render",
22138                ActivityOptions::new().task_queue("gpu-workers"),
22139                json!([]),
22140            );
22141            if let Some(changed) = changed {
22142                call = call.in_worker_session(changed);
22143            }
22144            let mut call = Box::pin(call);
22145            let mut cx = TaskContext::from_waker(noop_waker_ref());
22146            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22147                call.as_mut().poll(&mut cx)
22148            else {
22149                panic!("changed session must fail replay");
22150            };
22151            assert_eq!(failure.reason, "activity_worker_session_mismatch");
22152            assert!(ctx.take_commands().unwrap().is_empty());
22153        }
22154    }
22155
22156    #[test]
22157    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
22158        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22159        let ctx = workflow_context(Vec::new());
22160        let mut local = Box::pin(
22161            ctx.local_activity("render", json!([]))
22162                .in_worker_session(session.clone()),
22163        );
22164        let mut cx = TaskContext::from_waker(noop_waker_ref());
22165        assert!(matches!(
22166            local.as_mut().poll(&mut cx),
22167            Poll::Ready(Err(Error::WorkerLoop(_)))
22168        ));
22169        assert!(ctx.take_commands().unwrap().is_empty());
22170        let mut remote = Box::pin(
22171            ctx.activity_with_options(
22172                "render",
22173                ActivityOptions::new().task_queue("other"),
22174                json!([]),
22175            )
22176            .in_worker_session(session),
22177        );
22178        assert!(matches!(
22179            remote.as_mut().poll(&mut cx),
22180            Poll::Ready(Err(Error::WorkerLoop(_)))
22181        ));
22182        assert!(ctx.take_commands().unwrap().is_empty());
22183    }
22184
22185    #[test]
22186    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
22187        let ctx = workflow_context(Vec::new());
22188        let options = ActivityOptions::new().retry_policy(
22189            ActivityRetryPolicy::new(3)
22190                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
22191        );
22192        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
22193        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22194
22195        assert!(matches!(
22196            call.as_mut().poll(&mut task_context),
22197            Poll::Pending
22198        ));
22199        assert_eq!(
22200            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
22201            json!([1, 2])
22202        );
22203    }
22204
22205    #[test]
22206    fn activity_options_preserve_unused_explicit_backoff_entries() {
22207        for max_attempts in [1, 2, 10] {
22208            let ctx = workflow_context(Vec::new());
22209            let options =
22210                ActivityOptions::new()
22211                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
22212                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
22213                    ));
22214            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
22215            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22216            assert!(matches!(
22217                call.as_mut().poll(&mut task_context),
22218                Poll::Pending
22219            ));
22220            let commands = ctx.take_commands().expect("command");
22221            assert_eq!(commands.len(), 1);
22222            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
22223            assert_eq!(
22224                commands[0]["retry_policy"]["backoff_seconds"],
22225                json!([1, 2, 5, 10, 15, 30, 60, 120])
22226            );
22227        }
22228        let default_options = ActivityOptions::new().validate().expect("default options");
22229        let default_policy = current_activity_retry_snapshot(&default_options);
22230        assert_eq!(
22231            default_policy.max_attempts,
22232            RecordedSnapshotValue::Known(Some(1))
22233        );
22234        assert_eq!(
22235            default_policy.backoff_seconds,
22236            RecordedSnapshotValue::Known(Vec::new())
22237        );
22238    }
22239
22240    #[test]
22241    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
22242        let fixture: Value = serde_json::from_str(include_str!(
22243            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
22244        ))
22245        .expect("published PHP fixture");
22246        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
22247            .expect("unchanged published history");
22248        let matching = ActivityOptions::new().task_queue("default").retry_policy(
22249            ActivityRetryPolicy::new(1)
22250                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
22251        );
22252        let mut changed_tail = matching.clone();
22253        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
22254            [1, 2, 5, 10, 15, 30, 60, 121]
22255                .map(Duration::from_secs)
22256                .to_vec(),
22257        ));
22258        let mut changed_first = matching.clone();
22259        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
22260            [2, 2, 5, 10, 15, 30, 60, 120]
22261                .map(Duration::from_secs)
22262                .to_vec(),
22263        ));
22264        let mut changed_attempts = matching.clone();
22265        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
22266        let mut changed_types = matching.clone();
22267        changed_types
22268            .retry_policy
22269            .as_mut()
22270            .unwrap()
22271            .non_retryable_error_types = vec!["ChangedError".into()];
22272        let mut changed_start = matching.clone();
22273        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
22274        let mut changed_schedule_start = matching.clone();
22275        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
22276        let mut changed_schedule_close = matching.clone();
22277        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
22278        let mut changed_heartbeat = matching;
22279        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
22280        let unchanged_defaults = ActivityOptions::new().task_queue("default");
22281        for options in [
22282            changed_tail,
22283            changed_first,
22284            changed_attempts,
22285            changed_types,
22286            changed_start,
22287            changed_schedule_start,
22288            changed_schedule_close,
22289            changed_heartbeat,
22290            unchanged_defaults,
22291        ] {
22292            let ctx = workflow_context(history.clone());
22293            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
22294            assert!(!ctx.patched("frozen-zero").unwrap());
22295            ctx.deprecate_patch("frozen-zero").unwrap();
22296            let mut call =
22297                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
22298            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22299            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22300                call.as_mut().poll(&mut task_context)
22301            else {
22302                panic!("changed explicit policy must fail replay")
22303            };
22304            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
22305            assert_eq!(failure.sequence, Some(2));
22306            assert!(ctx.take_commands().unwrap().is_empty());
22307        }
22308    }
22309
22310    #[test]
22311    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
22312        let cases = [
22313            (
22314                ActivityOptions::new().task_queue("  "),
22315                ActivityOptionsErrorKind::EmptyTaskQueue,
22316            ),
22317            (
22318                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
22319                ActivityOptionsErrorKind::EmptyRetryPolicy,
22320            ),
22321            (
22322                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
22323                ActivityOptionsErrorKind::InvalidMaxAttempts,
22324            ),
22325            (
22326                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
22327                    max_attempts: None,
22328                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
22329                    non_retryable_error_types: Vec::new(),
22330                }),
22331                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
22332            ),
22333            (
22334                ActivityOptions::new().retry_policy(
22335                    ActivityRetryPolicy::new(2).exponential_backoff(
22336                        Duration::from_secs(1),
22337                        0,
22338                        None,
22339                    ),
22340                ),
22341                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
22342            ),
22343            (
22344                ActivityOptions::new()
22345                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
22346                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
22347            ),
22348            (
22349                ActivityOptions::new().retry_policy(
22350                    ActivityRetryPolicy::new(10_002).exponential_backoff(
22351                        Duration::from_secs(1),
22352                        1,
22353                        None,
22354                    ),
22355                ),
22356                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
22357            ),
22358            (
22359                ActivityOptions::new().retry_policy(
22360                    ActivityRetryPolicy::new(2)
22361                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
22362                ),
22363                ActivityOptionsErrorKind::BackoffOverflow,
22364            ),
22365        ];
22366
22367        for (options, expected_kind) in cases {
22368            let ctx = workflow_context(Vec::new());
22369            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
22370            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22371            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
22372                call.as_mut().poll(&mut task_context)
22373            else {
22374                panic!("expected typed activity validation error");
22375            };
22376            assert_eq!(error.kind, expected_kind);
22377            assert!(ctx.take_commands().expect("commands").is_empty());
22378        }
22379    }
22380
22381    #[test]
22382    fn activity_options_validate_positive_and_ordered_timeouts() {
22383        let zero_timeout_cases = [
22384            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
22385            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
22386            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
22387            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
22388        ];
22389        for options in zero_timeout_cases {
22390            assert_eq!(
22391                options.validate().expect_err("zero timeout").kind,
22392                ActivityOptionsErrorKind::TimeoutNotPositive
22393            );
22394        }
22395
22396        let ordering_cases = [
22397            ActivityOptions::new()
22398                .heartbeat_timeout(Duration::from_secs(11))
22399                .start_to_close_timeout(Duration::from_secs(10)),
22400            ActivityOptions::new()
22401                .start_to_close_timeout(Duration::from_secs(31))
22402                .schedule_to_close_timeout(Duration::from_secs(30)),
22403            ActivityOptions::new()
22404                .schedule_to_start_timeout(Duration::from_secs(31))
22405                .schedule_to_close_timeout(Duration::from_secs(30)),
22406        ];
22407        for options in ordering_cases {
22408            assert_eq!(
22409                options.validate().expect_err("timeout order").kind,
22410                ActivityOptionsErrorKind::TimeoutOrder
22411            );
22412        }
22413
22414        assert_eq!(
22415            ActivityOptions::new()
22416                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
22417                .validate()
22418                .expect_err("protocol integer overflow")
22419                .kind,
22420            ActivityOptionsErrorKind::TimeoutOverflow
22421        );
22422    }
22423
22424    #[test]
22425    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
22426        let ctx = workflow_context(completed_retry_activity_history());
22427        let mut call =
22428            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22429        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22430
22431        assert!(matches!(
22432            call.as_mut().poll(&mut task_context),
22433            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22434        ));
22435        assert!(ctx.take_commands().expect("commands").is_empty());
22436        ctx.ensure_history_consumed().expect("history consumed");
22437    }
22438
22439    #[test]
22440    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
22441        let mut options = retry_activity_options();
22442        options
22443            .retry_policy
22444            .as_mut()
22445            .expect("retry policy")
22446            .non_retryable_error_types
22447            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
22448
22449        let new_ctx = workflow_context(Vec::new());
22450        let mut new_call =
22451            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
22452        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22453        assert!(matches!(
22454            new_call.as_mut().poll(&mut task_context),
22455            Poll::Pending
22456        ));
22457        let commands = new_ctx.take_commands().expect("commands");
22458        assert_eq!(commands.len(), 1);
22459        assert_eq!(
22460            commands[0]["retry_policy"]["non_retryable_error_types"],
22461            json!(["PermanentError"])
22462        );
22463
22464        let replay_ctx = workflow_context(completed_retry_activity_history());
22465        let mut replay_call =
22466            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
22467        assert!(matches!(
22468            replay_call.as_mut().poll(&mut task_context),
22469            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22470        ));
22471        assert!(replay_ctx.take_commands().expect("commands").is_empty());
22472        replay_ctx
22473            .ensure_history_consumed()
22474            .expect("history consumed");
22475    }
22476
22477    #[test]
22478    fn replayed_intermediate_retry_remains_pending_across_restarts() {
22479        let history = completed_retry_activity_history()
22480            .into_iter()
22481            .take(3)
22482            .collect::<Vec<_>>();
22483
22484        for _restart in 0..2 {
22485            let ctx = workflow_context(history.clone());
22486            let mut call =
22487                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22488            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22489            assert!(matches!(
22490                call.as_mut().poll(&mut task_context),
22491                Poll::Pending
22492            ));
22493            assert!(ctx.take_commands().expect("commands").is_empty());
22494        }
22495    }
22496
22497    #[test]
22498    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
22499        let mut changed_queue = retry_activity_options();
22500        changed_queue.task_queue = Some("different-queue".to_string());
22501
22502        let mut changed_max_attempts = retry_activity_options();
22503        let retry_policy = changed_max_attempts
22504            .retry_policy
22505            .as_mut()
22506            .expect("retry policy");
22507        retry_policy.max_attempts = Some(4);
22508
22509        let mut changed_backoff = retry_activity_options();
22510        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
22511        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
22512            Duration::from_secs(3),
22513            Duration::from_secs(4),
22514        ]));
22515
22516        let mut changed_non_retryable_types = retry_activity_options();
22517        let retry_policy = changed_non_retryable_types
22518            .retry_policy
22519            .as_mut()
22520            .expect("retry policy");
22521        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
22522
22523        let mut changed_start_to_close = retry_activity_options();
22524        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
22525        let mut changed_schedule_to_start = retry_activity_options();
22526        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
22527        let mut changed_schedule_to_close = retry_activity_options();
22528        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
22529        let mut changed_heartbeat = retry_activity_options();
22530        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
22531
22532        let cases = [
22533            (changed_queue, "activity_task_queue_mismatch"),
22534            (changed_max_attempts, "activity_retry_policy_mismatch"),
22535            (changed_backoff, "activity_retry_policy_mismatch"),
22536            (
22537                changed_non_retryable_types,
22538                "activity_retry_policy_mismatch",
22539            ),
22540            (changed_start_to_close, "activity_retry_policy_mismatch"),
22541            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
22542            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
22543            (changed_heartbeat, "activity_retry_policy_mismatch"),
22544        ];
22545
22546        for (options, expected_reason) in cases {
22547            let ctx = workflow_context(completed_retry_activity_history());
22548            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
22549            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22550            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22551                call.as_mut().poll(&mut task_context)
22552            else {
22553                panic!("changed activity options must fail replay");
22554            };
22555            assert_eq!(failure.reason, expected_reason);
22556            assert_eq!(failure.sequence, Some(1));
22557            assert!(ctx.take_commands().expect("commands").is_empty());
22558        }
22559    }
22560
22561    #[test]
22562    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
22563        let cases = [
22564            (
22565                "execution_mode",
22566                json!("local"),
22567                "activity_execution_mode_mismatch",
22568            ),
22569            (
22570                "snapshot_version",
22571                json!(2),
22572                "activity_retry_policy_mismatch",
22573            ),
22574        ];
22575
22576        for (field, value, expected_reason) in cases {
22577            let mut history = completed_retry_activity_history();
22578            let activity = history[0].payload["activity"]
22579                .as_object_mut()
22580                .expect("activity snapshot");
22581            if field == "execution_mode" {
22582                activity.insert(field.to_string(), value);
22583            } else {
22584                activity["retry_policy"]
22585                    .as_object_mut()
22586                    .expect("retry snapshot")
22587                    .insert(field.to_string(), value);
22588            }
22589
22590            let ctx = workflow_context(history);
22591            let mut call =
22592                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22593            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22594            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22595                call.as_mut().poll(&mut task_context)
22596            else {
22597                panic!("changed {field} must fail replay");
22598            };
22599            assert_eq!(failure.reason, expected_reason);
22600            assert_eq!(failure.sequence, Some(1));
22601            assert!(ctx.take_commands().expect("commands").is_empty());
22602        }
22603    }
22604
22605    #[test]
22606    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
22607        for (nested, field, value, terminal_only) in [
22608            (false, "execution_mode", json!("local"), false),
22609            (false, "local_activity", json!(true), false),
22610            (true, "local_activity", json!(true), false),
22611            (false, "local_activity", json!(true), true),
22612        ] {
22613            let mut history = completed_retry_activity_history();
22614            history[0]
22615                .payload
22616                .as_object_mut()
22617                .unwrap()
22618                .remove("activity");
22619            let event = if terminal_only {
22620                history.last_mut().unwrap()
22621            } else {
22622                &mut history[0]
22623            };
22624            if nested {
22625                event.payload["activity"] = json!({(field): value});
22626            } else {
22627                event.payload[field] = value;
22628            }
22629            let ctx = workflow_context(history);
22630            let mut call =
22631                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22632            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22633            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22634                call.as_mut().poll(&mut task_context)
22635            else {
22636                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
22637            };
22638            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
22639            assert_eq!(failure.sequence, Some(1));
22640            assert!(ctx.take_commands().expect("commands").is_empty());
22641        }
22642    }
22643
22644    #[test]
22645    fn activity_history_rejects_conflicting_local_execution_markers() {
22646        let mut history = completed_retry_activity_history();
22647        history.last_mut().unwrap().payload["local_activity"] = json!(true);
22648        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
22649            .expect_err("remote schedule cannot become a local completion");
22650        assert!(
22651            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
22652            if reason == "activity_execution_mode_conflict")
22653        );
22654    }
22655
22656    #[test]
22657    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
22658        let mut history = completed_retry_activity_history();
22659        let activity = history[0].payload["activity"]
22660            .as_object_mut()
22661            .expect("activity snapshot");
22662        activity.remove("execution_mode");
22663        activity.remove("retry_policy");
22664
22665        let mut current = retry_activity_options();
22666        current.start_to_close_timeout = Some(Duration::from_secs(45));
22667        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
22668        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
22669        current.heartbeat_timeout = Some(Duration::from_secs(12));
22670
22671        let ctx = workflow_context(history);
22672        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
22673        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22674        assert!(matches!(
22675            call.as_mut().poll(&mut task_context),
22676            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22677        ));
22678        assert!(ctx.take_commands().expect("commands").is_empty());
22679        ctx.ensure_history_consumed().expect("history consumed");
22680    }
22681
22682    #[test]
22683    fn terminal_activity_failed_after_start_returns_typed_failure() {
22684        let history = vec![
22685            history_event(
22686                "ActivityScheduled",
22687                json!({
22688                    "sequence": 1,
22689                    "activity_type": "flaky",
22690                    "activity_execution_id": "act-terminal",
22691                    "activity": {
22692                        "id": "act-terminal",
22693                        "sequence": 1,
22694                        "type": "flaky",
22695                        "queue": "critical-activities",
22696                        "retry_policy": {
22697                            "snapshot_version": 1,
22698                            "max_attempts": 3,
22699                            "backoff_seconds": [2, 4],
22700                            "non_retryable_error_types": ["PermanentError"]
22701                        }
22702                    }
22703                }),
22704            ),
22705            history_event(
22706                "ActivityStarted",
22707                json!({
22708                    "sequence": 1,
22709                    "activity_type": "flaky",
22710                    "activity_execution_id": "act-terminal",
22711                    "activity_attempt_id": "attempt-1",
22712                    "attempt_number": 1
22713                }),
22714            ),
22715            history_event(
22716                "ActivityFailed",
22717                json!({
22718                    "sequence": 1,
22719                    "activity_type": "flaky",
22720                    "activity_execution_id": "act-terminal",
22721                    "activity_attempt_id": "attempt-1",
22722                    "attempt_number": 1,
22723                    "failure_id": "failure-terminal",
22724                    "failure_category": "activity",
22725                    "exception_type": "PermanentError",
22726                    "message": "cannot retry",
22727                    "non_retryable": true
22728                }),
22729            ),
22730        ];
22731        let ctx = workflow_context(history);
22732        let mut call =
22733            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22734        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22735
22736        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22737            call.as_mut().poll(&mut task_context)
22738        else {
22739            panic!("terminal ActivityFailed must settle the activity future");
22740        };
22741        assert_eq!(failure.kind, ActivityFailureKind::Failed);
22742        assert_eq!(
22743            failure.activity_execution_id.as_deref(),
22744            Some("act-terminal")
22745        );
22746        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
22747        assert!(failure.non_retryable);
22748        assert!(ctx.take_commands().expect("commands").is_empty());
22749        ctx.ensure_history_consumed().expect("history consumed");
22750    }
22751
22752    #[test]
22753    fn activity_terminal_events_return_machine_readable_failures() {
22754        let cases = [
22755            (
22756                "ActivityFailed",
22757                json!({
22758                    "sequence": 1,
22759                    "activity_type": "charge-card",
22760                    "activity_execution_id": "act-1",
22761                    "activity_attempt_id": "attempt-2",
22762                    "attempt_number": 2,
22763                    "failure_id": "failure-1",
22764                    "failure_category": "activity",
22765                    "exception_type": "PaymentDeclined",
22766                    "exception_class": "payments.PaymentDeclined",
22767                    "message": "card declined",
22768                    "non_retryable": true
22769                }),
22770                ActivityFailureKind::Failed,
22771                "activity",
22772            ),
22773            (
22774                "ActivityCancelled",
22775                json!({
22776                    "sequence": 1,
22777                    "activity_type": "charge-card",
22778                    "activity_execution_id": "act-1",
22779                    "activity_attempt_id": "attempt-1"
22780                }),
22781                ActivityFailureKind::Cancelled,
22782                "cancelled",
22783            ),
22784        ];
22785
22786        for (event_type, payload, expected_kind, expected_reason) in cases {
22787            let ctx = workflow_context(vec![history_event(event_type, payload)]);
22788            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
22789            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22790            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22791                call.as_mut().poll(&mut task_context)
22792            else {
22793                panic!("expected terminal activity failure");
22794            };
22795            assert_eq!(failure.kind, expected_kind);
22796            assert_eq!(failure.reason, expected_reason);
22797            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
22798            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
22799        }
22800    }
22801
22802    #[test]
22803    fn every_activity_timeout_class_is_typed() {
22804        for timeout_kind in [
22805            "start_to_close",
22806            "schedule_to_start",
22807            "schedule_to_close",
22808            "heartbeat",
22809        ] {
22810            let ctx = workflow_context(vec![history_event(
22811                "ActivityTimedOut",
22812                json!({
22813                    "sequence": 1,
22814                    "activity_type": "slow",
22815                    "activity_execution_id": "act-timeout",
22816                    "activity_attempt_id": "attempt-timeout",
22817                    "failure_category": "timeout",
22818                    "timeout_kind": timeout_kind,
22819                    "message": "deadline expired"
22820                }),
22821            )]);
22822            let mut call = Box::pin(ctx.activity("slow", json!([])));
22823            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22824            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22825                call.as_mut().poll(&mut task_context)
22826            else {
22827                panic!("expected timeout failure");
22828            };
22829            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
22830            assert_eq!(failure.reason, timeout_kind);
22831            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
22832            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
22833        }
22834    }
22835
22836    #[test]
22837    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
22838        let ctx = workflow_context(Vec::new());
22839        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
22840        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22841
22842        assert!(matches!(
22843            sleep.as_mut().poll(&mut task_context),
22844            Poll::Pending
22845        ));
22846        assert!(matches!(
22847            sleep.as_mut().poll(&mut task_context),
22848            Poll::Pending
22849        ));
22850
22851        let commands = ctx.take_commands().expect("timer command");
22852        assert_eq!(
22853            commands,
22854            vec![json!({
22855                "type": "start_timer",
22856                "delay_seconds": 2,
22857            })]
22858        );
22859    }
22860
22861    #[test]
22862    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
22863        let history = vec![
22864            history_event(
22865                "TimerScheduled",
22866                json!({
22867                    "sequence": 1,
22868                    "timer_id": "timer-1",
22869                    "delay_seconds": 5,
22870                    "fire_at": "2026-07-11T12:00:05Z",
22871                }),
22872            ),
22873            history_event(
22874                "TimerFired",
22875                json!({
22876                    "sequence": 1,
22877                    "timer_id": "timer-1",
22878                    "delay_seconds": 5,
22879                    "fire_at": "2026-07-11T12:00:05Z",
22880                    "fired_at": "2026-07-11T12:00:05Z",
22881                }),
22882            ),
22883        ];
22884
22885        for _restart in 0..2 {
22886            let ctx = workflow_context(history.clone());
22887            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
22888            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22889            assert!(matches!(
22890                sleep.as_mut().poll(&mut task_context),
22891                Poll::Ready(Ok(()))
22892            ));
22893            assert!(ctx.take_commands().expect("commands").is_empty());
22894            ctx.ensure_history_consumed().expect("history consumed");
22895        }
22896    }
22897
22898    #[test]
22899    fn workflow_sleep_rejects_changed_delay_during_replay() {
22900        let ctx = workflow_context(vec![
22901            history_event(
22902                "TimerScheduled",
22903                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22904            ),
22905            history_event(
22906                "TimerFired",
22907                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22908            ),
22909        ]);
22910        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
22911        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22912
22913        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22914            sleep.as_mut().poll(&mut task_context)
22915        else {
22916            panic!("changed timer delay must be rejected");
22917        };
22918        assert_eq!(failure.reason, "timer_delay_mismatch");
22919        assert_eq!(failure.sequence, Some(1));
22920    }
22921
22922    #[test]
22923    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
22924        let ctx = workflow_context(Vec::new());
22925        let mut wait = Box::pin(
22926            ctx.wait_condition(
22927                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
22928                    .timeout(Duration::from_millis(60_001)),
22929                || Ok(false),
22930            ),
22931        );
22932        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22933
22934        assert!(matches!(
22935            wait.as_mut().poll(&mut task_context),
22936            Poll::Pending
22937        ));
22938        assert!(matches!(
22939            wait.as_mut().poll(&mut task_context),
22940            Poll::Pending
22941        ));
22942        assert_eq!(
22943            ctx.take_commands().expect("condition command"),
22944            vec![json!({
22945                "type": "open_condition_wait",
22946                "condition_wait_occurrence_id": "rust:condition-wait:0",
22947                "condition_key": "approval.ready",
22948                "condition_definition_fingerprint": "sha256:approval-v1",
22949                "timeout_seconds": 61,
22950            })]
22951        );
22952    }
22953
22954    #[test]
22955    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
22956        let ctx = workflow_context(Vec::new());
22957        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
22958        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22959        assert!(matches!(
22960            satisfied.as_mut().poll(&mut task_context),
22961            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22962        ));
22963
22964        let mut timed_out = Box::pin(wait_condition!(
22965            ctx,
22966            "no-wait",
22967            timeout: Duration::ZERO,
22968            || Ok(false),
22969        ));
22970        assert!(matches!(
22971            timed_out.as_mut().poll(&mut task_context),
22972            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22973        ));
22974        assert!(ctx.take_commands().expect("commands").is_empty());
22975    }
22976
22977    #[test]
22978    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
22979        let signal_history = vec![
22980            history_event(
22981                "ConditionWaitOpened",
22982                json!({
22983                    "sequence": 4,
22984                    "condition_wait_id": "condition:4",
22985                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22986                    "condition_key": "approval",
22987                    "condition_definition_fingerprint": "sha256:approval-v1",
22988                    "timeout_seconds": 30,
22989                }),
22990            ),
22991            history_event(
22992                "SignalReceived",
22993                json!({
22994                    "workflow_sequence": 4,
22995                    "signal_name": "approve",
22996                    "arguments": fixture_envelope(json!(["Ada"])),
22997                }),
22998            ),
22999        ];
23000        for _worker_before_or_after_restart in 0..2 {
23001            let ctx = workflow_context(signal_history.clone());
23002            let predicate_ctx = ctx.clone();
23003            let mut wait = Box::pin(
23004                ctx.wait_condition(
23005                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
23006                        .timeout(Duration::from_secs(30)),
23007                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
23008                ),
23009            );
23010            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23011            assert!(matches!(
23012                wait.as_mut().poll(&mut task_context),
23013                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23014            ));
23015            assert!(ctx.take_commands().expect("commands").is_empty());
23016            ctx.ensure_history_consumed().expect("condition consumed");
23017        }
23018
23019        let update_history = vec![
23020            history_event(
23021                "ConditionWaitOpened",
23022                json!({
23023                    "sequence": 7,
23024                    "condition_wait_id": "condition:7",
23025                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23026                    "condition_key": "update-approval",
23027                    "condition_definition_fingerprint": "sha256:update-approval-v1",
23028                }),
23029            ),
23030            history_event(
23031                "UpdateApplied",
23032                json!({
23033                    "sequence": 7,
23034                    "update_id": "update-1",
23035                    "update_name": "approve",
23036                    "arguments": fixture_envelope(json!([true])),
23037                }),
23038            ),
23039        ];
23040        let ctx = workflow_context(update_history);
23041        let predicate_ctx = ctx.clone();
23042        let mut wait = Box::pin(ctx.wait_condition(
23043            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
23044            move || {
23045                Ok(predicate_ctx
23046                    .updates("approve")?
23047                    .first()
23048                    .and_then(|arguments| arguments.first())
23049                    .and_then(Value::as_bool)
23050                    == Some(true))
23051            },
23052        ));
23053        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23054        assert!(matches!(
23055            wait.as_mut().poll(&mut task_context),
23056            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23057        ));
23058        assert!(ctx.take_commands().expect("commands").is_empty());
23059        ctx.ensure_history_consumed().expect("condition consumed");
23060    }
23061
23062    #[test]
23063    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
23064        let open_history = vec![
23065            history_event(
23066                "ConditionWaitOpened",
23067                json!({
23068                    "sequence": 3,
23069                    "condition_wait_id": "condition:3",
23070                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23071                    "condition_key": "two-votes",
23072                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23073                    "timeout_seconds": 120,
23074                }),
23075            ),
23076            history_event(
23077                "SignalReceived",
23078                json!({
23079                    "workflow_sequence": 3,
23080                    "signal_name": "vote",
23081                    "arguments": fixture_envelope(json!(["first"])),
23082                }),
23083            ),
23084        ];
23085        for _worker_before_or_after_restart in 0..2 {
23086            let ctx = workflow_context(open_history.clone());
23087            let predicate_ctx = ctx.clone();
23088            let mut wait = Box::pin(
23089                ctx.wait_condition(
23090                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23091                        .timeout(Duration::from_secs(120)),
23092                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23093                ),
23094            );
23095            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23096            assert!(matches!(
23097                wait.as_mut().poll(&mut task_context),
23098                Poll::Pending
23099            ));
23100            assert_eq!(
23101                ctx.take_commands().expect("reopened condition"),
23102                vec![json!({
23103                    "type": "open_condition_wait",
23104                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23105                    "condition_key": "two-votes",
23106                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23107                    "timeout_seconds": 120,
23108                })]
23109            );
23110        }
23111
23112        let satisfied_ctx = workflow_context(vec![
23113            history_event(
23114                "ConditionWaitOpened",
23115                json!({
23116                    "sequence": 5,
23117                    "condition_wait_id": "condition:5",
23118                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23119                    "condition_key": "approval",
23120                    "condition_definition_fingerprint": "sha256:approval-v1",
23121                }),
23122            ),
23123            history_event(
23124                "ConditionWaitSatisfied",
23125                json!({
23126                    "sequence": 5,
23127                    "condition_wait_id": "condition:5",
23128                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23129                    "condition_key": "approval",
23130                    "condition_definition_fingerprint": "sha256:approval-v1",
23131                }),
23132            ),
23133        ]);
23134        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
23135            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
23136            || Ok(false),
23137        ));
23138        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23139        assert!(matches!(
23140            satisfied.as_mut().poll(&mut task_context),
23141            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23142        ));
23143
23144        let timed_out_ctx = workflow_context(vec![
23145            history_event(
23146                "ConditionWaitOpened",
23147                json!({
23148                    "sequence": 8,
23149                    "condition_wait_id": "condition:8",
23150                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23151                    "condition_key": "approval-timeout",
23152                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
23153                    "timeout_seconds": 5,
23154                }),
23155            ),
23156            history_event(
23157                "TimerScheduled",
23158                json!({
23159                    "sequence": 9,
23160                    "timer_id": "condition-timer:9",
23161                    "timer_kind": "condition_timeout",
23162                    "condition_wait_id": "condition:8",
23163                    "delay_seconds": 5,
23164                }),
23165            ),
23166            history_event(
23167                "TimerFired",
23168                json!({
23169                    "sequence": 9,
23170                    "timer_id": "condition-timer:9",
23171                    "timer_kind": "condition_timeout",
23172                    "condition_wait_id": "condition:8",
23173                    "delay_seconds": 5,
23174                }),
23175            ),
23176        ]);
23177        let mut timed_out = Box::pin(
23178            timed_out_ctx.wait_condition(
23179                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
23180                    .timeout(Duration::from_secs(5)),
23181                || Ok(true),
23182            ),
23183        );
23184        assert!(matches!(
23185            timed_out.as_mut().poll(&mut task_context),
23186            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
23187        ));
23188    }
23189
23190    #[test]
23191    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
23192        let ctx = workflow_context(reopened_selection_condition_history());
23193        {
23194            let state = ctx.state.lock().unwrap();
23195            assert!(matches!(
23196                selection_member_recorded_command(&state, 2),
23197                Some(RecordedCommand::ConditionWait {
23198                    sequence: 3,
23199                    result: None,
23200                    ..
23201                })
23202            ));
23203        }
23204        let mut selected = Box::pin(ctx.select_keyed(vec![
23205            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
23206            (
23207                "votes",
23208                ParallelOperation::condition(
23209                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
23210                    || Ok(true),
23211                ),
23212            ),
23213        ]));
23214        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23215        assert!(selected.as_mut().poll(&mut task_context).is_pending());
23216        assert!(
23217            ctx.take_commands().unwrap().is_empty(),
23218            "true predicate must not reopen the recorded wait"
23219        );
23220        ctx.ensure_history_consumed()
23221            .expect("physical reopens are consumed while canonical selection is pending");
23222    }
23223
23224    #[test]
23225    fn reopened_selection_condition_replays_its_latest_physical_winner() {
23226        for (terminal_type, acknowledge_timeout) in [
23227            ("ConditionWaitSatisfied", false),
23228            ("ConditionWaitTimedOut", false),
23229            ("TimerFired", false),
23230            ("TimerFired", true),
23231        ] {
23232            let mut history = reopened_selection_condition_history();
23233            let original_identity = history[1].payload["condition_wait_id"].clone();
23234            let uses_timer = terminal_type == "TimerFired";
23235            let mut resolution_payload = history[3].payload.clone();
23236            if uses_timer {
23237                for event in &mut history[1..] {
23238                    event.payload["timeout_seconds"] = json!(3);
23239                }
23240                resolution_payload = history[3].payload.clone();
23241                resolution_payload["timer_kind"] = json!("condition_timeout");
23242                resolution_payload["timer_id"] = json!("condition-timeout-3");
23243                resolution_payload["delay_seconds"] = json!(3);
23244                history.push(history_event("TimerScheduled", resolution_payload.clone()));
23245            }
23246            let mut resolution = history_event(terminal_type, resolution_payload.clone());
23247            resolution
23248                .raw
23249                .insert("id".into(), json!("latest-condition-resolution"));
23250            history.push(resolution);
23251            history.push(history_event(
23252                "SelectionResolved",
23253                json!({
23254                    "selection_group_id": "select-calls:1:2",
23255                    "selection_group_base_sequence": 1,
23256                    "selection_group_size": 2,
23257                    "member_key": "votes",
23258                    "member_index": 1,
23259                    "member_base_sequence": 2,
23260                    "member_size": 1,
23261                    "operation_kind": "condition",
23262                    "operation_identity": original_identity,
23263                    "outcome": "completed",
23264                    "resolution_event_id": "latest-condition-resolution",
23265                    "resolution_event_type": terminal_type,
23266                }),
23267            ));
23268            if acknowledge_timeout {
23269                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
23270            }
23271            let ctx = workflow_context(history);
23272            let mut selected = Box::pin(ctx.select_keyed(vec![
23273                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
23274                (
23275                    "votes",
23276                    ParallelOperation::condition(
23277                        if uses_timer {
23278                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23279                                .timeout(Duration::from_secs(3))
23280                        } else {
23281                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23282                        },
23283                        || Ok(true),
23284                    ),
23285                ),
23286            ]));
23287            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23288            match selected.as_mut().poll(&mut task_context) {
23289                Poll::Ready(Ok(result)) => {
23290                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
23291                    let expected = if terminal_type == "ConditionWaitSatisfied" {
23292                        ConditionWaitResult::Satisfied
23293                    } else {
23294                        ConditionWaitResult::TimedOut
23295                    };
23296                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
23297                }
23298                other => panic!("latest physical winner must replay: {other:?}"),
23299            }
23300            assert!(ctx.take_commands().unwrap().is_empty());
23301            ctx.ensure_history_consumed()
23302                .expect("winner history consumed");
23303        }
23304    }
23305
23306    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
23307        let fixture: Value = serde_json::from_str(include_str!(
23308            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
23309        ))
23310        .expect("grouped condition fixture");
23311        fixture["history"]
23312            .as_array()
23313            .unwrap()
23314            .iter()
23315            .map(|event| {
23316                let mut payload = event["payload"].clone();
23317                let index = payload["parallel_group_index"].as_u64().unwrap();
23318                payload["parallel_group_id"] = json!("select-calls:1:2");
23319                payload["parallel_group_mode"] = json!("select");
23320                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
23321                payload["selection_member_index"] = json!(index);
23322                payload["selection_member_base_sequence"] = json!(index + 1);
23323                payload["selection_member_size"] = json!(1);
23324                payload["selection_member_kind"] =
23325                    json!(if index == 0 { "timer" } else { "condition" });
23326                history_event(event["event_type"].as_str().unwrap(), payload)
23327            })
23328            .collect()
23329    }
23330
23331    #[test]
23332    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
23333        let fixture: Value = serde_json::from_str(include_str!(
23334            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
23335        ))
23336        .expect("grouped condition fixture");
23337        let original = fixture["history"].as_array().expect("fixture history");
23338        let decode = |events: &[Value]| {
23339            let history = events
23340                .iter()
23341                .map(|event| {
23342                    history_event(
23343                        event["event_type"].as_str().unwrap(),
23344                        event["payload"].clone(),
23345                    )
23346                })
23347                .collect::<Vec<_>>();
23348            recorded_commands(
23349                &history,
23350                DEFAULT_CODEC,
23351                WorkflowIdentity {
23352                    workflow_id: None,
23353                    run_id: None,
23354                },
23355            )
23356        };
23357        assert!(decode(original).is_ok());
23358        for field in [
23359            "condition_wait_occurrence_id",
23360            "condition_key",
23361            "condition_definition_fingerprint",
23362            "timeout_seconds",
23363            "parallel_group_id",
23364            "parallel_group_size",
23365            "parallel_group_index",
23366        ] {
23367            let mut changed = original.clone();
23368            changed[3]["payload"][field] = match field {
23369                "timeout_seconds" | "parallel_group_size" => json!(30),
23370                "parallel_group_index" => json!(0),
23371                _ => json!("changed"),
23372            };
23373            assert!(
23374                decode(&changed).is_err(),
23375                "reopen must reject changed {field}"
23376            );
23377        }
23378        let mut unsettled = original.clone();
23379        unsettled.remove(2);
23380        assert!(
23381            decode(&unsettled).is_err(),
23382            "physical predecessor must be resolved"
23383        );
23384        let mut timed_out = original.clone();
23385        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
23386        assert!(decode(&timed_out).is_err(), "timeout is terminal");
23387        let mut late_resolution = original.clone();
23388        late_resolution.swap(2, 3);
23389        assert!(
23390            decode(&late_resolution).is_err(),
23391            "later history cannot authorize a reopen"
23392        );
23393    }
23394
23395    #[test]
23396    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
23397        let history = vec![
23398            history_event(
23399                "ConditionWaitOpened",
23400                json!({
23401                    "sequence": 3,
23402                    "condition_wait_id": "condition:3",
23403                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23404                    "condition_key": "two-votes",
23405                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23406                }),
23407            ),
23408            history_event(
23409                "SignalReceived",
23410                json!({
23411                    "workflow_sequence": 3,
23412                    "signal_name": "vote",
23413                    "arguments": fixture_envelope(json!(["first"])),
23414                }),
23415            ),
23416            history_event(
23417                "ConditionWaitSatisfied",
23418                json!({
23419                    "sequence": 3,
23420                    "condition_wait_id": "condition:3",
23421                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23422                    "condition_key": "two-votes",
23423                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23424                }),
23425            ),
23426            history_event(
23427                "ConditionWaitOpened",
23428                json!({
23429                    "sequence": 5,
23430                    "condition_wait_id": "condition:5",
23431                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23432                    "condition_key": "two-votes",
23433                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23434                }),
23435            ),
23436            history_event(
23437                "SignalReceived",
23438                json!({
23439                    "workflow_sequence": 5,
23440                    "signal_name": "vote",
23441                    "arguments": fixture_envelope(json!(["second"])),
23442                }),
23443            ),
23444            history_event(
23445                "ConditionWaitSatisfied",
23446                json!({
23447                    "sequence": 5,
23448                    "condition_wait_id": "condition:5",
23449                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23450                    "condition_key": "two-votes",
23451                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23452                }),
23453            ),
23454        ];
23455        for _cold_worker_or_restart in 0..2 {
23456            let ctx = workflow_context(history.clone());
23457            let predicate_ctx = ctx.clone();
23458            let mut wait = Box::pin(ctx.wait_condition(
23459                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
23460                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23461            ));
23462            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23463
23464            assert!(matches!(
23465                wait.as_mut().poll(&mut task_context),
23466                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23467            ));
23468            assert!(ctx.take_commands().expect("commands").is_empty());
23469            ctx.ensure_history_consumed()
23470                .expect("every physical wait-open is consumed");
23471        }
23472    }
23473
23474    #[test]
23475    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
23476        let history = vec![
23477            history_event(
23478                "ConditionWaitOpened",
23479                json!({
23480                    "sequence": 3,
23481                    "condition_wait_id": "condition:3",
23482                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23483                    "condition_key": "approved",
23484                    "condition_definition_fingerprint": "sha256:approved-v1",
23485                }),
23486            ),
23487            history_event(
23488                "UpdateApplied",
23489                json!({
23490                    "sequence": 3,
23491                    "update_id": "update-1",
23492                    "update_name": "approve",
23493                    "arguments": fixture_envelope(json!([false])),
23494                }),
23495            ),
23496            history_event(
23497                "ConditionWaitOpened",
23498                json!({
23499                    "sequence": 5,
23500                    "condition_wait_id": "condition:5",
23501                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23502                    "condition_key": "approved",
23503                    "condition_definition_fingerprint": "sha256:approved-v1",
23504                }),
23505            ),
23506            history_event(
23507                "UpdateApplied",
23508                json!({
23509                    "sequence": 5,
23510                    "update_id": "update-2",
23511                    "update_name": "approve",
23512                    "arguments": fixture_envelope(json!([true])),
23513                }),
23514            ),
23515        ];
23516
23517        for _cold_worker_or_restart in 0..2 {
23518            let ctx = workflow_context(history.clone());
23519            let predicate_ctx = ctx.clone();
23520            let mut wait = Box::pin(ctx.wait_condition(
23521                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
23522                move || {
23523                    Ok(predicate_ctx
23524                        .updates("approve")?
23525                        .last()
23526                        .and_then(|arguments| arguments.first())
23527                        .and_then(Value::as_bool)
23528                        == Some(true))
23529                },
23530            ));
23531            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23532
23533            assert!(matches!(
23534                wait.as_mut().poll(&mut task_context),
23535                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23536            ));
23537            assert!(ctx.take_commands().expect("commands").is_empty());
23538            ctx.ensure_history_consumed()
23539                .expect("every update-driven reopen is consumed");
23540        }
23541    }
23542
23543    #[test]
23544    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
23545        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
23546            ("shared", "sha256:first", "shared", "sha256:second"),
23547            ("first", "sha256:shared", "second", "sha256:shared"),
23548            ("shared", "sha256:shared", "shared", "sha256:shared"),
23549            ("first", "sha256:first", "second", "sha256:second"),
23550        ] {
23551            let history = vec![
23552                history_event(
23553                    "ConditionWaitOpened",
23554                    json!({
23555                        "sequence": 3,
23556                        "condition_wait_id": "condition:3",
23557                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23558                        "condition_key": first_key,
23559                        "condition_definition_fingerprint": first_fingerprint,
23560                    }),
23561                ),
23562                history_event(
23563                    "ConditionWaitSatisfied",
23564                    json!({
23565                        "sequence": 3,
23566                        "condition_wait_id": "condition:3",
23567                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23568                        "condition_key": first_key,
23569                        "condition_definition_fingerprint": first_fingerprint,
23570                    }),
23571                ),
23572                history_event(
23573                    "ConditionWaitOpened",
23574                    json!({
23575                        "sequence": 4,
23576                        "condition_wait_id": "condition:4",
23577                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23578                        "condition_key": second_key,
23579                        "condition_definition_fingerprint": second_fingerprint,
23580                    }),
23581                ),
23582                history_event(
23583                    "ConditionWaitSatisfied",
23584                    json!({
23585                        "sequence": 4,
23586                        "condition_wait_id": "condition:4",
23587                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23588                        "condition_key": second_key,
23589                        "condition_definition_fingerprint": second_fingerprint,
23590                    }),
23591                ),
23592            ];
23593            for _cold_worker_or_restart in 0..2 {
23594                let ctx = workflow_context(history.clone());
23595                let mut task_context = TaskContext::from_waker(noop_waker_ref());
23596                let mut first = Box::pin(ctx.wait_condition(
23597                    ConditionWaitOptions::new(first_key, first_fingerprint),
23598                    || Ok(false),
23599                ));
23600                assert!(matches!(
23601                    first.as_mut().poll(&mut task_context),
23602                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23603                ));
23604
23605                let mut second = Box::pin(ctx.wait_condition(
23606                    ConditionWaitOptions::new(second_key, second_fingerprint),
23607                    || Ok(false),
23608                ));
23609                assert!(matches!(
23610                    second.as_mut().poll(&mut task_context),
23611                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23612                ));
23613                assert!(ctx.take_commands().expect("commands").is_empty());
23614                ctx.ensure_history_consumed()
23615                    .expect("each authored wait consumes one occurrence");
23616            }
23617        }
23618    }
23619
23620    #[test]
23621    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
23622        fn worker() -> Worker {
23623            let client = Client::new("http://127.0.0.1:8080").expect("client");
23624            let mut worker = Worker::new(client, "rust-workers");
23625            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
23626                let mut outcomes = Vec::new();
23627                for _ in 0..2 {
23628                    outcomes.push(
23629                        ctx.wait_condition(
23630                            ConditionWaitOptions::new("shared", "sha256:shared"),
23631                            || Ok(false),
23632                        )
23633                        .await?,
23634                    );
23635                }
23636                Ok(json!(outcomes))
23637            });
23638            worker
23639        }
23640
23641        let task = workflow_task(
23642            "rust.condition-loop",
23643            vec![
23644                history_event(
23645                    "ConditionWaitOpened",
23646                    json!({
23647                        "sequence": 1,
23648                        "condition_wait_id": "condition:1",
23649                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23650                        "condition_key": "shared",
23651                        "condition_definition_fingerprint": "sha256:shared",
23652                    }),
23653                ),
23654                history_event(
23655                    "ConditionWaitSatisfied",
23656                    json!({
23657                        "sequence": 1,
23658                        "condition_wait_id": "condition:1",
23659                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23660                        "condition_key": "shared",
23661                        "condition_definition_fingerprint": "sha256:shared",
23662                    }),
23663                ),
23664                history_event(
23665                    "ConditionWaitOpened",
23666                    json!({
23667                        "sequence": 2,
23668                        "condition_wait_id": "condition:2",
23669                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23670                        "condition_key": "shared",
23671                        "condition_definition_fingerprint": "sha256:shared",
23672                    }),
23673                ),
23674                history_event(
23675                    "ConditionWaitSatisfied",
23676                    json!({
23677                        "sequence": 2,
23678                        "condition_wait_id": "condition:2",
23679                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23680                        "condition_key": "shared",
23681                        "condition_definition_fingerprint": "sha256:shared",
23682                    }),
23683                ),
23684            ],
23685            DEFAULT_CODEC,
23686        );
23687
23688        for _cold_worker_or_restart in 0..2 {
23689            let commands = worker()
23690                .execute_workflow_task(task.clone())
23691                .expect("adjacent loop waits replay deterministically");
23692            assert_eq!(commands.len(), 1);
23693            assert_eq!(commands[0]["type"], "complete_workflow");
23694            assert_eq!(
23695                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23696                json!(["satisfied", "satisfied"])
23697            );
23698        }
23699    }
23700
23701    #[test]
23702    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
23703        let history = vec![history_event(
23704            "ConditionWaitOpened",
23705            json!({
23706                "sequence": 12,
23707                "condition_wait_id": "condition:12",
23708                "condition_wait_occurrence_id": "rust:condition-wait:0",
23709                "condition_key": "approval",
23710                "condition_definition_fingerprint": "sha256:approval-v1",
23711                "timeout_seconds": 30,
23712            }),
23713        )];
23714        for (options, expected_reason) in [
23715            (
23716                ConditionWaitOptions::new("changed", "sha256:approval-v1")
23717                    .timeout(Duration::from_secs(30)),
23718                "condition_wait_key_mismatch",
23719            ),
23720            (
23721                ConditionWaitOptions::new("approval", "sha256:approval-v2")
23722                    .timeout(Duration::from_secs(30)),
23723                "condition_wait_predicate_mismatch",
23724            ),
23725            (
23726                ConditionWaitOptions::new("approval", "sha256:approval-v1")
23727                    .timeout(Duration::from_secs(29)),
23728                "condition_wait_timeout_mismatch",
23729            ),
23730        ] {
23731            let ctx = workflow_context(history.clone());
23732            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
23733            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23734            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23735                wait.as_mut().poll(&mut task_context)
23736            else {
23737                panic!("changed condition definition must fail replay");
23738            };
23739            assert_eq!(failure.reason, expected_reason);
23740            assert_eq!(failure.sequence, Some(12));
23741        }
23742    }
23743
23744    #[test]
23745    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
23746        let error = WorkflowState::new(
23747            vec![history_event(
23748                "ConditionWaitOpened",
23749                json!({
23750                    "sequence": 12,
23751                    "condition_wait_id": "condition:12",
23752                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23753                    "condition_key": "approval",
23754                }),
23755            )],
23756            "rust-workers".to_string(),
23757            DEFAULT_CODEC.to_string(),
23758            None,
23759        )
23760        .expect_err("condition history without a predicate fingerprint must fail");
23761
23762        assert!(matches!(
23763            error,
23764            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23765                if reason == "condition_wait_predicate_fingerprint_missing"
23766        ));
23767    }
23768
23769    #[test]
23770    fn condition_wait_history_requires_authored_occurrence_identity() {
23771        let error = WorkflowState::new(
23772            vec![history_event(
23773                "ConditionWaitOpened",
23774                json!({
23775                    "sequence": 12,
23776                    "condition_wait_id": "condition:12",
23777                    "condition_key": "approval",
23778                    "condition_definition_fingerprint": "sha256:approval-v1",
23779                }),
23780            )],
23781            "rust-workers".to_string(),
23782            DEFAULT_CODEC.to_string(),
23783            None,
23784        )
23785        .expect_err("condition history without occurrence identity must fail");
23786
23787        assert!(matches!(
23788            error,
23789            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23790                if reason == "condition_wait_occurrence_id_missing"
23791        ));
23792    }
23793
23794    #[test]
23795    fn typed_search_attribute_updates_validate_emit_and_replay() {
23796        let update = SearchAttributeUpdate::new()
23797            .keyword("OrderStatus", " waiting ")
23798            .expect("keyword")
23799            .int("Attempt", 3)
23800            .expect("int")
23801            .bool("Escalated", false)
23802            .expect("bool")
23803            .keyword_list("Regions", ["us-east", "eu-west"])
23804            .expect("list")
23805            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
23806            .expect("datetime")
23807            .delete("LegacyStatus")
23808            .expect("delete");
23809        let ctx = workflow_context(Vec::new());
23810        ctx.upsert_search_attributes(update.clone())
23811            .expect("typed update");
23812        assert_eq!(
23813            ctx.take_commands().expect("search-attribute command"),
23814            vec![json!({
23815                "type": "upsert_search_attributes",
23816                "attributes": {
23817                    "Attempt": 3,
23818                    "Escalated": false,
23819                    "LegacyStatus": null,
23820                    "OrderStatus": "waiting",
23821                    "Regions": ["us-east", "eu-west"],
23822                    "UpdatedAt": "2026-08-22T04:00:00Z",
23823                },
23824                "attribute_types": {
23825                    "Attempt": "int",
23826                    "Escalated": "bool",
23827                    "OrderStatus": "keyword",
23828                    "Regions": "keyword_list",
23829                    "UpdatedAt": "datetime",
23830                },
23831            })]
23832        );
23833
23834        let replay = workflow_context(vec![history_event(
23835            "SearchAttributesUpserted",
23836            json!({
23837                "sequence": 6,
23838                "attributes": {
23839                    "Attempt": 3,
23840                    "Escalated": false,
23841                    "LegacyStatus": null,
23842                    "OrderStatus": "waiting",
23843                    "Regions": ["us-east", "eu-west"],
23844                    "UpdatedAt": "2026-08-22T04:00:00Z",
23845                },
23846                "attribute_types": {
23847                    "Attempt": "int",
23848                    "Escalated": "bool",
23849                    "OrderStatus": "keyword",
23850                    "Regions": "keyword_list",
23851                    "UpdatedAt": "datetime",
23852                },
23853                "merged": {},
23854            }),
23855        )]);
23856        replay
23857            .upsert_search_attributes(update)
23858            .expect("matching update replays");
23859        assert!(replay.take_commands().expect("commands").is_empty());
23860        replay.ensure_history_consumed().expect("history consumed");
23861
23862        let type_drift = workflow_context(vec![history_event(
23863            "SearchAttributesUpserted",
23864            json!({
23865                "sequence": 7,
23866                "attributes": {"OrderStatus": "waiting"},
23867                "attribute_types": {"OrderStatus": "keyword"},
23868                "merged": {"OrderStatus": "waiting"},
23869            }),
23870        )]);
23871        let error = type_drift
23872            .upsert_search_attributes(
23873                SearchAttributeUpdate::new()
23874                    .string("OrderStatus", "waiting")
23875                    .expect("string update"),
23876            )
23877            .expect_err("same JSON value with a changed type must fail replay");
23878        assert!(matches!(
23879            error,
23880            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23881                if reason == "search_attribute_type_mismatch"
23882        ));
23883
23884        let malformed_types = WorkflowState::new(
23885            vec![history_event(
23886                "SearchAttributesUpserted",
23887                json!({
23888                    "sequence": 8,
23889                    "attributes": {"OrderStatus": "waiting"},
23890                    "attribute_types": {"OrderStatus": "unsupported"},
23891                    "merged": {"OrderStatus": "waiting"},
23892                }),
23893            )],
23894            "rust-workers".to_string(),
23895            DEFAULT_CODEC.to_string(),
23896            None,
23897        )
23898        .expect_err("unsupported search-attribute type metadata must fail");
23899        assert!(matches!(
23900            malformed_types,
23901            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23902                if reason == "search_attribute_types_malformed"
23903        ));
23904
23905        assert!(matches!(
23906            SearchAttributeUpdate::new().keyword("bad key", "value"),
23907            Err(SearchAttributeUpdateError::InvalidKey(_))
23908        ));
23909        assert!(matches!(
23910            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
23911            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
23912        ));
23913        assert!(matches!(
23914            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
23915            Err(SearchAttributeUpdateError::ValueTooLong { .. })
23916        ));
23917        assert!(matches!(
23918            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
23919            Err(SearchAttributeUpdateError::InvalidDateTime(_))
23920        ));
23921        assert!(matches!(
23922            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
23923            Err(Error::InvalidSearchAttributeUpdate(
23924                SearchAttributeUpdateError::Empty
23925            ))
23926        ));
23927    }
23928
23929    #[test]
23930    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
23931        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
23932        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
23933
23934        assert!(SearchAttributeUpdate::new()
23935            .string("AsciiDescription", ascii)
23936            .is_ok());
23937        assert!(SearchAttributeUpdate::new()
23938            .string("Utf8Description", utf8)
23939            .is_ok());
23940        assert!(matches!(
23941            SearchAttributeUpdate::new().string(
23942                "TooLongDescription",
23943                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
23944            ),
23945            Err(SearchAttributeUpdateError::ValueTooLong {
23946                kind: "string",
23947                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
23948                ..
23949            })
23950        ));
23951    }
23952
23953    #[test]
23954    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
23955        let lone_fire = WorkflowState::new(
23956            vec![history_event(
23957                "TimerFired",
23958                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23959            )],
23960            "rust-workers".to_string(),
23961            DEFAULT_CODEC.to_string(),
23962            None,
23963        )
23964        .expect_err("TimerFired requires TimerScheduled");
23965        assert!(matches!(
23966            lone_fire,
23967            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23968                if reason == "timer_schedule_missing_or_duplicate"
23969        ));
23970
23971        let wrong_identity = WorkflowState::new(
23972            vec![
23973                history_event(
23974                    "TimerScheduled",
23975                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23976                ),
23977                history_event(
23978                    "TimerFired",
23979                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23980                ),
23981            ],
23982            "rust-workers".to_string(),
23983            DEFAULT_CODEC.to_string(),
23984            None,
23985        )
23986        .expect_err("fire must match scheduled timer identity");
23987        assert!(matches!(
23988            wrong_identity,
23989            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23990                if reason == "timer_identity_mismatch"
23991        ));
23992
23993        let duplicate_fire = WorkflowState::new(
23994            vec![
23995                history_event(
23996                    "TimerScheduled",
23997                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23998                ),
23999                history_event(
24000                    "TimerFired",
24001                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24002                ),
24003                history_event(
24004                    "TimerFired",
24005                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24006                ),
24007            ],
24008            "rust-workers".to_string(),
24009            DEFAULT_CODEC.to_string(),
24010            None,
24011        )
24012        .expect_err("a durable timer cannot fire twice");
24013        assert!(matches!(
24014            duplicate_fire,
24015            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24016                if reason == "duplicate_timer_fire"
24017        ));
24018
24019        let wrong_fired_delay = WorkflowState::new(
24020            vec![
24021                history_event(
24022                    "TimerScheduled",
24023                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24024                ),
24025                history_event(
24026                    "TimerFired",
24027                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
24028                ),
24029            ],
24030            "rust-workers".to_string(),
24031            DEFAULT_CODEC.to_string(),
24032            None,
24033        )
24034        .expect_err("timer schedule and fire delays must agree");
24035        assert!(matches!(
24036            wrong_fired_delay,
24037            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24038                if reason == "timer_history_delay_mismatch"
24039        ));
24040    }
24041
24042    #[test]
24043    fn replay_rejects_activity_moved_before_recorded_timer() {
24044        let ctx = workflow_context(vec![
24045            history_event(
24046                "TimerScheduled",
24047                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24048            ),
24049            history_event(
24050                "TimerFired",
24051                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24052            ),
24053            history_event(
24054                "ActivityCompleted",
24055                json!({
24056                    "sequence": 2,
24057                    "activity_type": "after-timer",
24058                    "payload_codec": DEFAULT_CODEC,
24059                    "result": fixture_envelope(json!("done")),
24060                }),
24061            ),
24062        ]);
24063        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
24064        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24065
24066        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24067            activity.as_mut().poll(&mut task_context)
24068        else {
24069            panic!("reordered durable command must be rejected");
24070        };
24071        assert_eq!(failure.reason, "recorded_command_mismatch");
24072        assert_eq!(failure.sequence, Some(1));
24073        assert_eq!(failure.expected.as_deref(), Some("timer"));
24074        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
24075    }
24076
24077    #[test]
24078    fn workflow_context_emits_a_typed_named_signal_wait() {
24079        let ctx = workflow_context(Vec::new());
24080        let mut signal = Box::pin(ctx.wait_signal("finish"));
24081        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24082
24083        assert!(matches!(
24084            signal.as_mut().poll(&mut task_context),
24085            Poll::Pending
24086        ));
24087        assert_eq!(
24088            ctx.take_commands().expect("signal-wait command"),
24089            vec![json!({
24090                "type": "open_signal_wait",
24091                "signal_name": "finish",
24092            })]
24093        );
24094    }
24095
24096    #[test]
24097    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
24098        let ctx = workflow_context(Vec::new());
24099        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
24100        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24101
24102        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
24103        else {
24104            panic!("runtime-reserved signal should be rejected");
24105        };
24106        assert!(message.contains("reserved by the workflow runtime"));
24107        assert!(ctx.take_commands().expect("commands").is_empty());
24108    }
24109
24110    #[tokio::test]
24111    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
24112        let client = Client::builder("http://127.0.0.1:9")
24113            .build()
24114            .expect("client");
24115        let error = client
24116            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
24117            .await
24118            .expect_err("runtime-reserved signal should be rejected before transport");
24119
24120        assert!(
24121            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
24122        );
24123    }
24124
24125    #[test]
24126    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
24127        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24128            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24129                value.to_string(),
24130            )]))
24131            .expect("message payload");
24132            json!({
24133                "schema": MESSAGE_STREAM_SCHEMA,
24134                "stream_name": "orders",
24135                "message_id": message_id,
24136                "position": position,
24137                "payload_envelope": payload,
24138            })
24139        }
24140
24141        fn opened(sequence: u64) -> HistoryEvent {
24142            history_event(
24143                "SignalWaitOpened",
24144                json!({
24145                    "sequence": sequence,
24146                    "signal_name": MESSAGE_STREAM_SIGNAL,
24147                }),
24148            )
24149        }
24150
24151        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24152            history_event(
24153                "SignalApplied",
24154                json!({
24155                    "sequence": sequence,
24156                    "signal_name": MESSAGE_STREAM_SIGNAL,
24157                    "value": fixture_envelope(json!([delivery])),
24158                }),
24159            )
24160        }
24161
24162        fn received(delivery: Value) -> HistoryEvent {
24163            history_event(
24164                "SignalReceived",
24165                json!({
24166                    "signal_name": MESSAGE_STREAM_SIGNAL,
24167                    "arguments": fixture_envelope(json!([delivery])),
24168                    "payload_codec": DEFAULT_CODEC,
24169                }),
24170            )
24171        }
24172
24173        let client = Client::new("http://127.0.0.1:8080").expect("client");
24174        let mut worker = Worker::new(client, "rust-workers");
24175        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
24176            let messages = ctx.message_stream("orders")?.receive(2).await?;
24177            Ok(json!(messages
24178                .into_iter()
24179                .map(|message| message.message_id)
24180                .collect::<Vec<_>>()))
24181        });
24182
24183        let first = delivery("message-1", 1, "one");
24184        let second = delivery("message-2", 2, "two");
24185        let batch = worker
24186            .execute_workflow_task_decision(workflow_task(
24187                "rust.message-stream-batch",
24188                vec![
24189                    opened(1),
24190                    received(first.clone()),
24191                    applied(1, first.clone()),
24192                    received(first.clone()),
24193                    received(second),
24194                ],
24195                DEFAULT_CODEC,
24196            ))
24197            .expect("worker task consumes the available batch");
24198
24199        assert_eq!(batch.commands.len(), 1);
24200        assert_eq!(batch.commands[0]["type"], "complete_workflow");
24201        assert_eq!(
24202            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
24203                .expect("workflow result"),
24204            json!(["message-1", "message-2"])
24205        );
24206        assert_eq!(
24207            batch.message_stream_cursors,
24208            vec![json!({"stream_name": "orders", "through_position": 2})]
24209        );
24210        assert!(batch.message_stream_waits.is_empty());
24211
24212        let partial = worker
24213            .execute_workflow_task_decision(workflow_task(
24214                "rust.message-stream-batch",
24215                vec![opened(1), received(first.clone()), applied(1, first)],
24216                DEFAULT_CODEC,
24217            ))
24218            .expect("worker task returns without waiting for a missing second item");
24219        assert_eq!(partial.commands.len(), 1);
24220        assert_eq!(partial.commands[0]["type"], "complete_workflow");
24221        assert_eq!(
24222            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
24223                .expect("workflow result"),
24224            json!(["message-1"])
24225        );
24226        assert_eq!(
24227            partial.message_stream_cursors,
24228            vec![json!({"stream_name": "orders", "through_position": 1})]
24229        );
24230        assert!(partial.message_stream_waits.is_empty());
24231    }
24232
24233    #[test]
24234    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
24235        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24236            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24237                value.to_string(),
24238            )]))
24239            .expect("message payload");
24240            json!({
24241                "schema": MESSAGE_STREAM_SCHEMA,
24242                "stream_name": "orders",
24243                "message_id": message_id,
24244                "position": position,
24245                "payload_envelope": payload,
24246            })
24247        }
24248
24249        fn opened(sequence: u64) -> HistoryEvent {
24250            history_event(
24251                "SignalWaitOpened",
24252                json!({
24253                    "sequence": sequence,
24254                    "signal_name": MESSAGE_STREAM_SIGNAL,
24255                }),
24256            )
24257        }
24258
24259        fn received(delivery: Value) -> HistoryEvent {
24260            history_event(
24261                "SignalReceived",
24262                json!({
24263                    "signal_name": MESSAGE_STREAM_SIGNAL,
24264                    "arguments": fixture_envelope(json!([delivery])),
24265                    "payload_codec": DEFAULT_CODEC,
24266                }),
24267            )
24268        }
24269
24270        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24271            history_event(
24272                "SignalApplied",
24273                json!({
24274                    "sequence": sequence,
24275                    "signal_name": MESSAGE_STREAM_SIGNAL,
24276                    "value": fixture_envelope(json!([delivery])),
24277                }),
24278            )
24279        }
24280
24281        let client = Client::new("http://127.0.0.1:8080").expect("client");
24282        let mut worker = Worker::new(client, "rust-workers");
24283        worker.register_workflow(
24284            "rust.message-stream-partial-batches",
24285            |ctx, _input| async move {
24286                let stream = ctx.message_stream("orders")?;
24287                let first = stream.receive(10).await?;
24288                let second = stream.receive(10).await?;
24289                Ok(json!([
24290                    first
24291                        .into_iter()
24292                        .map(|message| message.message_id)
24293                        .collect::<Vec<_>>(),
24294                    second
24295                        .into_iter()
24296                        .map(|message| message.message_id)
24297                        .collect::<Vec<_>>(),
24298                ]))
24299            },
24300        );
24301
24302        let first = delivery("message-1", 1, "one");
24303        let second = delivery("message-2", 2, "two");
24304        let decision = worker
24305            .execute_workflow_task_decision(workflow_task(
24306                "rust.message-stream-partial-batches",
24307                vec![
24308                    opened(1),
24309                    received(first.clone()),
24310                    applied(1, first),
24311                    opened(2),
24312                    received(second.clone()),
24313                    applied(2, second),
24314                ],
24315                DEFAULT_CODEC,
24316            ))
24317            .expect("cold replay preserves both authored receive boundaries");
24318
24319        assert_eq!(decision.commands.len(), 1);
24320        assert_eq!(decision.commands[0]["type"], "complete_workflow");
24321        assert_eq!(
24322            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
24323                .expect("workflow result"),
24324            json!([["message-1"], ["message-2"]])
24325        );
24326        assert_eq!(
24327            decision.message_stream_cursors,
24328            vec![json!({"stream_name": "orders", "through_position": 2})]
24329        );
24330        assert!(decision.message_stream_waits.is_empty());
24331    }
24332
24333    #[test]
24334    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
24335        let ctx = workflow_context(Vec::new());
24336        let stream = ctx.message_stream("orders").expect("message stream");
24337        let mut receive = Box::pin(stream.receive(10));
24338        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24339
24340        assert!(matches!(
24341            receive.as_mut().poll(&mut task_context),
24342            Poll::Pending
24343        ));
24344        assert_eq!(
24345            ctx.take_commands().expect("message-stream wait command"),
24346            vec![json!({
24347                "type": "open_signal_wait",
24348                "signal_name": MESSAGE_STREAM_SIGNAL,
24349            })]
24350        );
24351        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
24352        assert!(cursors.is_empty());
24353        assert_eq!(
24354            waits,
24355            vec![json!({"stream_name": "orders", "after_position": 0})]
24356        );
24357    }
24358
24359    #[test]
24360    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
24361        let ctx = workflow_context(vec![history_event(
24362            "SignalReceived",
24363            json!({
24364                "signal_name": MESSAGE_STREAM_SIGNAL,
24365                "arguments": fixture_envelope(json!([{
24366                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
24367                    "stream_name": "orders",
24368                    "through_position": 2,
24369                }])),
24370                "payload_codec": DEFAULT_CODEC,
24371            }),
24372        )]);
24373        let stream = ctx.message_stream("orders").expect("message stream");
24374        let mut receive = Box::pin(stream.receive(10));
24375        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24376
24377        assert!(matches!(
24378            receive.as_mut().poll(&mut task_context),
24379            Poll::Pending
24380        ));
24381        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
24382        assert_eq!(
24383            cursors,
24384            vec![json!({"stream_name": "orders", "through_position": 2})]
24385        );
24386        assert_eq!(
24387            waits,
24388            vec![json!({"stream_name": "orders", "after_position": 2})]
24389        );
24390    }
24391
24392    #[test]
24393    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
24394        let mut empty_map = BTreeMap::new();
24395        let mut nested = BTreeMap::new();
24396        nested.insert(
24397            "value".to_string(),
24398            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
24399        );
24400        let values = vec![
24401            AvroValue::Bytes(vec![0, 255]),
24402            AvroValue::Long(1),
24403            AvroValue::Double(1.0),
24404            AvroValue::Array(Vec::new()),
24405            AvroValue::Map(std::mem::take(&mut empty_map)),
24406            AvroValue::Map(nested),
24407        ];
24408        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
24409        let transport = vec![json!({
24410            "schema": MESSAGE_STREAM_SCHEMA,
24411            "stream_name": "orders",
24412            "message_id": "message-1",
24413            "position": 1,
24414            "payload_envelope": payload,
24415        })];
24416
24417        for _ in 0..2 {
24418            let Some(MessageStreamDelivery::Message(message)) =
24419                decode_message_stream_delivery(transport.clone()).expect("delivery")
24420            else {
24421                panic!("message delivery expected");
24422            };
24423            assert_eq!(message.arguments, values);
24424            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
24425            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
24426        }
24427    }
24428
24429    #[test]
24430    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
24431        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24432            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24433                value.to_string(),
24434            )]))
24435            .expect("message payload");
24436            json!({
24437                "schema": MESSAGE_STREAM_SCHEMA,
24438                "stream_name": "orders",
24439                "message_id": message_id,
24440                "position": position,
24441                "payload_envelope": payload,
24442            })
24443        }
24444
24445        fn opened(sequence: u64) -> HistoryEvent {
24446            history_event(
24447                "SignalWaitOpened",
24448                json!({
24449                    "sequence": sequence,
24450                    "signal_name": MESSAGE_STREAM_SIGNAL,
24451                }),
24452            )
24453        }
24454
24455        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24456            history_event(
24457                "SignalApplied",
24458                json!({
24459                    "sequence": sequence,
24460                    "signal_name": MESSAGE_STREAM_SIGNAL,
24461                    "value": fixture_envelope(json!([delivery])),
24462                }),
24463            )
24464        }
24465
24466        fn worker() -> Worker {
24467            let client = Client::new("http://127.0.0.1:8080").expect("client");
24468            let mut worker = Worker::new(client, "rust-workers");
24469            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
24470                let stream = ctx.message_stream("orders")?;
24471                let first = stream.receive_one().await?;
24472                let second = stream.receive_one().await?;
24473                Ok(json!([first.message_id, second.message_id]))
24474            });
24475            worker
24476        }
24477
24478        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
24479            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
24480            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
24481            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
24482            task
24483        }
24484
24485        let waiting = worker()
24486            .execute_workflow_task_decision(workflow_task(
24487                "rust.message-stream",
24488                Vec::new(),
24489                DEFAULT_CODEC,
24490            ))
24491            .expect("first worker opens the stream wait");
24492        assert_eq!(
24493            waiting.commands,
24494            vec![json!({
24495                "type": "open_signal_wait",
24496                "signal_name": MESSAGE_STREAM_SIGNAL,
24497            })]
24498        );
24499        assert!(waiting.message_stream_cursors.is_empty());
24500        assert_eq!(
24501            waiting.message_stream_waits,
24502            vec![json!({"stream_name": "orders", "after_position": 0})]
24503        );
24504
24505        let first_delivery = delivery("message-1", 1, "one");
24506        let first_arrival = worker()
24507            .execute_workflow_task_decision(task_with_resume(
24508                vec![opened(1)],
24509                first_delivery.clone(),
24510            ))
24511            .expect("replacement worker consumes the first arrival");
24512        assert_eq!(
24513            first_arrival.commands,
24514            vec![json!({
24515                "type": "open_signal_wait",
24516                "signal_name": MESSAGE_STREAM_SIGNAL,
24517            })]
24518        );
24519        assert_eq!(
24520            first_arrival.message_stream_cursors,
24521            vec![json!({"stream_name": "orders", "through_position": 1})]
24522        );
24523        assert_eq!(
24524            first_arrival.message_stream_waits,
24525            vec![json!({"stream_name": "orders", "after_position": 1})]
24526        );
24527
24528        let second_delivery = delivery("message-2", 2, "two");
24529        let first_applied = applied(1, first_delivery);
24530        let completed = worker()
24531            .execute_workflow_task_decision(task_with_resume(
24532                vec![opened(1), first_applied.clone(), opened(2)],
24533                second_delivery.clone(),
24534            ))
24535            .expect("next replacement worker consumes the second arrival");
24536        assert_eq!(completed.commands.len(), 1);
24537        assert_eq!(completed.commands[0]["type"], "complete_workflow");
24538        assert_eq!(
24539            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
24540                .expect("workflow result"),
24541            json!(["message-1", "message-2"])
24542        );
24543        assert_eq!(
24544            completed.message_stream_cursors,
24545            vec![json!({"stream_name": "orders", "through_position": 2})]
24546        );
24547        assert!(completed.message_stream_waits.is_empty());
24548
24549        let replay_history = vec![
24550            opened(1),
24551            first_applied,
24552            opened(2),
24553            applied(2, second_delivery),
24554        ];
24555        for _cold_worker_or_restart in 0..2 {
24556            let replayed = worker()
24557                .execute_workflow_task_decision(workflow_task(
24558                    "rust.message-stream",
24559                    replay_history.clone(),
24560                    DEFAULT_CODEC,
24561                ))
24562                .expect("cold worker replays each logical message exactly once");
24563            assert_eq!(replayed.commands.len(), 1);
24564            assert_eq!(
24565                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
24566                    .expect("replayed workflow result"),
24567                json!(["message-1", "message-2"])
24568            );
24569            assert_eq!(
24570                replayed.message_stream_cursors,
24571                vec![json!({"stream_name": "orders", "through_position": 2})]
24572            );
24573            assert!(replayed.message_stream_waits.is_empty());
24574        }
24575    }
24576
24577    #[test]
24578    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
24579        assert!(!worker_protocol_supports_message_streams("1.14"));
24580        assert!(worker_protocol_supports_message_streams("1.15"));
24581        assert!(worker_protocol_supports_message_streams("1.16"));
24582        assert!(worker_protocol_supports_message_streams(
24583            WORKER_PROTOCOL_VERSION
24584        ));
24585        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
24586    }
24587
24588    #[test]
24589    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
24590        let ctx = workflow_context(vec![
24591            history_event(
24592                "ConditionWaitOpened",
24593                json!({
24594                    "sequence": 1,
24595                    "condition_wait_id": "condition:1",
24596                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24597                    "condition_key": "signal:finish",
24598                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24599                }),
24600            ),
24601            history_event(
24602                "ConditionWaitSatisfied",
24603                json!({
24604                    "sequence": 1,
24605                    "condition_wait_id": "condition:1",
24606                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24607                    "condition_key": "signal:finish",
24608                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24609                }),
24610            ),
24611            history_event(
24612                "SignalReceived",
24613                json!({"signal_name": "finish", "arguments": []}),
24614            ),
24615        ]);
24616        let mut signal = Box::pin(ctx.wait_signal("finish"));
24617        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24618
24619        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24620            signal.as_mut().poll(&mut task_context)
24621        else {
24622            panic!("condition history must not resolve as a typed signal wait");
24623        };
24624        assert_eq!(failure.reason, "recorded_command_mismatch");
24625        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
24626    }
24627
24628    #[test]
24629    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
24630        let signal_then_timer = vec![
24631            history_event(
24632                "SignalWaitOpened",
24633                json!({"sequence": 1, "signal_name": "go"}),
24634            ),
24635            history_event(
24636                "SignalApplied",
24637                json!({
24638                    "sequence": 1,
24639                    "signal_name": "go",
24640                    "value": fixture_envelope(json!(["now"])),
24641                }),
24642            ),
24643            history_event(
24644                "TimerScheduled",
24645                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24646            ),
24647            history_event(
24648                "TimerFired",
24649                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24650            ),
24651        ];
24652
24653        let ctx = workflow_context(signal_then_timer.clone());
24654        let mut signal = Box::pin(ctx.wait_signal("go"));
24655        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24656        assert!(matches!(
24657            signal.as_mut().poll(&mut task_context),
24658            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
24659        ));
24660        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
24661        assert!(matches!(
24662            timer.as_mut().poll(&mut task_context),
24663            Poll::Ready(Ok(()))
24664        ));
24665        ctx.ensure_history_consumed()
24666            .expect("signal and timer history consumed in order");
24667
24668        let reordered = workflow_context(signal_then_timer);
24669        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
24670        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24671            timer_first.as_mut().poll(&mut task_context)
24672        else {
24673            panic!("timer cannot consume signal-wait-first history");
24674        };
24675        assert_eq!(failure.reason, "recorded_command_mismatch");
24676        assert_eq!(failure.sequence, Some(1));
24677        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
24678
24679        let timer_then_signal = vec![
24680            history_event(
24681                "TimerScheduled",
24682                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24683            ),
24684            history_event(
24685                "TimerFired",
24686                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24687            ),
24688            history_event(
24689                "SignalWaitOpened",
24690                json!({"sequence": 2, "signal_name": "go"}),
24691            ),
24692            history_event(
24693                "SignalApplied",
24694                json!({
24695                    "sequence": 2,
24696                    "signal_name": "go",
24697                    "value": fixture_envelope(json!([])),
24698                }),
24699            ),
24700        ];
24701        let reordered = workflow_context(timer_then_signal);
24702        let mut signal_first = Box::pin(reordered.wait_signal("go"));
24703        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24704            signal_first.as_mut().poll(&mut task_context)
24705        else {
24706            panic!("signal wait cannot consume timer-first history");
24707        };
24708        assert_eq!(failure.reason, "recorded_command_mismatch");
24709        assert_eq!(failure.sequence, Some(1));
24710        assert_eq!(failure.expected.as_deref(), Some("timer"));
24711    }
24712
24713    #[test]
24714    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
24715        let duplicate_timer = WorkflowState::new(
24716            vec![
24717                history_event(
24718                    "TimerScheduled",
24719                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24720                ),
24721                history_event(
24722                    "TimerScheduled",
24723                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24724                ),
24725            ],
24726            "rust-workers".to_string(),
24727            DEFAULT_CODEC.to_string(),
24728            None,
24729        )
24730        .expect_err("one workflow sequence cannot schedule two timers");
24731        assert!(matches!(
24732            duplicate_timer,
24733            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24734                if reason == "timer_schedule_missing_or_duplicate"
24735        ));
24736
24737        let colliding_kinds = WorkflowState::new(
24738            vec![
24739                history_event(
24740                    "TimerScheduled",
24741                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24742                ),
24743                history_event(
24744                    "ActivityCompleted",
24745                    json!({"sequence": 1, "activity_type": "same-sequence"}),
24746                ),
24747            ],
24748            "rust-workers".to_string(),
24749            DEFAULT_CODEC.to_string(),
24750            None,
24751        )
24752        .expect_err("one workflow sequence cannot identify two command kinds");
24753        assert!(matches!(
24754            colliding_kinds,
24755            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24756                if reason == "durable_command_sequence_collision"
24757        ));
24758
24759        let duplicate_signal_wait = WorkflowState::new(
24760            vec![
24761                history_event(
24762                    "SignalWaitOpened",
24763                    json!({"sequence": 1, "signal_name": "go"}),
24764                ),
24765                history_event(
24766                    "SignalWaitOpened",
24767                    json!({"sequence": 1, "signal_name": "go"}),
24768                ),
24769            ],
24770            "rust-workers".to_string(),
24771            DEFAULT_CODEC.to_string(),
24772            None,
24773        )
24774        .expect_err("one workflow sequence cannot open two signal waits");
24775        assert!(matches!(
24776            duplicate_signal_wait,
24777            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24778                if reason == "signal_wait_open_missing_or_duplicate"
24779        ));
24780    }
24781
24782    #[test]
24783    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
24784        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
24785            .expect("side-effect result");
24786        let ctx = workflow_context(vec![history_event(
24787            "SideEffectRecorded",
24788            json!({"sequence": 99, "result": result}),
24789        )]);
24790
24791        let replayed: Value = ctx
24792            .side_effect(|| panic!("recorded side effect must not run"))
24793            .expect("positive global workflow sequence is valid");
24794        assert_eq!(replayed, json!({"captured": true}));
24795        ctx.ensure_history_consumed().expect("history consumed");
24796    }
24797
24798    #[test]
24799    fn workflow_history_rejects_zero_and_descending_command_sequences() {
24800        let result =
24801            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
24802        let zero = WorkflowState::new(
24803            vec![history_event(
24804                "SideEffectRecorded",
24805                json!({"sequence": 0, "result": result.clone()}),
24806            )],
24807            "rust-workers".to_string(),
24808            DEFAULT_CODEC.to_string(),
24809            None,
24810        )
24811        .expect_err("durable command sequences must be positive");
24812        assert!(matches!(
24813            zero,
24814            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24815                if reason == "durable_command_sequence_invalid"
24816        ));
24817
24818        let descending = WorkflowState::new(
24819            vec![
24820                history_event(
24821                    "SideEffectRecorded",
24822                    json!({"sequence": 3, "result": result}),
24823                ),
24824                history_event(
24825                    "VersionMarkerRecorded",
24826                    json!({
24827                        "sequence": 2,
24828                        "change_id": "descending-marker",
24829                        "version": 1,
24830                        "min_supported": 1,
24831                        "max_supported": 1,
24832                    }),
24833                ),
24834            ],
24835            "rust-workers".to_string(),
24836            DEFAULT_CODEC.to_string(),
24837            None,
24838        )
24839        .expect_err("new durable commands must remain strictly ordered");
24840        let Error::NonDeterministicReplay(failure) = descending else {
24841            panic!("expected typed replay failure");
24842        };
24843        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
24844        assert_eq!(failure.sequence, Some(2));
24845        assert_eq!(
24846            failure.expected.as_deref(),
24847            Some("workflow sequence greater than 3")
24848        );
24849        assert_eq!(failure.actual.as_deref(), Some("2"));
24850    }
24851
24852    #[test]
24853    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
24854        fn worker() -> Worker {
24855            let client = Client::new("http://127.0.0.1:8080").expect("client");
24856            let mut worker = Worker::new(client, "rust-workers");
24857            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
24858                ctx.wait_signal("finish").await?;
24859                let marker: String =
24860                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
24861                assert_eq!(marker, "after-finish");
24862                Ok(json!("finished"))
24863            });
24864            worker
24865        }
24866
24867        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
24868            .expect("side-effect result");
24869        let task = workflow_task(
24870            "rust.finish-after-gaps",
24871            vec![
24872                history_event(
24873                    "SignalWaitOpened",
24874                    json!({"sequence": 1, "signal_name": "finish"}),
24875                ),
24876                history_event(
24877                    "SignalReceived",
24878                    json!({
24879                        "signal_id": "increment-3",
24880                        "signal_name": "increment",
24881                        "workflow_sequence": 2,
24882                        "payload_codec": DEFAULT_CODEC,
24883                        "arguments": fixture_envelope(json!([3])),
24884                    }),
24885                ),
24886                history_event(
24887                    "SignalReceived",
24888                    json!({
24889                        "signal_id": "increment-5",
24890                        "signal_name": "increment",
24891                        "workflow_sequence": 3,
24892                        "payload_codec": DEFAULT_CODEC,
24893                        "arguments": fixture_envelope(json!([5])),
24894                    }),
24895                ),
24896                history_event(
24897                    "SignalReceived",
24898                    json!({
24899                        "signal_id": "finish",
24900                        "signal_name": "finish",
24901                        "workflow_sequence": 4,
24902                        "payload_codec": DEFAULT_CODEC,
24903                        "arguments": fixture_envelope(json!([])),
24904                    }),
24905                ),
24906                history_event(
24907                    "SignalApplied",
24908                    json!({
24909                        "sequence": 1,
24910                        "signal_id": "finish",
24911                        "signal_name": "finish",
24912                        "payload_codec": DEFAULT_CODEC,
24913                        "value": fixture_envelope(json!([])),
24914                    }),
24915                ),
24916                history_event(
24917                    "SideEffectRecorded",
24918                    json!({"sequence": 5, "result": marker}),
24919                ),
24920            ],
24921            DEFAULT_CODEC,
24922        );
24923
24924        for _original_or_cold_worker in 0..2 {
24925            let commands = worker()
24926                .execute_workflow_task(task.clone())
24927                .expect("signal gaps preserve deterministic replay");
24928            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
24929            assert_eq!(commands[0]["type"], "complete_workflow");
24930            assert_eq!(
24931                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24932                json!("finished")
24933            );
24934        }
24935    }
24936
24937    #[test]
24938    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
24939        let ctx = workflow_context(Vec::new());
24940        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
24941        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24942        assert!(matches!(
24943            sleep.as_mut().poll(&mut task_context),
24944            Poll::Ready(Err(Error::TimerDurationOverflow))
24945        ));
24946        assert!(ctx.take_commands().expect("commands").is_empty());
24947    }
24948
24949    #[test]
24950    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
24951        let entries = AvroValue::Map(BTreeMap::from([
24952            ("text".to_string(), AvroValue::String("same".to_string())),
24953            (
24954                "nested".to_string(),
24955                AvroValue::Map(BTreeMap::from([
24956                    ("beta".to_string(), AvroValue::Long(2)),
24957                    ("alpha".to_string(), AvroValue::Long(1)),
24958                ])),
24959            ),
24960            ("long".to_string(), AvroValue::Long(7)),
24961            ("double".to_string(), AvroValue::Double(7.0)),
24962            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
24963        ]));
24964        let ctx = workflow_context(Vec::new());
24965        ctx.upsert_memo(entries.clone()).expect("valid memo update");
24966        let commands = ctx.take_commands().expect("commands");
24967
24968        assert_eq!(commands.len(), 1);
24969        assert_eq!(commands[0]["type"], "upsert_memo");
24970        let server_entries = json!({
24971            "codec": "avro",
24972            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
24973        });
24974        assert_eq!(
24975            commands[0]["entries"]
24976                .as_object()
24977                .expect("entries envelope")
24978                .keys()
24979                .collect::<Vec<_>>(),
24980            vec!["blob", "codec"]
24981        );
24982        assert_eq!(commands[0]["entries"], server_entries);
24983        let wire_entries =
24984            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
24985        assert_eq!(wire_entries, entries);
24986
24987        let history = vec![history_event(
24988            "MemoUpserted",
24989            json!({
24990                "sequence": 1,
24991                "entries": server_entries.clone(),
24992                "merged": server_entries,
24993            }),
24994        )];
24995        let replay = workflow_context(history.clone());
24996        replay
24997            .upsert_memo(entries.clone())
24998            .expect("matching replay identity");
24999        assert!(replay.take_commands().expect("replay commands").is_empty());
25000
25001        let changed_types = AvroValue::Map(BTreeMap::from([
25002            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
25003            (
25004                "nested".to_string(),
25005                AvroValue::Map(BTreeMap::from([
25006                    ("alpha".to_string(), AvroValue::Long(1)),
25007                    ("beta".to_string(), AvroValue::Long(2)),
25008                ])),
25009            ),
25010            ("long".to_string(), AvroValue::Double(7.0)),
25011            ("double".to_string(), AvroValue::Long(7)),
25012            ("binary".to_string(), AvroValue::String("same".to_string())),
25013        ]));
25014        let error = workflow_context(history)
25015            .upsert_memo(changed_types)
25016            .expect_err("memo replay identity must preserve Avro value types");
25017        assert!(matches!(
25018            error,
25019            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25020        ));
25021    }
25022
25023    #[test]
25024    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
25025        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
25026            .expect("memo envelope");
25027        let replay = workflow_context(vec![history_event(
25028            "MemoUpserted",
25029            json!({
25030                "sequence": 1,
25031                "entries": original.clone(),
25032                "merged": original
25033            }),
25034        )]);
25035        let error = replay
25036            .upsert_memo(json!({"stage": "changed"}))
25037            .expect_err("changed memo update must fail replay");
25038        assert!(matches!(
25039            error,
25040            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25041        ));
25042
25043        let invalid = workflow_context(Vec::new())
25044            .upsert_memo(
25045                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
25046            )
25047            .expect_err("oversized key");
25048        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
25049    }
25050
25051    #[test]
25052    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
25053        let negative_zero = AvroValue::Map(BTreeMap::from([(
25054            "reading".to_string(),
25055            AvroValue::Double(-0.0),
25056        )]));
25057        let negative_zero_envelope =
25058            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
25059        let history = vec![history_event(
25060            "MemoUpserted",
25061            json!({
25062                "sequence": 1,
25063                "entries": negative_zero_envelope.clone(),
25064                "merged": negative_zero_envelope,
25065            }),
25066        )];
25067
25068        workflow_context(history.clone())
25069            .upsert_memo(negative_zero)
25070            .expect("matching negative-zero history identity");
25071
25072        let error = workflow_context(history)
25073            .upsert_memo(AvroValue::Map(BTreeMap::from([(
25074                "reading".to_string(),
25075                AvroValue::Double(0.0),
25076            )])))
25077            .expect_err("positive zero must not consume negative-zero memo history");
25078        assert!(matches!(
25079            error,
25080            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25081        ));
25082    }
25083
25084    #[test]
25085    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
25086        let supported = json!({
25087            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
25088            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
25089        });
25090        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
25091        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
25092            "workflow_memo_updates": {"supported": false},
25093            "supported_workflow_task_commands": ["upsert_memo"]
25094        }))));
25095        assert!(commands_use_workflow_memo_updates(&[json!({
25096            "type": "upsert_memo",
25097            "entries": {"stage": "processing"}
25098        })]));
25099    }
25100
25101    #[test]
25102    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
25103        let client = Client::new("http://127.0.0.1:8080").expect("client");
25104        let mut worker = Worker::new(client, "rust-workers");
25105        worker.register_workflow("rust.timer", |ctx, _input| async move {
25106            ctx.sleep(Duration::from_secs(5)).await?;
25107            ctx.activity("after-timer", json!([])).await
25108        });
25109
25110        let task = |history_events| WorkflowTask {
25111            task_id: "wft-rust-timer-1".to_string(),
25112            workflow_command_id: None,
25113            workflow_id: Some("wf-rust-timer".to_string()),
25114            run_id: Some("run-rust-timer".to_string()),
25115            workflow_type: "rust.timer".to_string(),
25116            cancel_requested: false,
25117            payload_codec: DEFAULT_CODEC.to_string(),
25118            arguments: Some(
25119                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25120            ),
25121            history_events,
25122            total_history_events: None,
25123            history_size_bytes: None,
25124            continue_as_new_recommended: None,
25125            history_budget_pressure: None,
25126            next_history_page_token: None,
25127            workflow_task_attempt: 1,
25128            workflow_signal_id: None,
25129            signal_name: None,
25130            signal_arguments: None,
25131            workflow_update_id: None,
25132            update_name: None,
25133            lease_owner: Some("rust-worker".to_string()),
25134        };
25135
25136        let initial = worker
25137            .execute_workflow_task(task(Vec::new()))
25138            .expect("initial timer task");
25139        assert_eq!(
25140            initial,
25141            vec![json!({"type": "start_timer", "delay_seconds": 5})]
25142        );
25143
25144        let activity_result =
25145            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
25146        let replayed = worker
25147            .execute_workflow_task(task(vec![
25148                history_event(
25149                    "TimerScheduled",
25150                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25151                ),
25152                history_event(
25153                    "TimerFired",
25154                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25155                ),
25156                history_event(
25157                    "ActivityCompleted",
25158                    json!({
25159                        "sequence": 2,
25160                        "activity_type": "after-timer",
25161                        "payload_codec": DEFAULT_CODEC,
25162                        "result": activity_result,
25163                    }),
25164                ),
25165            ]))
25166            .expect("replayed workflow task");
25167        assert_eq!(replayed.len(), 1);
25168        assert_eq!(replayed[0]["type"], "complete_workflow");
25169        assert_eq!(
25170            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
25171            json!("done")
25172        );
25173    }
25174
25175    #[test]
25176    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
25177        let client = Client::new("http://127.0.0.1:8080").expect("client");
25178        let mut worker = Worker::new(client, "rust-workers");
25179        worker.register_workflow("rust.continue", |ctx, _input| async move {
25180            ctx.continue_as_new_with_options(
25181                ContinueAsNewOptions::new()
25182                    .workflow_type("rust.next")
25183                    .task_queue("next-workers"),
25184                json!([2, {"cursor": "next"}]),
25185            )
25186        });
25187
25188        let commands = worker
25189            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
25190            .expect("continue-as-new command");
25191
25192        assert_eq!(commands.len(), 1);
25193        assert_eq!(commands[0]["type"], "continue_as_new");
25194        assert_eq!(commands[0]["workflow_type"], "rust.next");
25195        assert_eq!(commands[0]["queue"], "next-workers");
25196        assert_eq!(
25197            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
25198                .expect("continue-as-new arguments"),
25199            json!([2, {"cursor": "next"}])
25200        );
25201    }
25202
25203    #[test]
25204    fn continue_as_new_preserves_typed_arguments() {
25205        let client = Client::new("http://127.0.0.1:8080").expect("client");
25206        let mut worker = Worker::new(client, "rust-workers");
25207        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
25208            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
25209            unreachable!("continue-as-new returns a control-flow error")
25210        });
25211
25212        let commands = worker
25213            .execute_workflow_task(workflow_task(
25214                "rust.typed-continue",
25215                Vec::new(),
25216                DEFAULT_CODEC,
25217            ))
25218            .expect("typed continue-as-new command");
25219
25220        assert_eq!(commands[0]["type"], "continue_as_new");
25221        assert_eq!(
25222            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
25223                .expect("typed continue arguments"),
25224            AvroValue::Array(vec![typed_fidelity_probe()])
25225        );
25226    }
25227
25228    #[test]
25229    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
25230        let client = Client::new("http://127.0.0.1:8080").expect("client");
25231        let mut worker = Worker::new(client, "rust-workers");
25232        worker.register_workflow("rust.continue", |ctx, _input| async move {
25233            ctx.continue_as_new(json!([2]))
25234        });
25235        let task = workflow_task(
25236            "rust.continue",
25237            vec![history_event(
25238                "WorkflowContinuedAsNew",
25239                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
25240            )],
25241            DEFAULT_CODEC,
25242        );
25243
25244        for _worker_restart_or_redelivery in 0..2 {
25245            let commands = worker
25246                .execute_workflow_task(task.clone())
25247                .expect("recorded transition replays");
25248            assert!(
25249                commands.is_empty(),
25250                "replay must not emit another successor"
25251            );
25252        }
25253    }
25254
25255    #[test]
25256    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
25257        let ctx = workflow_context(Vec::new());
25258        let error = ctx
25259            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
25260            .expect_err("blank queue must be rejected");
25261
25262        let Error::InvalidContinueAsNewOptions(error) = error else {
25263            panic!("expected typed continue-as-new validation error");
25264        };
25265        assert_eq!(error.field, "task_queue");
25266        assert!(ctx.take_commands().expect("commands").is_empty());
25267    }
25268
25269    #[test]
25270    fn workflow_context_exposes_server_history_budget() {
25271        let client = Client::new("http://127.0.0.1:8080").expect("client");
25272        let mut worker = Worker::new(client, "rust-workers");
25273        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
25274            let budget = ctx.history_budget()?;
25275            Ok(json!({
25276                "events": budget.event_count,
25277                "bytes": budget.size_bytes,
25278                "recommended": budget.continue_as_new_recommended,
25279                "pressure": budget.pressure,
25280            }))
25281        });
25282        let task: WorkflowTask = serde_json::from_value(json!({
25283            "task_id": "task-history-budget",
25284            "workflow_type": "rust.history-budget",
25285            "payload_codec": DEFAULT_CODEC,
25286            "history_events": [],
25287            "total_history_events": 480,
25288            "history_size_bytes": 1_048_576,
25289            "continue_as_new_recommended": true,
25290            "history_budget_pressure": "continue_as_new_recommended",
25291        }))
25292        .expect("published workflow task");
25293
25294        let commands = worker
25295            .execute_workflow_task(task)
25296            .expect("history-budget workflow");
25297        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
25298        assert_eq!(result["events"], 480);
25299        assert_eq!(result["bytes"], 1_048_576);
25300        assert_eq!(result["recommended"], true);
25301        assert_eq!(result["pressure"], "continue_as_new_recommended");
25302    }
25303
25304    #[test]
25305    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
25306        let client = Client::new("http://127.0.0.1:8080").expect("client");
25307        let mut worker = Worker::new(client, "rust-workers");
25308        worker.register_workflow("rust.failing", |_ctx, _input| async move {
25309            Err(Error::Codec("rust_conformance_failure".to_string()))
25310        });
25311        let task = WorkflowTask {
25312            task_id: "wft-rust-failing-1".to_string(),
25313            workflow_command_id: None,
25314            workflow_id: Some("wf-rust-failing".to_string()),
25315            run_id: Some("run-rust-failing".to_string()),
25316            workflow_type: "rust.failing".to_string(),
25317            cancel_requested: false,
25318            payload_codec: DEFAULT_CODEC.to_string(),
25319            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25320            history_events: Vec::new(),
25321            total_history_events: Some(0),
25322            history_size_bytes: None,
25323            continue_as_new_recommended: None,
25324            history_budget_pressure: None,
25325            next_history_page_token: None,
25326            workflow_task_attempt: 1,
25327            workflow_signal_id: None,
25328            signal_name: None,
25329            signal_arguments: None,
25330            workflow_update_id: None,
25331            update_name: None,
25332            lease_owner: Some("rust-worker".to_string()),
25333        };
25334
25335        let commands = worker
25336            .execute_workflow_task(task)
25337            .expect("handler failure becomes a workflow command");
25338
25339        assert_eq!(commands.len(), 1);
25340        assert_eq!(commands[0]["type"], "fail_workflow");
25341        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
25342        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
25343        assert_eq!(commands[0]["non_retryable"], false);
25344        assert_eq!(
25345            commands[0]["message"],
25346            "codec error: rust_conformance_failure"
25347        );
25348        assert_eq!(
25349            commands[0]["exception"]["message"],
25350            "codec error: rust_conformance_failure"
25351        );
25352    }
25353
25354    #[test]
25355    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
25356        let client = Client::new("http://127.0.0.1:8080").expect("client");
25357        let mut worker = Worker::new(client, "rust-workers");
25358        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
25359            let _: String = ctx.side_effect(|| "captured".to_string())?;
25360            Err(Error::WorkerLoop("application failure".to_string()))
25361        });
25362
25363        let commands = worker
25364            .execute_workflow_task(workflow_task(
25365                "rust.failing-after-side-effect",
25366                Vec::new(),
25367                DEFAULT_CODEC,
25368            ))
25369            .expect("ordinary failure remains a workflow decision");
25370
25371        assert_eq!(commands.len(), 2);
25372        assert_eq!(commands[0]["type"], "record_side_effect");
25373        assert_eq!(commands[1]["type"], "fail_workflow");
25374    }
25375
25376    #[test]
25377    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
25378        let client = Client::new("http://127.0.0.1:8080").expect("client");
25379        let mut worker = Worker::new(client, "rust-workers");
25380        worker.register_workflow("rust.redrive", |ctx, _input| async move {
25381            ctx.activity("greet", json!([])).await?;
25382            Ok(Value::Null)
25383        });
25384        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
25385            match ctx.activity("greet", json!([])).await {
25386                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
25387                result => result,
25388            }
25389        });
25390
25391        let failed = history_event(
25392            "ActivityFailed",
25393            json!({
25394                "sequence": 1,
25395                "activity_type": "greet",
25396                "activity_execution_id": "activity-1",
25397                "message": "failed"
25398            }),
25399        );
25400        let commands = worker
25401            .execute_workflow_task(workflow_task(
25402                "rust.redrive",
25403                vec![failed.clone()],
25404                DEFAULT_CODEC,
25405            ))
25406            .expect("recorded failure becomes a workflow command");
25407        assert_eq!(commands[0]["type"], "fail_workflow");
25408        assert_eq!(commands[0]["failed_step_sequence"], 1);
25409        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
25410
25411        let translated = worker
25412            .execute_workflow_task(workflow_task(
25413                "rust.redrive-translated",
25414                vec![failed],
25415                DEFAULT_CODEC,
25416            ))
25417            .expect("translated failure becomes a workflow command");
25418        assert_eq!(translated[0]["type"], "fail_workflow");
25419        assert!(translated[0].get("failed_step_sequence").is_none());
25420        assert!(translated[0].get("failed_activity_execution_id").is_none());
25421
25422        let without_identity = worker
25423            .execute_workflow_task(workflow_task(
25424                "rust.redrive",
25425                vec![history_event(
25426                    "ActivityFailed",
25427                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
25428                )],
25429                DEFAULT_CODEC,
25430            ))
25431            .expect("incomplete identity still fails the workflow");
25432        assert!(without_identity[0].get("failed_step_sequence").is_none());
25433
25434        let timed_out = worker
25435            .execute_workflow_task(workflow_task(
25436                "rust.redrive",
25437                vec![history_event(
25438                    "ActivityTimedOut",
25439                    json!({
25440                        "sequence": 1,
25441                        "activity_type": "greet",
25442                        "activity_execution_id": "activity-timeout",
25443                    }),
25444                )],
25445                DEFAULT_CODEC,
25446            ))
25447            .expect("timeout still fails the workflow");
25448        assert!(timed_out[0].get("failed_step_sequence").is_none());
25449    }
25450
25451    #[test]
25452    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
25453        let client = Client::new("http://127.0.0.1:8080").expect("client");
25454        let mut worker = Worker::new(client, "rust-workers");
25455        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
25456            let first = ctx.activity("first", json!([])).await?;
25457            let second = ctx.activity("second", json!([first.clone()])).await?;
25458            Ok(json!({"first": first, "second": second}))
25459        });
25460        let first = history_event(
25461            "ActivityCompleted",
25462            json!({
25463                "sequence": 1,
25464                "activity_type": "first",
25465                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
25466                "payload_codec": DEFAULT_CODEC,
25467                "reused_from_run_id": "failed-run",
25468                "reused_activity_execution_id": "original-first",
25469            }),
25470        );
25471
25472        let retry = worker
25473            .execute_workflow_task(workflow_task(
25474                "rust.redrive-successor",
25475                vec![first.clone()],
25476                DEFAULT_CODEC,
25477            ))
25478            .expect("reused result replays before failed step");
25479        assert_eq!(retry.len(), 1);
25480        assert_eq!(retry[0]["type"], "schedule_activity");
25481        assert_eq!(retry[0]["activity_type"], "second");
25482        assert_eq!(
25483            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
25484            json!(["recorded"]),
25485        );
25486
25487        let second = history_event(
25488            "ActivityCompleted",
25489            json!({
25490                "sequence": 2,
25491                "activity_type": "second",
25492                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
25493                "payload_codec": DEFAULT_CODEC,
25494            }),
25495        );
25496        let completed = worker
25497            .execute_workflow_task(workflow_task(
25498                "rust.redrive-successor",
25499                vec![first, second],
25500                DEFAULT_CODEC,
25501            ))
25502            .expect("retried step completes the successor");
25503        assert_eq!(completed.len(), 1);
25504        assert_eq!(completed[0]["type"], "complete_workflow");
25505        assert_eq!(
25506            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
25507            json!({"first": "recorded", "second": "retried"}),
25508        );
25509    }
25510
25511    #[test]
25512    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
25513        let client = Client::new("http://127.0.0.1:8080").expect("client");
25514        let mut worker = Worker::new(client, "rust-workers");
25515        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
25516            Err(Error::WorkerLoop("application failure".to_string()))
25517        });
25518        let result =
25519            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
25520
25521        let error = worker
25522            .execute_workflow_task(workflow_task(
25523                "rust.removed-side-effect",
25524                vec![history_event(
25525                    "SideEffectRecorded",
25526                    json!({"sequence": 1, "result": result}),
25527                )],
25528                DEFAULT_CODEC,
25529            ))
25530            .expect_err("removed committed history must not become fail_workflow");
25531
25532        let Error::NonDeterministicReplay(failure) = error else {
25533            panic!("expected typed replay failure");
25534        };
25535        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25536        assert_eq!(failure.sequence, Some(1));
25537        assert_eq!(failure.expected.as_deref(), Some("side effect"));
25538    }
25539
25540    #[test]
25541    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
25542        let client = Client::new("http://127.0.0.1:8080").expect("client");
25543        let mut worker = Worker::new(client, "rust-workers");
25544        worker.register_workflow(
25545            "rust.side-effect-before-marker-error",
25546            |ctx, _input| async move {
25547                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
25548                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
25549                ctx.get_version("restart-safe", 2, 2)?;
25550                Ok(Value::Null)
25551            },
25552        );
25553
25554        let error = worker
25555            .execute_workflow_task(workflow_task(
25556                "rust.side-effect-before-marker-error",
25557                vec![history_event(
25558                    "VersionMarkerRecorded",
25559                    json!({
25560                        "sequence": 1,
25561                        "change_id": "restart-safe",
25562                        "version": 1,
25563                        "min_supported": 1,
25564                        "max_supported": 1,
25565                    }),
25566                )],
25567                DEFAULT_CODEC,
25568            ))
25569            .expect_err("replay error must return no queued workflow commands");
25570
25571        let Error::NonDeterministicReplay(failure) = error else {
25572            panic!("expected typed replay failure");
25573        };
25574        assert_eq!(failure.reason, "version_marker_incompatible_range");
25575        assert_eq!(failure.sequence, Some(1));
25576    }
25577
25578    #[test]
25579    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
25580        let client = Client::new("http://127.0.0.1:8080").expect("client");
25581        let mut worker = Worker::new(client, "rust-workers");
25582        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
25583            ctx.sleep(Duration::from_secs(5)).await?;
25584            Ok(json!({"status": "timer fired"}))
25585        });
25586
25587        let task = WorkflowTask {
25588            task_id: "wft-rust-timer-pending".to_string(),
25589            workflow_command_id: None,
25590            workflow_id: Some("wf-rust-timer".to_string()),
25591            run_id: Some("run-rust-timer".to_string()),
25592            workflow_type: "rust.timer.pending".to_string(),
25593            cancel_requested: false,
25594            payload_codec: DEFAULT_CODEC.to_string(),
25595            arguments: Some(
25596                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25597            ),
25598            history_events: vec![history_event(
25599                "TimerScheduled",
25600                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25601            )],
25602            total_history_events: Some(1),
25603            history_size_bytes: None,
25604            continue_as_new_recommended: None,
25605            history_budget_pressure: None,
25606            next_history_page_token: None,
25607            workflow_task_attempt: 1,
25608            workflow_signal_id: None,
25609            signal_name: None,
25610            signal_arguments: None,
25611            workflow_update_id: None,
25612            update_name: None,
25613            lease_owner: Some("rust-worker".to_string()),
25614        };
25615
25616        for _redelivery_or_restart in 0..2 {
25617            let commands = worker
25618                .execute_workflow_task(task.clone())
25619                .expect("recorded timer remains pending");
25620            assert!(
25621                commands.is_empty(),
25622                "recorded timer must not be rescheduled"
25623            );
25624        }
25625    }
25626
25627    #[test]
25628    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
25629        let client = Client::new("http://127.0.0.1:8080").expect("client");
25630        let mut worker = Worker::new(client, "rust-workers");
25631        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
25632            Ok(json!({"status": "completed"}))
25633        });
25634        let task = WorkflowTask {
25635            task_id: "wft-rust-timer-removed".to_string(),
25636            workflow_command_id: None,
25637            workflow_id: Some("wf-rust-timer".to_string()),
25638            run_id: Some("run-rust-timer".to_string()),
25639            workflow_type: "rust.timer.removed".to_string(),
25640            cancel_requested: false,
25641            payload_codec: DEFAULT_CODEC.to_string(),
25642            arguments: Some(
25643                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25644            ),
25645            history_events: vec![
25646                history_event(
25647                    "TimerScheduled",
25648                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25649                ),
25650                history_event(
25651                    "TimerFired",
25652                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25653                ),
25654            ],
25655            total_history_events: Some(2),
25656            history_size_bytes: None,
25657            continue_as_new_recommended: None,
25658            history_budget_pressure: None,
25659            next_history_page_token: None,
25660            workflow_task_attempt: 1,
25661            workflow_signal_id: None,
25662            signal_name: None,
25663            signal_arguments: None,
25664            workflow_update_id: None,
25665            update_name: None,
25666            lease_owner: Some("rust-worker".to_string()),
25667        };
25668
25669        let Error::NonDeterministicReplay(failure) = worker
25670            .execute_workflow_task(task)
25671            .expect_err("removed timer must fail replay")
25672        else {
25673            panic!("expected typed replay failure");
25674        };
25675        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25676        assert_eq!(failure.sequence, Some(1));
25677    }
25678
25679    #[test]
25680    fn workflow_context_emits_explicit_child_workflow_contract() {
25681        let ctx = WorkflowContext {
25682            cancellation_scope_id: "root".into(),
25683            state: Arc::new(Mutex::new(
25684                WorkflowState::new_with_identity(
25685                    Vec::new(),
25686                    Some("wf-parent".to_string()),
25687                    Some("run-parent".to_string()),
25688                    "parent-workers".to_string(),
25689                    DEFAULT_CODEC.to_string(),
25690                    None,
25691                )
25692                .expect("workflow state"),
25693            )),
25694        };
25695        let options = ChildWorkflowOptions::new("python-workers")
25696            .parent_close_policy(ParentClosePolicy::RequestCancel)
25697            .retry_policy(ChildWorkflowRetryPolicy {
25698                max_attempts: Some(3),
25699                backoff_seconds: vec![1, 5],
25700                non_retryable_error_types: vec!["ValidationError".to_string()],
25701            })
25702            .execution_timeout_seconds(600)
25703            .run_timeout_seconds(120);
25704        let mut call = Box::pin(ctx.start_child_workflow(
25705            "python.fulfil-order",
25706            options,
25707            json!([{"order_id": "order-42"}]),
25708        ));
25709        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25710
25711        assert!(matches!(
25712            call.as_mut().poll(&mut task_context),
25713            Poll::Pending
25714        ));
25715        let commands = ctx.take_commands().expect("commands");
25716        assert_eq!(commands.len(), 1);
25717        let command = &commands[0];
25718        assert_eq!(command["type"], "start_child_workflow");
25719        assert_eq!(command["workflow_type"], "python.fulfil-order");
25720        assert_eq!(command["queue"], "python-workers");
25721        assert_eq!(command["parent_close_policy"], "request_cancel");
25722        assert_eq!(command["retry_policy"]["max_attempts"], 3);
25723        assert_eq!(command["execution_timeout_seconds"], 600);
25724        assert_eq!(command["run_timeout_seconds"], 120);
25725        assert_eq!(
25726            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
25727            json!([{"order_id": "order-42"}])
25728        );
25729    }
25730
25731    fn child_parent_worker() -> Worker {
25732        let client = Client::new("http://127.0.0.1:8080").expect("client");
25733        let mut worker = Worker::new(client, "rust-parent-workers");
25734        worker.register_workflow("rust.parent", |ctx, _input| async move {
25735            let child = ctx
25736                .start_child_workflow(
25737                    "python.child",
25738                    ChildWorkflowOptions::new("python-child-workers")
25739                        .parent_close_policy(ParentClosePolicy::Terminate),
25740                    json!([{"codec_probe": [1, true, "rust"]}]),
25741                )
25742                .await?;
25743            Ok(json!({
25744                "parent_workflow_id": child.parent.workflow_id,
25745                "parent_run_id": child.parent.run_id,
25746                "child_workflow_id": child.child.workflow_id,
25747                "child_run_id": child.child.run_id,
25748                "child_workflow_type": child.child_workflow_type,
25749                "result": child.result,
25750            }))
25751        });
25752        worker
25753    }
25754
25755    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
25756        WorkflowTask {
25757            task_id: "wft-child-parent".to_string(),
25758            workflow_command_id: None,
25759            workflow_id: Some("wf-parent".to_string()),
25760            run_id: Some("run-parent".to_string()),
25761            workflow_type: "rust.parent".to_string(),
25762            cancel_requested: false,
25763            payload_codec: DEFAULT_CODEC.to_string(),
25764            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25765            history_events: vec![
25766                HistoryEvent {
25767                    event_type: "ChildWorkflowScheduled".to_string(),
25768                    payload: json!({
25769                        "sequence": 1,
25770                        "child_call_id": "call-child",
25771                        "child_workflow_instance_id": "wf-child",
25772                        "child_workflow_run_id": "run-child",
25773                        "child_workflow_type": "python.child",
25774                        "parent_close_policy": "terminate",
25775                    }),
25776                    raw: HashMap::new(),
25777                },
25778                HistoryEvent {
25779                    event_type: event_type.to_string(),
25780                    payload,
25781                    raw: HashMap::new(),
25782                },
25783            ],
25784            total_history_events: Some(2),
25785            history_size_bytes: None,
25786            continue_as_new_recommended: None,
25787            history_budget_pressure: None,
25788            next_history_page_token: None,
25789            workflow_task_attempt: 1,
25790            workflow_signal_id: None,
25791            signal_name: None,
25792            signal_arguments: None,
25793            workflow_update_id: None,
25794            update_name: None,
25795            lease_owner: Some("rust-worker".to_string()),
25796        }
25797    }
25798
25799    #[test]
25800    fn committed_child_result_replays_without_starting_a_duplicate() {
25801        let worker = child_parent_worker();
25802        let task = child_parent_task(
25803            "ChildRunCompleted",
25804            json!({
25805                "sequence": 1,
25806                "child_call_id": "call-child",
25807                "child_workflow_instance_id": "wf-child",
25808                "child_workflow_run_id": "run-child",
25809                "child_workflow_type": "python.child",
25810                "payload_codec": DEFAULT_CODEC,
25811                "result": fixture_envelope(json!({"from":"python","ok":true})),
25812            }),
25813        );
25814
25815        for _restart in 0..2 {
25816            let commands = worker
25817                .execute_workflow_task(task.clone())
25818                .expect("replayed parent task");
25819            assert_eq!(commands.len(), 1);
25820            assert_eq!(commands[0]["type"], "complete_workflow");
25821            assert!(!commands
25822                .iter()
25823                .any(|command| command["type"] == "start_child_workflow"));
25824            let output =
25825                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25826            assert_eq!(output["parent_workflow_id"], "wf-parent");
25827            assert_eq!(output["parent_run_id"], "run-parent");
25828            assert_eq!(output["child_workflow_id"], "wf-child");
25829            assert_eq!(output["child_run_id"], "run-child");
25830            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
25831        }
25832    }
25833
25834    #[test]
25835    fn typed_child_arguments_and_results_survive_replay() {
25836        let client = Client::new("http://127.0.0.1:8080").expect("client");
25837        let mut worker = Worker::new(client, "rust-parent-workers");
25838        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
25839            let child = ctx
25840                .start_child_workflow_avro_value(
25841                    "python.typed-child",
25842                    ChildWorkflowOptions::new("python-workers"),
25843                    AvroValue::Array(vec![typed_fidelity_probe()]),
25844                )
25845                .await?;
25846            Ok(child.result)
25847        });
25848
25849        let initial = worker
25850            .execute_workflow_task(workflow_task(
25851                "rust.typed-parent",
25852                Vec::new(),
25853                DEFAULT_CODEC,
25854            ))
25855            .expect("typed child start");
25856        assert_eq!(initial[0]["type"], "start_child_workflow");
25857        assert_eq!(
25858            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
25859                .expect("typed child arguments"),
25860            AvroValue::Array(vec![typed_fidelity_probe()])
25861        );
25862
25863        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
25864            .expect("typed child result");
25865        let task = workflow_task(
25866            "rust.typed-parent",
25867            vec![
25868                history_event(
25869                    "ChildWorkflowScheduled",
25870                    json!({
25871                        "sequence": 1,
25872                        "child_call_id": "call-typed",
25873                        "child_workflow_instance_id": "wf-child",
25874                        "child_workflow_run_id": "run-child",
25875                        "child_workflow_type": "python.typed-child",
25876                    }),
25877                ),
25878                history_event(
25879                    "ChildRunCompleted",
25880                    json!({
25881                        "sequence": 1,
25882                        "child_call_id": "call-typed",
25883                        "child_workflow_instance_id": "wf-child",
25884                        "child_workflow_run_id": "run-child",
25885                        "child_workflow_type": "python.typed-child",
25886                        "payload_codec": DEFAULT_CODEC,
25887                        "result": result,
25888                    }),
25889                ),
25890            ],
25891            DEFAULT_CODEC,
25892        );
25893
25894        let commands = worker
25895            .execute_workflow_task(task)
25896            .expect("typed child replay");
25897        assert_eq!(commands[0]["type"], "complete_workflow");
25898        assert_eq!(
25899            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
25900                .expect("typed parent result"),
25901            typed_fidelity_probe()
25902        );
25903    }
25904
25905    #[test]
25906    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
25907        let worker = child_parent_worker();
25908        let mut task = child_parent_task("unused", Value::Null);
25909        task.history_events.truncate(1);
25910        task.total_history_events = Some(1);
25911
25912        for _redelivery_or_restart in 0..2 {
25913            let commands = worker
25914                .execute_workflow_task(task.clone())
25915                .expect("recorded child remains pending");
25916            assert!(
25917                commands.is_empty(),
25918                "recorded pending child must not be started again"
25919            );
25920        }
25921    }
25922
25923    #[test]
25924    fn child_cancellation_becomes_stable_parent_failure_command() {
25925        let worker = child_parent_worker();
25926        let task = child_parent_task(
25927            "ChildRunCancelled",
25928            json!({
25929                "sequence": 1,
25930                "child_workflow_instance_id": "wf-child",
25931                "child_workflow_run_id": "run-child",
25932                "child_workflow_type": "python.child",
25933                "failure_id": "failure-child",
25934                "failure_category": "cancelled",
25935                "message": "cancelled by parent-close policy",
25936            }),
25937        );
25938
25939        let commands = worker
25940            .execute_workflow_task(task)
25941            .expect("parent settlement");
25942        assert_eq!(commands.len(), 1);
25943        assert_eq!(commands[0]["type"], "fail_workflow");
25944        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
25945        assert_eq!(
25946            commands[0]["exception"]["properties"]["reason"],
25947            "cancelled"
25948        );
25949        assert_eq!(
25950            commands[0]["exception"]["properties"]["child_workflow_run_id"],
25951            "run-child"
25952        );
25953    }
25954
25955    #[test]
25956    fn workflow_can_handle_typed_child_failure() {
25957        let client = Client::new("http://127.0.0.1:8080").expect("client");
25958        let mut worker = Worker::new(client, "rust-parent-workers");
25959        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
25960            match ctx
25961                .start_child_workflow(
25962                    "python.child",
25963                    ChildWorkflowOptions::new("python-child-workers"),
25964                    json!([]),
25965                )
25966                .await
25967            {
25968                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
25969                    "reason": failure.reason,
25970                    "failure_id": failure.failure_id,
25971                    "exception_class": failure.exception_class,
25972                    "child_run_id": failure.child_workflow_run_id,
25973                })),
25974                Err(error) => Err(error),
25975                Ok(_) => Err(Error::WorkerLoop(
25976                    "child unexpectedly succeeded".to_string(),
25977                )),
25978            }
25979        });
25980        let mut task = child_parent_task(
25981            "ChildRunFailed",
25982            json!({
25983                "sequence": 1,
25984                "child_workflow_instance_id": "wf-child",
25985                "child_workflow_run_id": "run-child",
25986                "child_workflow_type": "python.child",
25987                "failure_id": "failure-child",
25988                "failure_category": "child_workflow",
25989                "message": "payment rejected",
25990                "exception": {
25991                    "type": "PaymentRejected",
25992                    "class": "payments.PaymentRejected",
25993                    "message": "payment rejected"
25994                }
25995            }),
25996        );
25997        task.workflow_type = "rust.handled-parent".to_string();
25998        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
25999
26000        let commands = worker.execute_workflow_task(task).expect("handled failure");
26001        assert_eq!(commands[0]["type"], "complete_workflow");
26002        let output =
26003            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26004        assert_eq!(output["reason"], "child_workflow");
26005        assert_eq!(output["failure_id"], "failure-child");
26006        assert_eq!(output["exception_class"], "payments.PaymentRejected");
26007        assert_eq!(output["child_run_id"], "run-child");
26008    }
26009
26010    #[test]
26011    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
26012        let client = Client::new("http://127.0.0.1:8080").expect("client");
26013        let mut worker = Worker::new(client, "rust-workers");
26014
26015        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
26016            let signal = ctx.wait_signal("start").await?;
26017            let name = signal
26018                .first()
26019                .and_then(|value| value.as_str())
26020                .unwrap_or("world");
26021            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
26022            Ok(json!({
26023                "greeting": greeting,
26024                "language": "rust"
26025            }))
26026        });
26027
26028        let signal_arguments =
26029            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
26030        let task = WorkflowTask {
26031            task_id: "wft-rust-signal-1".to_string(),
26032            workflow_command_id: None,
26033            workflow_id: Some("wf-rust-hello".to_string()),
26034            run_id: Some("run-rust-hello".to_string()),
26035            workflow_type: "rust.hello_workflow".to_string(),
26036            cancel_requested: false,
26037            payload_codec: DEFAULT_CODEC.to_string(),
26038            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26039            history_events: vec![HistoryEvent {
26040                event_type: "SignalReceived".to_string(),
26041                payload: json!({
26042                    "signal_id": "sig-rust-1",
26043                    "signal_name": "start"
26044                }),
26045                raw: HashMap::new(),
26046            }],
26047            total_history_events: Some(1),
26048            history_size_bytes: None,
26049            continue_as_new_recommended: None,
26050            history_budget_pressure: None,
26051            next_history_page_token: None,
26052            workflow_task_attempt: 1,
26053            workflow_signal_id: Some("sig-rust-1".to_string()),
26054            signal_name: Some("start".to_string()),
26055            signal_arguments: Some(signal_arguments),
26056            workflow_update_id: None,
26057            update_name: None,
26058            lease_owner: Some("rust-worker".to_string()),
26059        };
26060
26061        let commands = worker.execute_workflow_task(task).expect("workflow task");
26062
26063        assert_eq!(commands.len(), 1);
26064        assert_eq!(commands[0]["type"], "schedule_activity");
26065        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
26066        assert_eq!(
26067            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
26068            json!(["Rust"])
26069        );
26070    }
26071
26072    #[test]
26073    fn workflow_task_appends_paginated_history_events() {
26074        let mut task = WorkflowTask {
26075            task_id: "wft-rust-pages-1".to_string(),
26076            workflow_command_id: None,
26077            workflow_id: Some("wf-rust-pages".to_string()),
26078            run_id: Some("run-rust-pages".to_string()),
26079            workflow_type: "rust.hello_workflow".to_string(),
26080            cancel_requested: false,
26081            payload_codec: DEFAULT_CODEC.to_string(),
26082            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26083            history_events: vec![HistoryEvent {
26084                event_type: "WorkflowStarted".to_string(),
26085                payload: json!({}),
26086                raw: HashMap::new(),
26087            }],
26088            total_history_events: Some(3),
26089            history_size_bytes: None,
26090            continue_as_new_recommended: None,
26091            history_budget_pressure: None,
26092            next_history_page_token: Some("MQ==".to_string()),
26093            workflow_task_attempt: 1,
26094            workflow_signal_id: None,
26095            signal_name: None,
26096            signal_arguments: None,
26097            workflow_update_id: None,
26098            update_name: None,
26099            lease_owner: Some("rust-worker".to_string()),
26100        };
26101
26102        task.append_history_page(WorkflowTaskHistoryPage {
26103            history_events: vec![
26104                HistoryEvent {
26105                    event_type: "SignalReceived".to_string(),
26106                    payload: json!({
26107                        "signal_id": "sig-rust-1",
26108                        "signal_name": "start",
26109                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
26110                            .expect("signal arguments")
26111                    }),
26112                    raw: HashMap::new(),
26113                },
26114                HistoryEvent {
26115                    event_type: "MarkerRecorded".to_string(),
26116                    payload: json!({"sequence": 3}),
26117                    raw: HashMap::new(),
26118                },
26119            ],
26120            total_history_events: Some(3),
26121            next_history_page_token: None,
26122        });
26123
26124        assert_eq!(task.history_events.len(), 3);
26125        assert_eq!(task.total_history_events, Some(3));
26126        assert_eq!(task.next_history_page_token, None);
26127
26128        let signal = task
26129            .history_events
26130            .iter()
26131            .find(|event| event.event_type == "SignalReceived")
26132            .expect("signal event");
26133        assert_eq!(
26134            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
26135            vec![AvroValue::String("Rust".to_string())]
26136        );
26137    }
26138
26139    #[tokio::test]
26140    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
26141        let client = Client::new("http://127.0.0.1:8080").expect("client");
26142        let mut worker = Worker::new(client, "rust-workers");
26143        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26144        worker.register_query("counter", "current", |ctx, _args| async move {
26145            let mut count = 0_i64;
26146            for signal in ctx.signal_events() {
26147                let value = signal
26148                    .arguments
26149                    .first()
26150                    .and_then(Value::as_i64)
26151                    .unwrap_or_default();
26152                match signal.name.as_str() {
26153                    "increment" => count += value,
26154                    "set" => count = value,
26155                    _ => {}
26156                }
26157            }
26158            Ok(json!(count))
26159        });
26160
26161        let task = QueryTask {
26162            query_task_id: "query-rust-counter".to_string(),
26163            query_task_attempt: 1,
26164            lease_owner: Some("rust-worker".to_string()),
26165            workflow_id: Some("counter-1".to_string()),
26166            run_id: Some("run-counter-1".to_string()),
26167            workflow_type: "counter".to_string(),
26168            query_name: "current".to_string(),
26169            payload_codec: DEFAULT_CODEC.to_string(),
26170            workflow_arguments: Some(
26171                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26172            ),
26173            query_arguments: Some(
26174                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
26175            ),
26176            history_events: vec![
26177                HistoryEvent {
26178                    event_type: "SignalReceived".to_string(),
26179                    payload: json!({
26180                        "signal_id": "php-signal-1",
26181                        "signal_name": "increment",
26182                        "workflow_sequence": 1,
26183                        "payload_codec": DEFAULT_CODEC,
26184                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
26185                    }),
26186                    raw: HashMap::new(),
26187                },
26188                HistoryEvent {
26189                    event_type: "SignalReceived".to_string(),
26190                    payload: json!({
26191                        "signal_id": "python-signal-2",
26192                        "signal_name": "increment",
26193                        "workflow_sequence": 2,
26194                        "payload_codec": DEFAULT_CODEC,
26195                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
26196                    }),
26197                    raw: HashMap::new(),
26198                },
26199                HistoryEvent {
26200                    event_type: "SignalReceived".to_string(),
26201                    payload: json!({
26202                        "signal_id": "rust-signal-3",
26203                        "signal_name": "set",
26204                        "workflow_sequence": 3,
26205                        "payload_codec": DEFAULT_CODEC,
26206                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
26207                    }),
26208                    raw: HashMap::new(),
26209                },
26210            ],
26211            history_export: None,
26212            run_status: Some("completed".to_string()),
26213        };
26214
26215        let result = worker.execute_query_task(task).await.expect("query result");
26216        assert_eq!(result.into_json().expect("query projection"), json!(0));
26217    }
26218
26219    #[tokio::test]
26220    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
26221        let worker = replay_counter_worker();
26222        let running_history = json!([
26223            {
26224                "type": "ActivityCompleted",
26225                "payload": {
26226                    "sequence": 1,
26227                    "activity_type": "load-counter",
26228                    "payload_codec": DEFAULT_CODEC,
26229                    "result": fixture_envelope(json!("loaded"))
26230                }
26231            },
26232            {
26233                "type": "SignalWaitOpened",
26234                "payload": {
26235                    "sequence": 3,
26236                    "signal_name": "increment"
26237                }
26238            },
26239            {
26240                "type": "SignalReceived",
26241                "payload": {
26242                    "signal_id": "signal-3",
26243                    "signal_name": "increment",
26244                    "workflow_sequence": 2,
26245                    "payload_codec": DEFAULT_CODEC,
26246                    "arguments": fixture_envelope(json!([3]))
26247                }
26248            },
26249            {
26250                "type": "SignalApplied",
26251                "payload": {
26252                    "sequence": 3,
26253                    "signal_id": "signal-3",
26254                    "signal_name": "increment",
26255                    "payload_codec": DEFAULT_CODEC,
26256                    "value": fixture_envelope(json!([3]))
26257                }
26258            }
26259        ]);
26260
26261        let running = worker
26262            .execute_query_task(replay_counter_query(
26263                "current",
26264                running_history.clone(),
26265                "running",
26266            ))
26267            .await
26268            .expect("running replay query");
26269        assert_eq!(
26270            running.clone().into_json().expect("query projection"),
26271            json!({"loaded": "loaded", "count": 3, "finished": false})
26272        );
26273
26274        let detached = worker
26275            .execute_query_task(replay_counter_query(
26276                "detached-mutation",
26277                running_history.clone(),
26278                "running",
26279            ))
26280            .await
26281            .expect("query mutates only its detached state clone");
26282        assert_eq!(detached.into_json().expect("query projection"), json!(999));
26283        let failed = worker
26284            .execute_query_task(replay_counter_query(
26285                "failed-mutation",
26286                running_history.clone(),
26287                "running",
26288            ))
26289            .await
26290            .expect_err("failed query");
26291        assert_eq!(failed.reason, "query_rejected");
26292        let unchanged = worker
26293            .execute_query_task(replay_counter_query("current", running_history, "running"))
26294            .await
26295            .expect("later query reconstructs unchanged state");
26296        assert_eq!(unchanged, running);
26297
26298        let restarted_worker = replay_counter_worker();
26299        let empty_arguments = fixture_envelope(json!([]));
26300        let loaded_result = fixture_envelope(json!("loaded"));
26301        let signal_three = fixture_blob(json!([3]));
26302        let signal_five = fixture_blob(json!([5]));
26303        let restarted_task: QueryTask = serde_json::from_value(json!({
26304            "query_task_id": "query-after-restart",
26305            "workflow_id": "counter-1",
26306            "run_id": "run-counter-1",
26307            "workflow_type": "replay-counter",
26308            "query_name": "current",
26309            "payload_codec": DEFAULT_CODEC,
26310            "workflow_arguments": empty_arguments.clone(),
26311            "query_arguments": empty_arguments,
26312            "history_events": [],
26313            "history_export": {
26314                "payloads": {"codec": DEFAULT_CODEC},
26315                "history_events": [
26316                    {
26317                        "type": "ActivityCompleted",
26318                        "payload": {
26319                            "sequence": 1,
26320                            "activity_type": "load-counter",
26321                            "payload_codec": DEFAULT_CODEC,
26322                            "result": null
26323                        }
26324                    },
26325                    {
26326                        "type": "SignalWaitOpened",
26327                        "payload": {
26328                            "sequence": 3,
26329                            "signal_name": "increment"
26330                        }
26331                    },
26332                    {
26333                        "type": "SignalReceived",
26334                        "payload": {
26335                            "signal_id": "signal-3",
26336                            "signal_name": "increment",
26337                            "workflow_sequence": 2
26338                        }
26339                    },
26340                    {
26341                        "type": "SignalApplied",
26342                        "payload": {
26343                            "sequence": 3,
26344                            "signal_id": "signal-3",
26345                            "signal_name": "increment"
26346                        }
26347                    },
26348                    {
26349                        "type": "SignalWaitOpened",
26350                        "payload": {
26351                            "sequence": 5,
26352                            "signal_name": "increment"
26353                        }
26354                    },
26355                    {
26356                        "type": "SignalReceived",
26357                        "payload": {
26358                            "signal_id": "signal-5",
26359                            "signal_name": "increment",
26360                            "workflow_sequence": 4
26361                        }
26362                    },
26363                    {
26364                        "type": "SignalApplied",
26365                        "payload": {
26366                            "sequence": 5,
26367                            "signal_id": "signal-5",
26368                            "signal_name": "increment"
26369                        }
26370                    }
26371                ],
26372                "activities": [{
26373                    "sequence": 1,
26374                    "activity_type": "load-counter",
26375                    "payload_codec": DEFAULT_CODEC,
26376                    "result": loaded_result
26377                }],
26378                "signals": [
26379                    {
26380                        "id": "signal-3",
26381                        "name": "increment",
26382                        "workflow_sequence": 2,
26383                        "payload_codec": DEFAULT_CODEC,
26384                        "arguments": signal_three
26385                    },
26386                    {
26387                        "id": "signal-5",
26388                        "name": "increment",
26389                        "workflow_sequence": 4,
26390                        "payload_codec": DEFAULT_CODEC,
26391                        "arguments": signal_five
26392                    }
26393                ]
26394            },
26395            "run_status": "completed"
26396        }))
26397        .expect("cold replay query task");
26398        let completed = restarted_worker
26399            .execute_query_task(restarted_task)
26400            .await
26401            .expect("completed cold replay query");
26402        assert_eq!(
26403            completed.into_json().expect("query projection"),
26404            json!({"loaded": "loaded", "count": 8, "finished": true})
26405        );
26406    }
26407
26408    #[tokio::test]
26409    async fn replayed_query_replay_failures_are_machine_readable() {
26410        let worker = replay_counter_worker();
26411        let task = replay_counter_query(
26412            "current",
26413            json!([{
26414                "type": "ActivityCompleted",
26415                "payload": {
26416                    "sequence": 1,
26417                    "payload_codec": DEFAULT_CODEC,
26418                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
26419                }
26420            }]),
26421            "running",
26422        );
26423        let failure = worker
26424            .execute_query_task(task)
26425            .await
26426            .expect_err("invalid replay history payload");
26427        assert_eq!(failure.reason, "query_payload_decode_failed");
26428        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
26429        assert!(failure.message.contains("invalid_payload_framing"));
26430    }
26431
26432    #[tokio::test]
26433    async fn query_task_restores_compact_history_from_export() {
26434        let client = Client::new("http://127.0.0.1:8080").expect("client");
26435        let mut worker = Worker::new(client, "rust-workers");
26436        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26437        worker.register_query("counter", "current", |ctx, _args| async move {
26438            Ok(json!(ctx.signals("increment")[0][0]))
26439        });
26440        let empty_arguments = fixture_envelope(json!([]));
26441        let exported_signal = fixture_blob(json!([9]));
26442        let task: QueryTask = serde_json::from_value(json!({
26443            "query_task_id": "query-export",
26444            "workflow_type": "counter",
26445            "query_name": "current",
26446            "payload_codec": DEFAULT_CODEC,
26447            "workflow_arguments": empty_arguments.clone(),
26448            "query_arguments": empty_arguments,
26449            "history_events": [],
26450            "history_export": {
26451                "payloads": {"codec": DEFAULT_CODEC},
26452                "history_events": [{
26453                    "type": "SignalReceived",
26454                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
26455                }],
26456                "signals": [{
26457                    "id": "signal-export",
26458                    "name": "increment",
26459                    "status": "applied",
26460                    "workflow_sequence": 1,
26461                    "payload_codec": DEFAULT_CODEC,
26462                    "arguments": exported_signal
26463                }]
26464            }
26465        }))
26466        .expect("query task");
26467
26468        let result = worker.execute_query_task(task).await.expect("query result");
26469        assert_eq!(result.into_json().expect("query projection"), json!(9));
26470    }
26471
26472    #[tokio::test]
26473    async fn query_task_failures_have_stable_reasons() {
26474        let client = Client::new("http://127.0.0.1:8080").expect("client");
26475        let mut worker = Worker::new(client, "rust-workers");
26476        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26477        worker.register_query(
26478            "counter",
26479            "current",
26480            |_ctx, _args| async move { Ok(json!(0)) },
26481        );
26482
26483        let base_task = QueryTask {
26484            query_task_id: "query-errors".to_string(),
26485            query_task_attempt: 1,
26486            lease_owner: None,
26487            workflow_id: Some("counter-errors".to_string()),
26488            run_id: Some("run-errors".to_string()),
26489            workflow_type: "counter".to_string(),
26490            query_name: "missing".to_string(),
26491            payload_codec: DEFAULT_CODEC.to_string(),
26492            workflow_arguments: Some(fixture_envelope(json!([]))),
26493            query_arguments: Some(fixture_envelope(json!([]))),
26494            history_events: Vec::new(),
26495            history_export: None,
26496            run_status: Some("running".to_string()),
26497        };
26498
26499        let unknown = worker
26500            .execute_query_task(base_task.clone())
26501            .await
26502            .expect_err("unknown query");
26503        assert_eq!(unknown.reason, "rejected_unknown_query");
26504
26505        let mut malformed = base_task;
26506        malformed.query_name = "current".to_string();
26507        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
26508        let malformed = worker
26509            .execute_query_task(malformed)
26510            .await
26511            .expect_err("malformed payload");
26512        assert_eq!(malformed.reason, "query_payload_decode_failed");
26513
26514        let client = Client::new("http://127.0.0.1:8080").expect("client");
26515        let mut unavailable_worker = Worker::new(client, "rust-workers");
26516        unavailable_worker
26517            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26518        let empty_arguments = fixture_envelope(json!([]));
26519        let unavailable_task: QueryTask = serde_json::from_value(json!({
26520            "query_task_id": "query-unavailable",
26521            "workflow_type": "counter",
26522            "query_name": "current",
26523            "payload_codec": DEFAULT_CODEC,
26524            "workflow_arguments": empty_arguments.clone(),
26525            "query_arguments": empty_arguments
26526        }))
26527        .expect("query task");
26528        let unavailable = unavailable_worker
26529            .execute_query_task(unavailable_task)
26530            .await
26531            .expect_err("query handler unavailable");
26532        assert_eq!(unavailable.reason, "query_handler_unavailable");
26533    }
26534
26535    #[tokio::test]
26536    async fn client_query_decodes_result_and_typed_failure() {
26537        let server = MockWorkerServer::start();
26538        let client = Client::builder(server.base_url())
26539            .timeout(Duration::from_secs(2))
26540            .build()
26541            .expect("client");
26542
26543        let result = client
26544            .query_workflow("counter-1", "current", json!([]))
26545            .await
26546            .expect("query result");
26547        assert_eq!(result, json!({"count": 8}));
26548
26549        let error = client
26550            .query_workflow("counter-1", "missing", json!([]))
26551            .await
26552            .expect_err("unknown query");
26553        let Error::QueryFailed(failure) = error else {
26554            panic!("expected typed query failure");
26555        };
26556        assert_eq!(failure.status, 404);
26557        assert_eq!(failure.reason, "rejected_unknown_query");
26558    }
26559
26560    #[tokio::test]
26561    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
26562        let server = MockWorkerServer::start();
26563        let client = Client::builder(server.base_url())
26564            .timeout(Duration::from_secs(2))
26565            .build()
26566            .expect("client");
26567        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
26568
26569        client
26570            .start_workflow(
26571                "typed.echo",
26572                "rust-workers",
26573                "typed-start",
26574                arguments.clone(),
26575            )
26576            .await
26577            .expect("typed workflow start");
26578        assert_eq!(
26579            decode_wire_avro_value(
26580                &server.request_body("/api/workflows")["input"],
26581                DEFAULT_CODEC,
26582            )
26583            .expect("typed start input"),
26584            arguments
26585        );
26586
26587        client
26588            .signal_workflow("typed-1", "changed", arguments.clone())
26589            .await
26590            .expect("typed signal");
26591        assert_eq!(
26592            decode_wire_avro_value(
26593                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
26594                DEFAULT_CODEC,
26595            )
26596            .expect("typed signal input"),
26597            arguments
26598        );
26599
26600        assert_eq!(
26601            client
26602                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
26603                .await
26604                .expect("typed query"),
26605            typed_fidelity_probe()
26606        );
26607        assert_eq!(
26608            decode_wire_avro_value(
26609                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
26610                DEFAULT_CODEC,
26611            )
26612            .expect("typed query input"),
26613            arguments
26614        );
26615
26616        assert_eq!(
26617            client
26618                .update_workflow_avro_value(
26619                    "typed-1",
26620                    "replace",
26621                    arguments.clone(),
26622                    Some("typed-request"),
26623                )
26624                .await
26625                .expect("typed update"),
26626            typed_fidelity_probe()
26627        );
26628        let update = server.request_body("/api/workflows/typed-1/update/replace");
26629        assert_eq!(update["request_id"], "typed-request");
26630        assert_eq!(
26631            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
26632            arguments
26633        );
26634
26635        let handle = WorkflowHandle {
26636            client: client.clone(),
26637            workflow_id: "typed-1".to_string(),
26638            run_id: Some("run-typed-1".to_string()),
26639            workflow_type: "typed.echo".to_string(),
26640        };
26641        assert_eq!(
26642            handle
26643                .result_avro_value(WorkflowResultOptions::default())
26644                .await
26645                .expect("typed workflow result"),
26646            typed_fidelity_probe()
26647        );
26648
26649        client
26650            .complete_activity_task(
26651                "activity-typed",
26652                "attempt-typed",
26653                "rust-worker",
26654                typed_fidelity_probe(),
26655                DEFAULT_CODEC,
26656            )
26657            .await
26658            .expect("typed activity completion");
26659        assert_eq!(
26660            decode_wire_avro_value(
26661                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
26662                    ["result"],
26663                DEFAULT_CODEC,
26664            )
26665            .expect("typed activity result"),
26666            typed_fidelity_probe()
26667        );
26668        client
26669            .fail_activity_task(
26670                "activity-typed",
26671                "attempt-typed",
26672                "rust-worker",
26673                "typed failure",
26674                true,
26675            )
26676            .await
26677            .expect("activity failure");
26678    }
26679
26680    #[tokio::test]
26681    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
26682        let server = MockWorkerServer::start();
26683        let client = Client::builder(server.base_url())
26684            .timeout(Duration::from_secs(2))
26685            .build()
26686            .expect("client");
26687
26688        let options = WorkflowCommandOptions::new()
26689            .reason("cleanup requested")
26690            .request_id("cancel-17");
26691        let cancelled = client
26692            .cancel_workflow("wf-lifecycle", options)
26693            .await
26694            .expect("instance cancellation");
26695        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
26696        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
26697        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
26698        assert_eq!(
26699            server.request_body("/api/workflows/wf-lifecycle/cancel"),
26700            json!({"reason":"cleanup requested","request_id":"cancel-17"})
26701        );
26702
26703        let terminated = client
26704            .terminate_workflow(
26705                "wf-lifecycle",
26706                WorkflowCommandOptions::new().reason("forced stop"),
26707            )
26708            .await
26709            .expect("instance termination");
26710        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
26711        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
26712
26713        client
26714            .cancel_workflow_run(
26715                "wf-lifecycle",
26716                "run-current",
26717                WorkflowCommandOptions::default(),
26718            )
26719            .await
26720            .expect("selected run cancellation");
26721        client
26722            .terminate_workflow_run(
26723                "wf-lifecycle",
26724                "run-current",
26725                WorkflowCommandOptions::default(),
26726            )
26727            .await
26728            .expect("selected run termination");
26729
26730        for (command, error) in [
26731            (
26732                WorkflowCommandKind::Cancel,
26733                client
26734                    .cancel_workflow_run(
26735                        "wf-lifecycle",
26736                        "run-stale",
26737                        WorkflowCommandOptions::default(),
26738                    )
26739                    .await
26740                    .expect_err("stale cancellation must be rejected"),
26741            ),
26742            (
26743                WorkflowCommandKind::Terminate,
26744                client
26745                    .terminate_workflow_run(
26746                        "wf-lifecycle",
26747                        "run-stale",
26748                        WorkflowCommandOptions::default(),
26749                    )
26750                    .await
26751                    .expect_err("stale termination must be rejected"),
26752            ),
26753        ] {
26754            let Error::WorkflowCommandRejected(rejection) = error else {
26755                panic!("expected typed command rejection");
26756            };
26757            assert_eq!(rejection.command, command);
26758            assert_eq!(rejection.status, 409);
26759            assert_eq!(rejection.reason, "historical_run_command_rejected");
26760            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
26761            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
26762        }
26763    }
26764
26765    #[tokio::test]
26766    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
26767        let server = MockWorkerServer::start();
26768        let client = Client::builder(server.base_url())
26769            .timeout(Duration::from_secs(2))
26770            .build()
26771            .expect("client");
26772
26773        let result = client
26774            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
26775            .await
26776            .expect("redrive accepted");
26777        assert_eq!(result.workflow_id, "wf-lifecycle");
26778        assert_eq!(result.source_run_id, "run-failed");
26779        assert_eq!(result.run_id, "run-successor");
26780        assert_eq!(result.resume_step_sequence, 2);
26781        assert_eq!(
26782            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
26783            json!({"request_id":"retry-1"})
26784        );
26785
26786        let repeated = client
26787            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
26788            .await
26789            .expect("idempotent redrive response accepted");
26790        assert_eq!(repeated.run_id, "run-successor");
26791
26792        let error = client
26793            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
26794            .await
26795            .expect_err("completed run must be rejected");
26796        let Error::Http { status, body } = error else {
26797            panic!("expected HTTP redrive rejection");
26798        };
26799        assert_eq!(status.as_u16(), 409);
26800        assert!(body.contains("run_not_failed"));
26801        assert_eq!(
26802            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
26803            json!({})
26804        );
26805
26806        let handle = WorkflowHandle {
26807            client: client.clone(),
26808            workflow_id: "wf-lifecycle".to_string(),
26809            run_id: Some("run-failed".to_string()),
26810            workflow_type: "test".to_string(),
26811        };
26812        assert_eq!(
26813            handle.redrive(None).await.expect("handle redrive").run_id,
26814            "run-successor"
26815        );
26816        let missing_run = WorkflowHandle {
26817            run_id: None,
26818            ..handle
26819        };
26820        assert!(matches!(
26821            missing_run.redrive(None).await,
26822            Err(Error::Codec(_))
26823        ));
26824    }
26825
26826    #[tokio::test]
26827    async fn workflow_start_options_send_server_enforced_deadlines() {
26828        let server = MockWorkerServer::start();
26829        let client = Client::builder(server.base_url())
26830            .timeout(Duration::from_secs(2))
26831            .build()
26832            .expect("client");
26833
26834        let handle = client
26835            .start_workflow_with_options(
26836                "rust.timeout",
26837                "rust-timeouts",
26838                "wf-start-options",
26839                WorkflowStartOptions::new()
26840                    .execution_timeout_seconds(30)
26841                    .run_timeout_seconds(1),
26842                json!([]),
26843            )
26844            .await
26845            .expect("workflow start");
26846
26847        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
26848        let body = server.request_body("/api/workflows");
26849        assert_eq!(body["execution_timeout_seconds"], 30);
26850        assert_eq!(body["run_timeout_seconds"], 1);
26851
26852        let invalid = client
26853            .start_workflow_with_options(
26854                "rust.timeout",
26855                "rust-timeouts",
26856                "wf-invalid-options",
26857                WorkflowStartOptions::new()
26858                    .execution_timeout_seconds(1)
26859                    .run_timeout_seconds(2),
26860                json!([]),
26861            )
26862            .await
26863            .expect_err("invalid deadline ordering");
26864        assert!(invalid
26865            .to_string()
26866            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
26867    }
26868
26869    #[tokio::test]
26870    async fn workflow_result_returns_each_typed_terminal_outcome() {
26871        let server = MockWorkerServer::start();
26872        let client = Client::builder(server.base_url())
26873            .timeout(Duration::from_secs(2))
26874            .build()
26875            .expect("client");
26876        let options = WorkflowResultOptions {
26877            poll_interval: Duration::ZERO,
26878            timeout: Duration::from_secs(1),
26879        };
26880
26881        let failed = WorkflowHandle {
26882            client: client.clone(),
26883            workflow_id: "wf-failed".to_string(),
26884            run_id: Some("run-failed".to_string()),
26885            workflow_type: "failure".to_string(),
26886        }
26887        .result(options)
26888        .await
26889        .expect_err("failed outcome");
26890        let Error::WorkflowFailed(failure) = failed else {
26891            panic!("expected WorkflowFailed");
26892        };
26893        assert_eq!(failure.workflow_id, "wf-failed");
26894        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
26895        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
26896        assert_eq!(failure.failure_category.as_deref(), Some("application"));
26897        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
26898        assert_eq!(
26899            failure.exception_class.as_deref(),
26900            Some("billing::PaymentError")
26901        );
26902        assert_eq!(failure.non_retryable, Some(true));
26903
26904        for (workflow_id, expected_kind, expected_reason) in [
26905            (
26906                "wf-cancelled",
26907                WorkflowTerminalKind::Cancelled,
26908                "cleanup requested",
26909            ),
26910            (
26911                "wf-terminated",
26912                WorkflowTerminalKind::Terminated,
26913                "forced stop",
26914            ),
26915            (
26916                "wf-timed-out",
26917                WorkflowTerminalKind::TimedOut,
26918                "run_timeout",
26919            ),
26920        ] {
26921            let error = WorkflowHandle {
26922                client: client.clone(),
26923                workflow_id: workflow_id.to_string(),
26924                run_id: None,
26925                workflow_type: "terminal".to_string(),
26926            }
26927            .result(options)
26928            .await
26929            .expect_err("typed terminal outcome");
26930            let outcome = match error {
26931                Error::WorkflowCancelled(outcome) => outcome,
26932                Error::WorkflowTerminated(outcome) => outcome,
26933                Error::WorkflowTimedOut(outcome) => outcome,
26934                other => panic!("unexpected terminal error: {other}"),
26935            };
26936            assert_eq!(outcome.kind, expected_kind);
26937            assert_eq!(outcome.workflow_id, workflow_id);
26938            assert_eq!(outcome.reason, expected_reason);
26939        }
26940
26941        let wait_timeout = WorkflowHandle {
26942            client,
26943            workflow_id: "wf-waiting".to_string(),
26944            run_id: Some("run-waiting".to_string()),
26945            workflow_type: "waiting".to_string(),
26946        }
26947        .result(WorkflowResultOptions {
26948            poll_interval: Duration::ZERO,
26949            timeout: Duration::ZERO,
26950        })
26951        .await
26952        .expect_err("client wait timeout");
26953        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
26954            panic!("expected typed client timeout");
26955        };
26956        assert_eq!(timeout.reason, "result_wait_timeout");
26957        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
26958        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
26959    }
26960
26961    #[tokio::test]
26962    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
26963        let server = MockWorkerServer::start();
26964        let client = Client::builder(server.base_url())
26965            .timeout(Duration::from_secs(2))
26966            .build()
26967            .expect("client");
26968
26969        let handle = WorkflowHandle {
26970            client,
26971            workflow_id: "wf-selected".to_string(),
26972            run_id: Some("run-selected".to_string()),
26973            workflow_type: "selected".to_string(),
26974        };
26975        let options = WorkflowResultOptions {
26976            poll_interval: Duration::ZERO,
26977            timeout: Duration::from_secs(1),
26978        };
26979
26980        let current = handle
26981            .result(options)
26982            .await
26983            .expect("instance result follows the current run");
26984        assert_eq!(current, json!("current run output"));
26985
26986        let error = handle
26987            .result_selected_run(options)
26988            .await
26989            .expect_err("the selected run is cancelled even though the current run completed");
26990
26991        let Error::WorkflowCancelled(outcome) = error else {
26992            panic!("expected selected run cancellation");
26993        };
26994        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
26995        assert_eq!(outcome.reason, "selected run cancelled");
26996        assert_eq!(
26997            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
26998            1
26999        );
27000        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
27001    }
27002
27003    #[tokio::test]
27004    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
27005        let server = MockWorkerServer::draining_polls();
27006        let client = Client::builder(server.base_url())
27007            .timeout(Duration::from_secs(2))
27008            .build()
27009            .expect("client");
27010
27011        let workflow = client
27012            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
27013            .await
27014            .expect("workflow drain response");
27015        let activity = client
27016            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
27017            .await
27018            .expect("activity drain response");
27019        let query = client
27020            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
27021            .await
27022            .expect("query drain response");
27023
27024        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
27025            assert_eq!(
27026                outcome,
27027                WorkerPollOutcome::Stop {
27028                    poll_status: Some("draining".to_string()),
27029                    reason: Some("worker_draining".to_string()),
27030                }
27031            );
27032        }
27033
27034        assert!(client
27035            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
27036            .await
27037            .expect("compatibility poll")
27038            .is_none());
27039    }
27040
27041    #[tokio::test]
27042    async fn managed_worker_honors_drain_stop_for_every_task_family() {
27043        let server = MockWorkerServer::draining_polls();
27044        let client = Client::builder(server.base_url())
27045            .timeout(Duration::from_secs(2))
27046            .build()
27047            .expect("client");
27048
27049        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
27050            .worker_id("draining-workflow-worker")
27051            .poll_timeout(Duration::ZERO);
27052        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
27053        workflow_worker
27054            .run()
27055            .await
27056            .expect("workflow drain is a clean stop");
27057
27058        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
27059            .worker_id("draining-activity-worker")
27060            .poll_timeout(Duration::ZERO);
27061        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
27062        activity_worker
27063            .run()
27064            .await
27065            .expect("activity drain is a clean stop");
27066
27067        let mut query_worker = Worker::new(client, "rust-workers")
27068            .worker_id("draining-query-worker")
27069            .poll_timeout(Duration::ZERO);
27070        query_worker.register_query("counter", "current", |_ctx, _args| async {
27071            Ok(Value::Null)
27072        });
27073        query_worker
27074            .run()
27075            .await
27076            .expect("query drain is a clean stop");
27077    }
27078
27079    #[tokio::test]
27080    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
27081        let server = MockWorkerServer::start();
27082        let client = Client::builder(server.base_url())
27083            .timeout(Duration::from_secs(2))
27084            .build()
27085            .expect("client");
27086
27087        let details: Value = serde_json::from_str(include_str!(
27088            "../tests/fixtures/activity-heartbeat-progress.json"
27089        ))
27090        .expect("heartbeat progress fixture");
27091        // Every individual field fits Server's progress contract, while the
27092        // obsolete encoded envelope exceeded its 191-character string limit.
27093        assert!(
27094            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
27095                .unwrap()["blob"]
27096                .as_str()
27097                .unwrap()
27098                .len()
27099                > 191
27100        );
27101        let heartbeat = client
27102            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
27103            .await
27104            .expect("cancellation heartbeat");
27105        assert!(heartbeat.cancel_requested);
27106        assert!(heartbeat.should_stop());
27107        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
27108        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
27109        let heartbeat_body =
27110            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
27111        assert_eq!(heartbeat_body["details"], details);
27112        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
27113        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
27114
27115        let error = client
27116            .complete_activity_task(
27117                "activity-cancel",
27118                "attempt-cancel",
27119                "rust-worker",
27120                json!({"late":true}),
27121                DEFAULT_CODEC,
27122            )
27123            .await
27124            .expect_err("late completion must be refused");
27125        assert!(activity_task_rejection_is_final(&error));
27126        let Error::ActivityTaskRejected(rejection) = error else {
27127            panic!("expected typed activity rejection");
27128        };
27129        assert_eq!(rejection.status, 409);
27130        assert_eq!(rejection.reason, "run_cancelled");
27131        assert!(rejection.cancel_requested);
27132        assert_eq!(rejection.can_continue, Some(false));
27133    }
27134
27135    #[tokio::test]
27136    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
27137        let server = MockWorkerServer::cancelled_activity();
27138        let client = Client::builder(server.base_url())
27139            .timeout(Duration::from_secs(2))
27140            .build()
27141            .expect("client");
27142        let cancellation_observed = Arc::new(AtomicBool::new(false));
27143        let observed = Arc::clone(&cancellation_observed);
27144        let mut worker = Worker::new(client.clone(), "rust-workers")
27145            .worker_id("rust-cancel-worker")
27146            .poll_timeout(Duration::from_millis(10));
27147        worker.register_activity("cancel-aware", move |ctx, _args| {
27148            let observed = Arc::clone(&observed);
27149            async move {
27150                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
27151                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
27152                Ok(json!({"late":"completion"}))
27153            }
27154        });
27155
27156        assert_eq!(
27157            worker.run_once().await.expect("cancelled attempt handled"),
27158            1
27159        );
27160        assert!(cancellation_observed.load(Ordering::SeqCst));
27161        assert_eq!(
27162            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
27163            1
27164        );
27165
27166        let mut restarted = Worker::new(client, "rust-workers")
27167            .worker_id("rust-cancel-worker-restarted")
27168            .poll_timeout(Duration::from_millis(10));
27169        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
27170        assert_eq!(
27171            restarted
27172                .run_once()
27173                .await
27174                .expect("replacement worker continues polling"),
27175            0
27176        );
27177    }
27178
27179    #[tokio::test]
27180    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
27181        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"}"#;
27182        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
27183        let client = Client::builder(server.base_url())
27184            .timeout(Duration::from_secs(2))
27185            .build()
27186            .expect("client");
27187
27188        let direct_error = client
27189            .complete_workflow_task(
27190                "workflow-timeout-task",
27191                "timeout-worker",
27192                3,
27193                vec![json!({
27194                    "type": "complete_workflow",
27195                    "result": fixture_envelope(Value::Null)
27196                })],
27197            )
27198            .await
27199            .expect_err("the low-level client preserves the completion rejection");
27200        let Error::Http { status, body } = direct_error else {
27201            panic!("expected the original HTTP completion rejection");
27202        };
27203        assert_eq!(status, reqwest::StatusCode::CONFLICT);
27204        assert_eq!(
27205            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
27206            "run_timed_out"
27207        );
27208
27209        let mut worker = Worker::new(client, "rust-workers")
27210            .worker_id("timeout-worker")
27211            .poll_timeout(Duration::from_millis(10));
27212        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
27213            Ok(json!({"late": "result"}))
27214        });
27215
27216        assert_eq!(
27217            worker
27218                .run_once()
27219                .await
27220                .expect("authoritative selected-run timeout settles the tick"),
27221            1
27222        );
27223        assert_eq!(
27224            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
27225            2,
27226            "both the direct client proof and managed worker must see the rejection"
27227        );
27228    }
27229
27230    #[tokio::test]
27231    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
27232        for (name, status, response) in [
27233            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
27234            (
27235                "command was recorded",
27236                "409 Conflict",
27237                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27238            ),
27239            (
27240                "lease conflict",
27241                "409 Conflict",
27242                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
27243            ),
27244            (
27245                "nonterminal run",
27246                "409 Conflict",
27247                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
27248            ),
27249            (
27250                "different selected run",
27251                "409 Conflict",
27252                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"}"#,
27253            ),
27254            (
27255                "different task attempt",
27256                "409 Conflict",
27257                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27258            ),
27259            (
27260                "authentication failure",
27261                "401 Unauthorized",
27262                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27263            ),
27264            (
27265                "authorization failure",
27266                "403 Forbidden",
27267                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27268            ),
27269            (
27270                "protocol failure",
27271                "400 Bad Request",
27272                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
27273            ),
27274            (
27275                "malformed command",
27276                "422 Unprocessable Entity",
27277                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27278            ),
27279            (
27280                "transient server failure",
27281                "503 Service Unavailable",
27282                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27283            ),
27284        ] {
27285            let server = MockWorkerServer::workflow_completion(status, response);
27286            let client = Client::builder(server.base_url())
27287                .timeout(Duration::from_secs(2))
27288                .build()
27289                .expect("client");
27290            let mut worker = Worker::new(client, "rust-workers")
27291                .worker_id("timeout-worker")
27292                .poll_timeout(Duration::from_millis(10));
27293            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
27294                Ok(json!({"late": "result"}))
27295            });
27296
27297            let error = worker
27298                .run_once()
27299                .await
27300                .expect_err(&format!("{name} must remain an error"));
27301            assert!(
27302                matches!(error, Error::Http { .. } | Error::Protocol(_)),
27303                "{name} returned an unexpected error variant: {error}"
27304            );
27305        }
27306    }
27307
27308    #[tokio::test]
27309    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
27310        let server = MockWorkerServer::start();
27311        let client = Client::builder(server.base_url())
27312            .worker_token(Some("worker-secret".to_string()))
27313            .namespace("orders")
27314            .timeout(Duration::from_secs(2))
27315            .build()
27316            .expect("client");
27317        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
27318
27319        let result = client
27320            .deregister_worker_registration("worker/α space")
27321            .await
27322            .expect("deregister worker registration");
27323
27324        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
27325        assert_eq!(
27326            server.worker_protocol_for(path).as_deref(),
27327            Some(WORKER_PROTOCOL_VERSION)
27328        );
27329        assert_eq!(server.control_protocol_for(path), None);
27330        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
27331        assert_eq!(
27332            server.authorization_for(path).as_deref(),
27333            Some("Bearer worker-secret")
27334        );
27335        assert_eq!(
27336            result,
27337            WorkerDeregistrationEnvelope {
27338                worker_id: "deregistered-worker".to_string(),
27339                outcome: "deregistered".to_string(),
27340                recovered_workflow_task_count: 2,
27341            }
27342        );
27343    }
27344
27345    #[tokio::test]
27346    async fn low_level_registration_rejects_update_validators_before_transport() {
27347        let server = MockWorkerServer::start();
27348        let client = Client::builder(server.base_url())
27349            .timeout(Duration::from_secs(2))
27350            .build()
27351            .expect("client");
27352
27353        for update_validators in [json!(["approve"]), json!("approve")] {
27354            let error = client
27355                .register_worker_with_command_contracts(
27356                    "validator-claiming-worker",
27357                    "rust-workers",
27358                    vec!["orders".to_string()],
27359                    vec![],
27360                    1,
27361                    1,
27362                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
27363                    json!({
27364                        "orders": {
27365                            "queries": ["current"],
27366                            "updates": ["approve"],
27367                            "update_validators": update_validators,
27368                        },
27369                    }),
27370                )
27371                .await
27372                .expect_err("unsupported validator claims must fail before registration");
27373
27374            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
27375                panic!("expected typed unsupported-validator failure");
27376            };
27377            assert_eq!(workflow_type, "orders");
27378        }
27379        assert_eq!(server.request_count("/api/worker/register"), 0);
27380    }
27381
27382    #[tokio::test]
27383    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
27384        let server = MockWorkerServer::start();
27385        let client = Client::builder(server.base_url())
27386            .timeout(Duration::from_secs(2))
27387            .build()
27388            .expect("client");
27389        let mut worker = Worker::new(client, "rust-workers");
27390        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
27391        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
27392        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
27393        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
27394        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
27395        worker
27396            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
27397            .expect("declare workflow signals");
27398
27399        worker.register().await.expect("register handler contracts");
27400
27401        let declaration =
27402            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
27403        let expected_contracts = json!([
27404            {
27405                "name": "a-avro",
27406                "parameters": [{
27407                    "name": "args", "position": 0, "required": false,
27408                    "variadic": true, "type": null, "allows_null": true,
27409                    "default_available": false, "default": null,
27410                }],
27411            },
27412            {
27413                "name": "z-json",
27414                "parameters": [{
27415                    "name": "args", "position": 0, "required": false,
27416                    "variadic": true, "type": null, "allows_null": true,
27417                    "default_available": false, "default": null,
27418                }],
27419            },
27420        ]);
27421        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
27422        assert_eq!(declaration["query_contracts"], expected_contracts);
27423        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
27424        assert_eq!(declaration["update_contracts"], expected_contracts);
27425        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
27426        assert_eq!(declaration["signal_contracts"], expected_contracts);
27427        assert_eq!(declaration["update_validators"], json!([]));
27428    }
27429
27430    #[tokio::test]
27431    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
27432        let server = MockWorkerServer::start();
27433        let client = Client::new(server.base_url()).expect("client");
27434        let mut worker = Worker::new(client, "rust-workers");
27435        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
27436        assert!(worker
27437            .declare_workflow_signals("missing", &["finish"])
27438            .is_err());
27439        worker
27440            .declare_workflow_signals("orders", &["finish"])
27441            .unwrap();
27442        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
27443            assert!(worker.declare_workflow_signals("orders", names).is_err());
27444        }
27445        worker.register().await.unwrap();
27446        assert_eq!(
27447            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
27448                ["signals"],
27449            json!(["finish"])
27450        );
27451        worker.declare_workflow_signals("orders", &[]).unwrap();
27452        worker.register().await.unwrap();
27453        let registrations = server.request_bodies("/api/worker/register");
27454        assert_eq!(
27455            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
27456            json!([])
27457        );
27458        assert_eq!(
27459            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
27460            json!([])
27461        );
27462    }
27463
27464    #[tokio::test]
27465    async fn low_level_registration_preserves_query_and_update_contracts() {
27466        let server = MockWorkerServer::start();
27467        let client = Client::builder(server.base_url())
27468            .timeout(Duration::from_secs(2))
27469            .build()
27470            .expect("client");
27471        let contracts = json!({
27472            "orders": {
27473                "queries": ["current"],
27474                "updates": ["approve"],
27475                "update_validators": [],
27476            },
27477            "payments": {
27478                "queries": ["status"],
27479                "updates": ["capture"],
27480            },
27481        });
27482
27483        client
27484            .register_worker_with_command_contracts(
27485                "command-worker",
27486                "rust-workers",
27487                vec!["orders".to_string(), "payments".to_string()],
27488                vec![],
27489                1,
27490                1,
27491                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
27492                contracts.clone(),
27493            )
27494            .await
27495            .expect("query and update contracts must remain supported");
27496
27497        assert_eq!(
27498            server.request_body("/api/worker/register")["workflow_command_contracts"],
27499            contracts
27500        );
27501        assert!(server
27502            .request_body("/api/worker/register")
27503            .get("workflow_definition_fingerprints")
27504            .is_none());
27505    }
27506
27507    #[tokio::test]
27508    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
27509        let server = MockWorkerServer::start();
27510        let client = Client::builder(server.base_url())
27511            .timeout(Duration::from_secs(2))
27512            .build()
27513            .expect("client");
27514        let mut worker = Worker::new(client.clone(), "rust-workers");
27515        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27516
27517        assert!(worker
27518            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
27519            .is_err());
27520        assert!(worker
27521            .set_workflow_definition_sources("orders", &[])
27522            .is_err());
27523        worker
27524            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
27525            .expect("embed workflow source");
27526        worker.register().await.expect("register worker");
27527        let first = server.request_bodies("/api/worker/register")[0]
27528            ["workflow_definition_fingerprints"]["orders"]
27529            .as_str()
27530            .expect("source-backed fingerprint")
27531            .to_string();
27532        assert!(first.starts_with("sha256:"));
27533
27534        worker
27535            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
27536            .expect("change embedded helper source");
27537        worker.register().await.expect("register changed source");
27538        let changed = server.request_bodies("/api/worker/register")[1]
27539            ["workflow_definition_fingerprints"]["orders"]
27540            .as_str()
27541            .expect("changed fingerprint")
27542            .to_string();
27543        assert_ne!(first, changed);
27544
27545        let mut replacement =
27546            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
27547        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27548        replacement
27549            .register()
27550            .await
27551            .expect("register replacement handler");
27552        assert_eq!(
27553            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
27554            json!({})
27555        );
27556    }
27557
27558    #[tokio::test]
27559    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
27560        let server = MockWorkerServer::start();
27561        let control_only = Client::builder(server.base_url())
27562            .control_token(Some("control-secret".to_string()))
27563            .build()
27564            .expect("control client");
27565
27566        let error = control_only
27567            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27568            .await
27569            .expect_err("control token must not authorize a worker request");
27570        assert!(matches!(
27571            error,
27572            Error::MissingRoleCredentials { role: "worker", .. }
27573        ));
27574        assert_eq!(server.request_count("/api/worker/register"), 0);
27575
27576        let worker_only = Client::builder(server.base_url())
27577            .worker_token(Some("worker-secret".to_string()))
27578            .build()
27579            .expect("worker client");
27580        let error = worker_only
27581            .health()
27582            .await
27583            .expect_err("worker token must not authorize a control request");
27584        assert!(matches!(
27585            error,
27586            Error::MissingRoleCredentials {
27587                role: "control",
27588                ..
27589            }
27590        ));
27591        assert_eq!(server.request_count("/api/health"), 0);
27592    }
27593
27594    #[tokio::test]
27595    async fn shared_token_supports_worker_and_control_planes() {
27596        let server = MockWorkerServer::start();
27597        let client = Client::builder(server.base_url())
27598            .token(Some("shared-secret".to_string()))
27599            .build()
27600            .expect("client");
27601
27602        client.health().await.expect("control request");
27603        client
27604            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27605            .await
27606            .expect("worker request");
27607
27608        assert_eq!(
27609            server.authorization_for("/api/health").as_deref(),
27610            Some("Bearer shared-secret")
27611        );
27612        assert_eq!(
27613            server.control_protocol_for("/api/health").as_deref(),
27614            Some(CONTROL_PLANE_VERSION)
27615        );
27616        assert_eq!(
27617            server.authorization_for("/api/worker/register").as_deref(),
27618            Some("Bearer shared-secret")
27619        );
27620        assert_eq!(
27621            server
27622                .worker_protocol_for("/api/worker/register")
27623                .as_deref(),
27624            Some(WORKER_PROTOCOL_VERSION)
27625        );
27626    }
27627
27628    #[tokio::test]
27629    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
27630        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
27631        let server = MockWorkerServer::start();
27632        let client = Client::builder(server.base_url())
27633            .timeout(Duration::from_secs(2))
27634            .build()
27635            .expect("client");
27636
27637        client
27638            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
27639            .await
27640            .expect("register");
27641        client
27642            .heartbeat_worker("capture-worker", 1, 1)
27643            .await
27644            .expect("heartbeat");
27645        client
27646            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27647            .await
27648            .expect("workflow poll");
27649        client
27650            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27651            .await
27652            .expect("activity poll");
27653
27654        for path in [
27655            "/api/worker/register",
27656            "/api/worker/heartbeat",
27657            "/api/worker/workflow-tasks/poll",
27658            "/api/worker/activity-tasks/poll",
27659        ] {
27660            assert_eq!(
27661                server.worker_protocol_for(path).as_deref(),
27662                Some(WORKER_PROTOCOL_VERSION),
27663                "unexpected protocol for {path}"
27664            );
27665        }
27666
27667        assert_eq!(
27668            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
27669            1
27670        );
27671        assert_eq!(
27672            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
27673            500
27674        );
27675        assert_eq!(
27676            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
27677            1
27678        );
27679        assert!(
27680            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
27681                .as_str()
27682                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
27683        );
27684        assert!(
27685            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
27686                .as_str()
27687                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
27688        );
27689        let registration = server.request_body("/api/worker/register");
27690        for optional in [
27691            "cooperative_cancellation",
27692            "local_activities",
27693            "worker_sessions",
27694            "sticky_execution",
27695        ] {
27696            assert!(!registration["capabilities"]
27697                .as_array()
27698                .is_some_and(|capabilities| capabilities
27699                    .iter()
27700                    .any(|capability| capability.as_str() == Some(optional))));
27701        }
27702    }
27703
27704    #[tokio::test]
27705    async fn explicit_previous_worker_protocol_preserves_headers() {
27706        let server = MockWorkerServer::start();
27707        let client = Client::builder(server.base_url())
27708            .worker_protocol_version(WorkerProtocolVersion::V119)
27709            .timeout(Duration::from_secs(2))
27710            .build()
27711            .expect("client");
27712        client
27713            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
27714            .await
27715            .expect("register");
27716        client
27717            .heartbeat_worker("legacy-worker", 1, 1)
27718            .await
27719            .expect("heartbeat");
27720        client
27721            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
27722            .await
27723            .expect("workflow poll");
27724        client
27725            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
27726            .await
27727            .expect("activity poll");
27728        client
27729            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
27730            .await
27731            .expect("query poll");
27732        client
27733            .deregister_worker_registration("legacy-worker")
27734            .await
27735            .expect("deregister");
27736        for path in [
27737            "/api/worker/register",
27738            "/api/worker/heartbeat",
27739            "/api/worker/workflow-tasks/poll",
27740            "/api/worker/activity-tasks/poll",
27741            "/api/worker/query-tasks/poll",
27742            "/api/worker/registrations/legacy-worker",
27743        ] {
27744            assert_eq!(
27745                server.worker_protocol_for(path).as_deref(),
27746                Some("1.19"),
27747                "{path}"
27748            );
27749            assert_eq!(server.control_protocol_for(path), None, "{path}");
27750        }
27751    }
27752
27753    #[tokio::test]
27754    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
27755        let server = MockWorkerServer::start();
27756        let client = Client::builder(server.base_url())
27757            .worker_protocol_version(WorkerProtocolVersion::V119)
27758            .timeout(Duration::from_secs(2))
27759            .build()
27760            .expect("client");
27761        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
27762        let error = worker
27763            .register()
27764            .await
27765            .expect_err("legacy cooperation must be refused");
27766        assert!(matches!(
27767            error,
27768            Error::CooperativeCancellationUnavailable(_)
27769        ));
27770        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
27771    }
27772
27773    #[tokio::test]
27774    async fn query_task_endpoints_send_the_selected_worker_protocol() {
27775        let server = MockWorkerServer::start();
27776        let client = Client::builder(server.base_url())
27777            .timeout(Duration::from_secs(2))
27778            .build()
27779            .expect("client");
27780
27781        client
27782            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27783            .await
27784            .expect("query poll");
27785        client
27786            .complete_query_task(
27787                "query-capture",
27788                "capture-worker",
27789                1,
27790                json!(8),
27791                DEFAULT_CODEC,
27792            )
27793            .await
27794            .expect("query complete");
27795        client
27796            .fail_query_task(
27797                "query-capture",
27798                "capture-worker",
27799                1,
27800                "failed",
27801                "query_rejected",
27802                "QueryFailed",
27803            )
27804            .await
27805            .expect("query fail");
27806
27807        for path in [
27808            "/api/worker/query-tasks/poll",
27809            "/api/worker/query-tasks/query-capture/complete",
27810            "/api/worker/query-tasks/query-capture/fail",
27811        ] {
27812            assert_eq!(
27813                server.worker_protocol_for(path).as_deref(),
27814                Some(WORKER_PROTOCOL_VERSION),
27815                "unexpected protocol for {path}"
27816            );
27817        }
27818
27819        assert_eq!(
27820            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
27821            1
27822        );
27823        assert!(
27824            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
27825                .as_str()
27826                .is_some_and(|id| id.starts_with("rust-query-poll-"))
27827        );
27828    }
27829
27830    #[tokio::test]
27831    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
27832        let server = MockWorkerServer::transient_worker_failures();
27833        let client = Client::builder(server.base_url())
27834            .timeout(Duration::from_secs(2))
27835            .build()
27836            .expect("client");
27837
27838        client
27839            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27840            .await
27841            .expect("workflow poll retry");
27842        client
27843            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27844            .await
27845            .expect("activity poll retry");
27846        client
27847            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27848            .await
27849            .expect("query poll retry");
27850
27851        for path in [
27852            "/api/worker/workflow-tasks/poll",
27853            "/api/worker/activity-tasks/poll",
27854            "/api/worker/query-tasks/poll",
27855        ] {
27856            let bodies = server.request_bodies(path);
27857            assert_eq!(bodies.len(), 2, "{path} must be retried once");
27858            assert_eq!(
27859                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
27860                "{path} must preserve the request binding across retry"
27861            );
27862        }
27863    }
27864
27865    #[tokio::test]
27866    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
27867        let server = MockWorkerServer::consecutive_poll_failures(2);
27868        let client = Client::builder(server.base_url())
27869            .timeout(Duration::from_secs(2))
27870            .build()
27871            .expect("client");
27872        let mut worker = Worker::new(client, "capture")
27873            .worker_id("capture-worker")
27874            .poll_timeout(Duration::from_millis(10))
27875            .retry_policy(WorkerRetryPolicy {
27876                max_retries: 2,
27877                initial_backoff: Duration::from_millis(1),
27878                max_backoff: Duration::from_millis(1),
27879            });
27880        worker.register_workflow(
27881            "capture.workflow",
27882            |_ctx, _input| async move { Ok(Value::Null) },
27883        );
27884        worker.register_activity(
27885            "capture.activity",
27886            |_ctx, _input| async move { Ok(Value::Null) },
27887        );
27888        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
27889            Ok(Value::Null)
27890        });
27891
27892        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
27893
27894        for path in [
27895            "/api/worker/workflow-tasks/poll",
27896            "/api/worker/activity-tasks/poll",
27897            "/api/worker/query-tasks/poll",
27898        ] {
27899            let bodies = server.request_bodies(path);
27900            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
27901            assert!(
27902                bodies
27903                    .iter()
27904                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
27905                "{path} must preserve one request binding across every retry"
27906            );
27907        }
27908    }
27909
27910    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
27911        let reason = if unavailable {
27912            "storage_admission_unavailable"
27913        } else {
27914            "storage_pressure"
27915        };
27916        let mut body = json!({
27917            "reason": reason,
27918            "storage_state": if unavailable { "fenced" } else { "draining" },
27919            "retryable": true,
27920            "retry_after_seconds": 1,
27921        });
27922        if !mid_poll {
27923            body["request_admitted"] = json!(false);
27924        }
27925        if let Some(id) = poll_id {
27926            body["task"] = Value::Null;
27927            body["poll_status"] = json!(reason);
27928            body["poll_request_id"] = json!(id);
27929            body["retry_same_poll_request_id"] = json!(true);
27930            body["claim_admitted"] = json!(false);
27931        }
27932        body
27933    }
27934
27935    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
27936        let operation = match path {
27937            "/api/worker/register" => "register_worker",
27938            "/api/worker/heartbeat" => "heartbeat_worker",
27939            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
27940            "/api/worker/activity-tasks/poll" => "poll_activity_task",
27941            "/api/worker/query-tasks/poll" => "poll_query_task",
27942            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
27943            _ => return None,
27944        };
27945        let request: Value = serde_json::from_str(request).ok()?;
27946        let mut response = json!({
27947            "reason": "backend_unavailable",
27948            "operation": operation,
27949            "outcome": "unknown",
27950            "retryable": true,
27951            "retry_after_seconds": 1,
27952            "worker_id": request["worker_id"],
27953            "task_queue": request.get("task_queue"),
27954        });
27955        if path.ends_with("/poll") {
27956            response["task"] = Value::Null;
27957            response["poll_status"] = json!("backend_unavailable");
27958            response["poll_request_id"] = request["poll_request_id"].clone();
27959            response["retry_same_poll_request_id"] = json!(true);
27960        }
27961        Some(response)
27962    }
27963
27964    fn backend_retry_override(
27965        path: &str,
27966        request: &str,
27967        number: usize,
27968    ) -> Option<(&'static str, String)> {
27969        if number > 8 {
27970            return None;
27971        }
27972        Some((
27973            "503 Service Unavailable",
27974            backend_refusal(path, request)?.to_string(),
27975        ))
27976    }
27977
27978    fn backend_unavailable_override(
27979        path: &str,
27980        request: &str,
27981        _number: usize,
27982    ) -> Option<(&'static str, String)> {
27983        Some((
27984            "503 Service Unavailable",
27985            backend_refusal(path, request)?.to_string(),
27986        ))
27987    }
27988
27989    fn storage_worker(server: &MockWorkerServer) -> Worker {
27990        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
27991            .worker_id("storage-worker")
27992            .retry_policy(WorkerRetryPolicy {
27993                max_retries: 1,
27994                initial_backoff: Duration::from_millis(1),
27995                max_backoff: Duration::from_millis(1),
27996            })
27997    }
27998
27999    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
28000        let requests = server.requests.lock().expect("requests");
28001        let bodies: Vec<_> = requests
28002            .iter()
28003            .filter(|request| request.path == path)
28004            .map(|request| &request.body)
28005            .collect();
28006        assert_eq!(bodies.len(), count, "{path}");
28007        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
28008    }
28009
28010    #[test]
28011    fn backend_recovery_requires_the_explicit_worker_contract() {
28012        for (path, operation) in [
28013            ("/worker/register", "register_worker"),
28014            ("/worker/heartbeat", "heartbeat_worker"),
28015            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
28016            ("/worker/activity-tasks/poll", "poll_activity_task"),
28017            ("/worker/query-tasks/poll", "poll_query_task"),
28018            (
28019                "/worker/update-validation-tasks/poll",
28020                "poll_update_validation_task",
28021            ),
28022        ] {
28023            let poll_id = path.ends_with("/poll").then_some("same-poll");
28024            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
28025            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
28026                .expect("worker operation");
28027            assert_eq!(body["operation"], operation);
28028            let error = Error::Http {
28029                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28030                body: body.to_string(),
28031            };
28032            assert_eq!(
28033                worker_backend_unavailable_retry_after(&error, path, poll_id),
28034                Some(Duration::from_secs(1))
28035            );
28036            assert!(!worker_operation_is_retryable(&error));
28037            for (field, value) in [
28038                ("operation", json!("wrong_operation")),
28039                ("outcome", json!("completed")),
28040                ("retryable", json!(false)),
28041                ("retry_after_seconds", json!(0)),
28042                ("worker_id", json!("")),
28043            ] {
28044                let mut invalid = body.clone();
28045                invalid[field] = value;
28046                let error = Error::Http {
28047                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28048                    body: invalid.to_string(),
28049                };
28050                assert!(
28051                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
28052                    "{path}: {field}"
28053                );
28054                assert!(!worker_operation_is_retryable(&error));
28055            }
28056            if let Some(poll_id) = poll_id {
28057                for (field, value) in [
28058                    ("poll_request_id", json!("wrong-poll")),
28059                    ("poll_status", json!("empty")),
28060                    ("task", json!({"task_id":"claimed"})),
28061                    ("retry_same_poll_request_id", json!(false)),
28062                ] {
28063                    let mut invalid = body.clone();
28064                    invalid[field] = value;
28065                    let error = Error::Http {
28066                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28067                        body: invalid.to_string(),
28068                    };
28069                    assert!(
28070                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
28071                            .is_none(),
28072                        "{path}: {field}"
28073                    );
28074                }
28075            }
28076            let error = Error::Http {
28077                status: reqwest::StatusCode::UNAUTHORIZED,
28078                body: body.to_string(),
28079            };
28080            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
28081            assert!(!worker_operation_is_retryable(&error));
28082        }
28083    }
28084
28085    #[tokio::test]
28086    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
28087        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28088            request_override: Some(backend_retry_override),
28089            ..MockWorkerBehavior::default()
28090        });
28091        let mut worker =
28092            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28093        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
28094        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
28095        worker.register_query("backend.workflow", "state", |_, _| async {
28096            Ok(Value::Null)
28097        });
28098        worker.register().await.expect("registration recovery");
28099        worker
28100            .client
28101            .heartbeat_worker("storage-worker", 1, 1)
28102            .await
28103            .expect("heartbeat recovery");
28104        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
28105        for path in [
28106            "/api/worker/register",
28107            "/api/worker/heartbeat",
28108            "/api/worker/workflow-tasks/poll",
28109            "/api/worker/activity-tasks/poll",
28110            "/api/worker/query-tasks/poll",
28111        ] {
28112            assert_identical_requests(&server, path, 9);
28113        }
28114    }
28115
28116    #[tokio::test]
28117    async fn backend_recovery_wait_stops_with_worker() {
28118        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28119            request_override: Some(backend_unavailable_override),
28120            ..MockWorkerBehavior::default()
28121        });
28122        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
28123            max_retries: 1,
28124            initial_backoff: Duration::from_secs(2),
28125            max_backoff: Duration::from_secs(2),
28126        });
28127        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
28128        let started = tokio::time::Instant::now();
28129        let _ = tokio::time::timeout(
28130            Duration::from_secs(1),
28131            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
28132        )
28133        .await
28134        .expect("shutdown interrupts backend wait");
28135        assert!(started.elapsed() < Duration::from_secs(1));
28136        assert!(server.request_count("/api/worker/register") >= 1);
28137    }
28138
28139    #[test]
28140    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
28141        for unavailable in [false, true] {
28142            for mid_poll in [false, true] {
28143                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
28144                let error = Error::Http {
28145                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28146                    body: body.to_string(),
28147                };
28148                assert_eq!(
28149                    worker_storage_admission_retry_after(&error, Some("same-poll")),
28150                    Some(Duration::from_secs(1))
28151                );
28152                assert!(
28153                    !worker_operation_is_retryable(&error),
28154                    "storage is not a bounded generic retry"
28155                );
28156                for (field, value) in [
28157                    ("poll_request_id", json!("wrong-poll")),
28158                    ("task", json!({"task_id":"claimed"})),
28159                    ("retryable", json!(false)),
28160                    ("retry_after_seconds", json!(0)),
28161                    ("retry_after_seconds", json!(true)),
28162                    ("retry_after_seconds", json!(1.0)),
28163                    ("storage_state", json!("normal")),
28164                    ("poll_status", json!("empty")),
28165                    ("claim_admitted", json!(true)),
28166                    ("retry_same_poll_request_id", json!(false)),
28167                    ("request_admitted", json!(true)),
28168                ] {
28169                    let mut invalid = body.clone();
28170                    invalid[field] = value;
28171                    let error = Error::Http {
28172                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28173                        body: invalid.to_string(),
28174                    };
28175                    assert!(
28176                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
28177                        "{field}"
28178                    );
28179                }
28180            }
28181        }
28182        let body = storage_refusal(None, false, false);
28183        let error = Error::Http {
28184            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28185            body: body.to_string(),
28186        };
28187        assert!(worker_storage_admission_retry_after(&error, None).is_some());
28188        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
28189        let error = Error::Http {
28190            status: reqwest::StatusCode::FORBIDDEN,
28191            body: body.to_string(),
28192        };
28193        assert!(worker_storage_admission_retry_after(&error, None).is_none());
28194        let body = storage_refusal(None, false, true);
28195        let error = Error::Http {
28196            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28197            body: body.to_string(),
28198        };
28199        assert!(worker_storage_admission_retry_after(&error, None).is_none());
28200    }
28201
28202    #[tokio::test]
28203    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
28204        for unavailable in [false, true] {
28205            for mid_poll in [false, true] {
28206                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28207                    poll_failures_per_path: 1,
28208                    storage_refusals: 7,
28209                    storage_path: Some("/poll"),
28210                    storage_unavailable: unavailable,
28211                    storage_mid_poll: mid_poll,
28212                    ..MockWorkerBehavior::default()
28213                });
28214                let mut worker = storage_worker(&server);
28215                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
28216                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
28217                for path in [
28218                    "/api/worker/workflow-tasks/poll",
28219                    "/api/worker/activity-tasks/poll",
28220                    "/api/worker/query-tasks/poll",
28221                ] {
28222                    assert_identical_requests(&server, path, 9);
28223                }
28224            }
28225        }
28226    }
28227
28228    #[tokio::test]
28229    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
28230        struct CountedBody(Arc<AtomicUsize>);
28231        impl Serialize for CountedBody {
28232            fn serialize<S: Serializer>(
28233                &self,
28234                serializer: S,
28235            ) -> std::result::Result<S::Ok, S::Error> {
28236                let count = self.0.fetch_add(1, Ordering::SeqCst);
28237                json!({"serialization":count,"lease_owner":"worker","attempt":7})
28238                    .serialize(serializer)
28239            }
28240        }
28241        for path in [
28242            "/api/worker/register",
28243            "/api/worker/heartbeat",
28244            "/api/worker/workflow-tasks/storage-task/complete",
28245            "/api/worker/workflow-tasks/storage-task/fail",
28246            "/api/worker/activity-tasks/storage-task/complete",
28247            "/api/worker/activity-tasks/storage-task/fail",
28248            "/api/worker/activity-tasks/storage-task/heartbeat",
28249            "/api/worker/query-tasks/storage-task/complete",
28250            "/api/worker/query-tasks/storage-task/fail",
28251        ] {
28252            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28253                storage_refusals: 7,
28254                storage_path: Some(path),
28255                ..MockWorkerBehavior::default()
28256            });
28257            let worker =
28258                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28259            let calls = Arc::new(AtomicUsize::new(0));
28260            let _: Value = worker
28261                .client
28262                .request_json(
28263                    reqwest::Method::POST,
28264                    &path[4..],
28265                    RequestProtocol::DefaultWorker,
28266                    Some(&CountedBody(Arc::clone(&calls))),
28267                )
28268                .await
28269                .expect("prepared request recovery");
28270            assert_eq!(calls.load(Ordering::SeqCst), 1);
28271            assert_identical_requests(&server, path, 8);
28272        }
28273        for worker_scope in [false, true] {
28274            let path = if worker_scope {
28275                "/api/health"
28276            } else {
28277                "/api/worker/register"
28278            };
28279            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28280                storage_refusals: usize::MAX,
28281                storage_path: Some(path),
28282                ..MockWorkerBehavior::default()
28283            });
28284            let worker = storage_worker(&server);
28285            let client = worker.client.clone();
28286            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
28287            let error = if worker_scope {
28288                worker
28289                    .client
28290                    .health()
28291                    .await
28292                    .expect_err("control plane is not retried")
28293            } else {
28294                client
28295                    .request_json::<Value, Value>(
28296                        reqwest::Method::POST,
28297                        "/worker/register",
28298                        RequestProtocol::DefaultWorker,
28299                        Some(&json!({})),
28300                    )
28301                    .await
28302                    .expect_err("direct client is not retried")
28303            };
28304            assert!(worker_storage_admission_body(&error).is_some());
28305            assert_eq!(server.request_count(path), 1);
28306        }
28307    }
28308
28309    #[tokio::test]
28310    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
28311        for fail in [false, true] {
28312            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28313                storage_activity: true,
28314                storage_refusals: 7,
28315                storage_path: Some("/storage-activity/"),
28316                ..MockWorkerBehavior::default()
28317            });
28318            let mut worker = storage_worker(&server);
28319            let calls = Arc::new(AtomicUsize::new(0));
28320            let observed = Arc::clone(&calls);
28321            worker.register_activity("storage.activity", move |ctx, _| {
28322                let calls = Arc::clone(&observed);
28323                async move {
28324                    calls.fetch_add(1, Ordering::SeqCst);
28325                    ctx.heartbeat(json!({"step":2})).await?;
28326                    if fail {
28327                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
28328                    } else {
28329                        Ok(json!({"receipt":true}))
28330                    }
28331                }
28332            });
28333            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
28334            assert_eq!(calls.load(Ordering::SeqCst), 1);
28335            assert_identical_requests(
28336                &server,
28337                "/api/worker/activity-tasks/storage-activity/heartbeat",
28338                8,
28339            );
28340            let suffix = if fail { "fail" } else { "complete" };
28341            assert_identical_requests(
28342                &server,
28343                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
28344                8,
28345            );
28346            let other = if fail { "complete" } else { "fail" };
28347            assert_eq!(
28348                server.request_count(&format!(
28349                    "/api/worker/activity-tasks/storage-activity/{other}"
28350                )),
28351                0
28352            );
28353        }
28354    }
28355
28356    #[tokio::test]
28357    async fn storage_waits_are_interruptible_without_false_activity_failure() {
28358        for path in [
28359            "/api/worker/register",
28360            "/api/worker/heartbeat",
28361            "/api/worker/activity-tasks/poll",
28362            "/api/worker/activity-tasks/storage-activity/heartbeat",
28363            "/api/worker/activity-tasks/storage-activity/complete",
28364        ] {
28365            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28366                storage_activity: true,
28367                storage_refusals: usize::MAX,
28368                storage_path: Some(path),
28369                ..MockWorkerBehavior::default()
28370            });
28371            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
28372            worker.register_activity("storage.activity", |ctx, _| async move {
28373                ctx.heartbeat(json!({"step":2})).await?;
28374                Ok(json!({"receipt":true}))
28375            });
28376            let shutdown = async {
28377                while server.request_count(path) == 0 {
28378                    tokio::time::sleep(Duration::from_millis(1)).await;
28379                }
28380            };
28381            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
28382                .await
28383                .expect("shutdown interrupts admission");
28384            assert!(
28385                result.is_err(),
28386                "a refused operation must not appear acknowledged: {path}, {result:?}"
28387            );
28388            assert_eq!(server.request_count(path), 1);
28389            assert_eq!(
28390                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
28391                0
28392            );
28393            assert_eq!(
28394                server.request_count("/api/worker/registrations/mock-worker"),
28395                usize::from(!path.ends_with("/register"))
28396            );
28397        }
28398    }
28399
28400    #[tokio::test]
28401    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
28402        for fail in [false, true] {
28403            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28404                storage_query: true,
28405                storage_refusals: 7,
28406                storage_path: Some("/storage-query/"),
28407                ..MockWorkerBehavior::default()
28408            });
28409            let mut worker = storage_worker(&server);
28410            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
28411            let calls = Arc::new(AtomicUsize::new(0));
28412            let observed = Arc::clone(&calls);
28413            worker.register_query("storage.workflow", "state", move |_, _| {
28414                let calls = Arc::clone(&observed);
28415                async move {
28416                    calls.fetch_add(1, Ordering::SeqCst);
28417                    if fail {
28418                        Err(Error::WorkerLoop("intentional query failure".to_string()))
28419                    } else {
28420                        Ok(json!({"state":"waiting"}))
28421                    }
28422                }
28423            });
28424            assert_eq!(worker.run_once().await.expect("query settled"), 1);
28425            assert_eq!(calls.load(Ordering::SeqCst), 1);
28426            let suffix = if fail { "fail" } else { "complete" };
28427            assert_identical_requests(
28428                &server,
28429                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
28430                8,
28431            );
28432            let other = if fail { "complete" } else { "fail" };
28433            assert_eq!(
28434                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
28435                0
28436            );
28437        }
28438    }
28439
28440    #[tokio::test]
28441    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
28442        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28443            storage_refusals: 7,
28444            storage_path: Some("/poll"),
28445            unauthorized_polls: true,
28446            ..MockWorkerBehavior::default()
28447        });
28448        let error = storage_worker(&server)
28449            .run_once()
28450            .await
28451            .expect_err("auth remains terminal");
28452        assert!(matches!(
28453            error,
28454            Error::Http {
28455                status: reqwest::StatusCode::UNAUTHORIZED,
28456                ..
28457            }
28458        ));
28459        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
28460
28461        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28462            storage_refusals: 7,
28463            storage_path: Some("/activity-cancel/complete"),
28464            ..MockWorkerBehavior::default()
28465        });
28466        let worker =
28467            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28468        let error = worker
28469            .client
28470            .complete_activity_task(
28471                "activity-cancel",
28472                "attempt-cancel",
28473                "worker",
28474                json!({}),
28475                DEFAULT_CODEC,
28476            )
28477            .await
28478            .expect_err("cancellation remains terminal");
28479        assert!(activity_task_rejection_is_final(&error));
28480        assert_identical_requests(
28481            &server,
28482            "/api/worker/activity-tasks/activity-cancel/complete",
28483            8,
28484        );
28485
28486        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28487            storage_refusals: usize::MAX,
28488            storage_path: Some("/poll"),
28489            storage_wrong_poll_id: true,
28490            ..MockWorkerBehavior::default()
28491        });
28492        assert!(storage_worker(&server).run_once().await.is_err());
28493        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28494    }
28495
28496    #[tokio::test]
28497    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
28498        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28499            storage_refusals: usize::MAX,
28500            storage_path: Some("/poll"),
28501            ..MockWorkerBehavior::default()
28502        });
28503        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
28504        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
28505        let run = tokio::spawn(async move { worker.run().await });
28506        tokio::time::timeout(Duration::from_secs(2), async {
28507            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
28508                tokio::time::sleep(Duration::from_millis(1)).await;
28509            }
28510        })
28511        .await
28512        .expect("poll started");
28513        run.abort();
28514        assert!(run.await.expect_err("cancelled run").is_cancelled());
28515        tokio::time::sleep(Duration::from_millis(250)).await;
28516        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
28517    }
28518
28519    #[tokio::test]
28520    async fn query_protocol_rejection_from_older_server_is_typed() {
28521        let server = MockWorkerServer::reject_query_protocol();
28522        let client = Client::builder(server.base_url())
28523            .timeout(Duration::from_secs(2))
28524            .build()
28525            .expect("client");
28526
28527        let error = client
28528            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
28529            .await
28530            .expect_err("server below query protocol floor must reject");
28531        let Error::Protocol(failure) = error else {
28532            panic!("expected typed protocol failure");
28533        };
28534
28535        assert_eq!(failure.status, 400);
28536        assert_eq!(failure.reason, "unsupported_protocol_version");
28537        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
28538        assert_eq!(
28539            failure.requested_version.as_deref(),
28540            Some(WORKER_PROTOCOL_VERSION)
28541        );
28542        assert_eq!(
28543            server
28544                .worker_protocol_for("/api/worker/query-tasks/poll")
28545                .as_deref(),
28546            Some(WORKER_PROTOCOL_VERSION)
28547        );
28548    }
28549
28550    #[tokio::test]
28551    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
28552        let server = MockWorkerServer::reject_query_protocol();
28553        let client = Client::builder(server.base_url())
28554            .timeout(Duration::from_secs(2))
28555            .build()
28556            .expect("client");
28557        let mut worker = Worker::new(client, "rust-workers")
28558            .worker_id("baseline-worker")
28559            .poll_timeout(Duration::from_millis(10));
28560
28561        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
28562            Ok(Value::Null)
28563        });
28564
28565        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
28566        assert_eq!(
28567            server
28568                .worker_protocol_for("/api/worker/workflow-tasks/poll")
28569                .as_deref(),
28570            Some(WORKER_PROTOCOL_VERSION)
28571        );
28572        assert_eq!(
28573            server.worker_protocol_for("/api/worker/query-tasks/poll"),
28574            None,
28575            "a worker without query handlers must not use the query-task endpoint"
28576        );
28577    }
28578
28579    #[tokio::test]
28580    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
28581        let server = MockWorkerServer::reject_query_completion();
28582        let client = Client::builder(server.base_url())
28583            .timeout(Duration::from_secs(2))
28584            .build()
28585            .expect("client");
28586
28587        let error = client
28588            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
28589            .await
28590            .expect_err("expired completion must be rejected");
28591        let Error::QueryFailed(failure) = error else {
28592            panic!("expected typed query failure");
28593        };
28594        assert_eq!(failure.status, 409);
28595        assert_eq!(failure.reason, "query_task_timed_out");
28596
28597        let mut worker = Worker::new(client, "rust-workers")
28598            .worker_id("late-worker")
28599            .poll_timeout(Duration::from_millis(10));
28600        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28601        worker.register_query(
28602            "counter",
28603            "current",
28604            |_ctx, _args| async move { Ok(json!(8)) },
28605        );
28606
28607        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
28608        assert_eq!(
28609            worker
28610                .run_once()
28611                .await
28612                .expect("worker continues after late completion"),
28613            0
28614        );
28615        assert_eq!(
28616            server.request_count("/api/worker/query-tasks/query-late/complete"),
28617            2
28618        );
28619        assert_eq!(
28620            server.request_count("/api/worker/query-tasks/query-late/fail"),
28621            0,
28622            "a server completion rejection must not be reported as an encoding failure"
28623        );
28624    }
28625
28626    #[tokio::test]
28627    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
28628        let server = MockWorkerServer::start();
28629        let client = Client::builder(server.base_url())
28630            .timeout(Duration::from_secs(2))
28631            .build()
28632            .expect("client");
28633        let mut worker = Worker::new(client, "rust-workers")
28634            .worker_id("joined-worker")
28635            .poll_timeout(Duration::from_millis(10));
28636        worker.register_workflow(
28637            "joined.workflow",
28638            |_ctx, _input| async move { Ok(Value::Null) },
28639        );
28640        worker.register_activity(
28641            "joined.activity",
28642            |_ctx, _input| async move { Ok(Value::Null) },
28643        );
28644        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
28645            Ok(Value::Null)
28646        });
28647
28648        worker
28649            .run_until(tokio::time::sleep(Duration::from_millis(20)))
28650            .await
28651            .expect("normal shutdown");
28652
28653        let deregistration_path = "/api/worker/registrations/mock-worker";
28654        assert_eq!(server.request_count(deregistration_path), 1);
28655        for poll_path in [
28656            "/api/worker/workflow-tasks/poll",
28657            "/api/worker/activity-tasks/poll",
28658            "/api/worker/query-tasks/poll",
28659        ] {
28660            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
28661        }
28662        assert_eq!(
28663            server.captured_paths().last().map(String::as_str),
28664            Some(deregistration_path),
28665            "deregistration must start only after every poller has joined"
28666        );
28667    }
28668
28669    #[tokio::test]
28670    async fn registration_failure_does_not_deregister() {
28671        let server = MockWorkerServer::rejected_registration();
28672        let client = Client::builder(server.base_url())
28673            .timeout(Duration::from_secs(2))
28674            .build()
28675            .expect("client");
28676        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
28677
28678        let error = worker
28679            .run_until(async {})
28680            .await
28681            .expect_err("registration must fail");
28682        assert!(matches!(
28683            error,
28684            Error::Http {
28685                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28686                ..
28687            }
28688        ));
28689        assert!(server
28690            .captured_paths()
28691            .iter()
28692            .all(|path| !path.starts_with("/api/worker/registrations/")));
28693    }
28694
28695    #[tokio::test]
28696    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
28697        let server = MockWorkerServer::rejected_registration_protocol();
28698        let client = Client::builder(server.base_url())
28699            .timeout(Duration::from_secs(2))
28700            .build()
28701            .expect("client");
28702        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
28703
28704        let error = worker
28705            .run_until(async {})
28706            .await
28707            .expect_err("a protocol 1.16 server must reject this worker");
28708        let Error::Protocol(failure) = error else {
28709            panic!("expected typed protocol rejection");
28710        };
28711        assert_eq!(failure.reason, "unsupported_protocol_version");
28712        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
28713        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
28714        assert_eq!(
28715            server
28716                .worker_protocol_for("/api/worker/register")
28717                .as_deref(),
28718            Some(WORKER_PROTOCOL_VERSION)
28719        );
28720    }
28721
28722    #[tokio::test]
28723    async fn declined_registration_does_not_deregister() {
28724        let server = MockWorkerServer::declined_registration();
28725        let client = Client::builder(server.base_url())
28726            .timeout(Duration::from_secs(2))
28727            .build()
28728            .expect("client");
28729        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
28730
28731        let error = worker
28732            .run_until(async {})
28733            .await
28734            .expect_err("declined registration must fail");
28735        assert!(matches!(error, Error::WorkerLoop(_)));
28736        assert!(error.to_string().contains("was not accepted"));
28737        assert!(server
28738            .captured_paths()
28739            .iter()
28740            .all(|path| !path.starts_with("/api/worker/registrations/")));
28741    }
28742
28743    #[tokio::test]
28744    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
28745        let server = MockWorkerServer::rejected_deregistration();
28746        let client = Client::builder(server.base_url())
28747            .timeout(Duration::from_secs(2))
28748            .build()
28749            .expect("client");
28750        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
28751
28752        let error = worker
28753            .run_until(async {})
28754            .await
28755            .expect_err("deregistration must fail");
28756        assert!(matches!(
28757            error,
28758            Error::Http {
28759                status: reqwest::StatusCode::FORBIDDEN,
28760                ..
28761            }
28762        ));
28763        assert_eq!(
28764            server.request_count("/api/worker/registrations/mock-worker"),
28765            1
28766        );
28767    }
28768
28769    #[tokio::test]
28770    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
28771        let server = MockWorkerServer::rejected_deregistration_protocol();
28772        let client = Client::builder(server.base_url())
28773            .timeout(Duration::from_secs(2))
28774            .build()
28775            .expect("client");
28776        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
28777
28778        let error = worker
28779            .run_until(async {})
28780            .await
28781            .expect_err("protocol rejection must fail shutdown");
28782        let Error::Protocol(failure) = error else {
28783            panic!("expected typed protocol failure");
28784        };
28785        assert_eq!(failure.reason, "unsupported_protocol_version");
28786        assert_eq!(
28787            failure.requested_version.as_deref(),
28788            Some(WORKER_PROTOCOL_VERSION)
28789        );
28790        assert_eq!(
28791            server.request_count("/api/worker/registrations/mock-worker"),
28792            1
28793        );
28794    }
28795
28796    #[tokio::test]
28797    async fn primary_poller_error_retains_deregistration_failure_context() {
28798        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
28799        let client = Client::builder(server.base_url())
28800            .timeout(Duration::from_secs(2))
28801            .build()
28802            .expect("client");
28803        let mut worker = Worker::new(client, "rust-workers")
28804            .worker_id("combined-failure")
28805            .poll_timeout(Duration::from_millis(10));
28806        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
28807            Ok(Value::Null)
28808        });
28809
28810        let error = worker
28811            .run()
28812            .await
28813            .expect_err("worker and cleanup must fail");
28814        let summary = error.to_string();
28815        assert!(summary.contains("authentication_failed"));
28816        assert!(summary.contains("worker cannot deregister"));
28817        let Error::WorkerShutdown {
28818            primary,
28819            deregistration,
28820        } = error
28821        else {
28822            panic!("expected combined worker shutdown error");
28823        };
28824        assert!(matches!(
28825            *primary,
28826            Error::Http {
28827                status: reqwest::StatusCode::UNAUTHORIZED,
28828                ..
28829            }
28830        ));
28831        assert!(matches!(
28832            *deregistration,
28833            Error::Http {
28834                status: reqwest::StatusCode::FORBIDDEN,
28835                ..
28836            }
28837        ));
28838        assert_eq!(
28839            server.request_count("/api/worker/registrations/mock-worker"),
28840            1
28841        );
28842    }
28843
28844    #[tokio::test]
28845    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
28846        let server = MockWorkerServer::start();
28847        let client = Client::builder(server.base_url())
28848            .timeout(Duration::from_secs(2))
28849            .build()
28850            .expect("client");
28851        let mut worker = Worker::new(client, "rust-workers")
28852            .worker_id("activity-only-worker")
28853            .poll_timeout(Duration::from_millis(10));
28854
28855        worker.register_activity(
28856            "activity.only",
28857            |_ctx, _args| async move { Ok(Value::Null) },
28858        );
28859
28860        worker.run_until(async {}).await.expect("run worker");
28861    }
28862
28863    #[tokio::test]
28864    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
28865        let server = MockWorkerServer::start();
28866        let client = Client::builder(server.base_url())
28867            .timeout(Duration::from_secs(2))
28868            .build()
28869            .expect("client");
28870        let mut worker = Worker::new(client, "rust-workers")
28871            .worker_id("workflow-only-worker")
28872            .poll_timeout(Duration::from_millis(10));
28873
28874        worker.register_workflow(
28875            "workflow.only",
28876            |_ctx, _input| async move { Ok(Value::Null) },
28877        );
28878
28879        worker.run_until(async {}).await.expect("run worker");
28880    }
28881
28882    #[tokio::test]
28883    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
28884        let server = MockWorkerServer::start();
28885        let client = Client::builder(server.base_url())
28886            .timeout(Duration::from_secs(2))
28887            .build()
28888            .expect("client");
28889        let observations = Arc::new(Mutex::new(Vec::new()));
28890        let observed = Arc::clone(&observations);
28891        let mut worker = Worker::new(client, "rust-workers")
28892            .worker_id("observed-heartbeat-worker")
28893            .poll_timeout(Duration::from_millis(10))
28894            .on_worker_heartbeat(move |observation| {
28895                observed
28896                    .lock()
28897                    .expect("heartbeat observations")
28898                    .push(observation.clone());
28899            });
28900
28901        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
28902            Ok(Value::Null)
28903        });
28904        let acknowledged = Arc::clone(&observations);
28905        worker
28906            .run_until(async move {
28907                tokio::time::timeout(Duration::from_secs(2), async move {
28908                    loop {
28909                        if !acknowledged
28910                            .lock()
28911                            .expect("heartbeat observations")
28912                            .is_empty()
28913                        {
28914                            break;
28915                        }
28916                        tokio::time::sleep(Duration::from_millis(1)).await;
28917                    }
28918                })
28919                .await
28920                .expect("heartbeat acknowledgement within timeout");
28921            })
28922            .await
28923            .expect("run worker");
28924
28925        let observations = observations.lock().expect("heartbeat observations");
28926        let first = observations.first().expect("heartbeat acknowledgement");
28927        assert_eq!(first.worker_id, "observed-heartbeat-worker");
28928        assert_eq!(first.task_queue, "rust-workers");
28929        assert!(first.acknowledged_at_unix_millis > 0);
28930        assert_eq!(first.acknowledgement, json!({}));
28931    }
28932
28933    #[tokio::test]
28934    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
28935        let server = MockWorkerServer::delayed_heartbeat_worker();
28936        let client = Client::builder(server.base_url())
28937            .timeout(Duration::from_secs(3))
28938            .build()
28939            .expect("client");
28940        let observations = Arc::new(Mutex::new(Vec::new()));
28941        let observed = Arc::clone(&observations);
28942        let mut worker = Worker::new(client, "rust-snapshot-workers")
28943            .worker_id("rust-snapshot-worker")
28944            .poll_timeout(Duration::from_millis(10))
28945            .on_worker_heartbeat(move |observation| {
28946                observed
28947                    .lock()
28948                    .expect("heartbeat observations")
28949                    .push(observation.clone());
28950            });
28951
28952        worker.register_workflow("snapshot", |ctx, _input| async move {
28953            ctx.wait_signal("finish").await?;
28954            Ok(json!({"status": "finished"}))
28955        });
28956        worker.register_query("snapshot", "current", |ctx, _args| async move {
28957            Ok(json!(ctx
28958                .signals("increment")
28959                .iter()
28960                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28961                .sum::<i64>()))
28962        });
28963        worker.register_activity("cancel-aware", |_ctx, _args| async move {
28964            Ok(json!({"late": "completion"}))
28965        });
28966
28967        worker
28968            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
28969            .await
28970            .expect("delayed heartbeat must allow a clean worker shutdown");
28971
28972        let observations = observations.lock().expect("heartbeat observations");
28973        assert!(
28974            observations.len() >= 3,
28975            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
28976        );
28977        assert!(
28978            observations.windows(2).all(|pair| {
28979                pair[1].acknowledged_at_unix_millis
28980                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28981                    >= 850
28982            }),
28983            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
28984        );
28985        drop(observations);
28986
28987        let heartbeat_times = server.request_times("/api/worker/heartbeat");
28988        let delayed_request_at = *heartbeat_times
28989            .get(1)
28990            .expect("intentionally delayed heartbeat request");
28991        let delay_window_start = delayed_request_at + Duration::from_millis(100);
28992        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
28993        for path in [
28994            "/api/worker/workflow-tasks/poll",
28995            "/api/worker/activity-tasks/poll",
28996            "/api/worker/query-tasks/poll",
28997        ] {
28998            assert!(
28999                server
29000                    .request_times(path)
29001                    .iter()
29002                    .any(|received_at| *received_at >= delay_window_start
29003                        && *received_at <= delay_window_end),
29004                "{path} must keep polling while a heartbeat acknowledgement is delayed"
29005            );
29006        }
29007        assert!(
29008            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
29009            "workflow work must be settled"
29010        );
29011        assert!(
29012            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
29013            "activity work must be settled"
29014        );
29015        assert!(
29016            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
29017            "query work must be settled"
29018        );
29019    }
29020
29021    #[tokio::test]
29022    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
29023        let server = MockWorkerServer::heartbeat_retry_worker();
29024        let client = Client::builder(server.base_url())
29025            .timeout(Duration::from_secs(2))
29026            .build()
29027            .expect("client");
29028        let observations = Arc::new(Mutex::new(Vec::new()));
29029        let observed = Arc::clone(&observations);
29030        let worker = Worker::new(client, "rust-workers")
29031            .worker_id("heartbeat-retry-worker")
29032            .retry_policy(WorkerRetryPolicy {
29033                max_retries: 1,
29034                initial_backoff: Duration::from_millis(300),
29035                max_backoff: Duration::from_millis(300),
29036            })
29037            .on_worker_heartbeat(move |observation| {
29038                observed
29039                    .lock()
29040                    .expect("heartbeat observations")
29041                    .push(observation.clone());
29042            });
29043
29044        worker
29045            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
29046            .await
29047            .expect("retryable heartbeat failure must remain bounded and recover");
29048
29049        let observations = observations.lock().expect("heartbeat observations");
29050        assert!(observations.len() >= 3, "heartbeat retry must recover");
29051        assert!(
29052            observations.windows(2).all(|pair| {
29053                pair[1]
29054                    .acknowledged_at_unix_millis
29055                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
29056                    >= 850
29057            }),
29058            "a successful retry must start a fresh advertised cadence: {observations:?}"
29059        );
29060        assert_eq!(
29061            server.request_count("/api/worker/heartbeat"),
29062            observations.len() + 1,
29063            "one retryable failure must add exactly one bounded request"
29064        );
29065    }
29066
29067    #[tokio::test]
29068    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
29069        let server = MockWorkerServer::waiting_query_worker();
29070        let client = Client::builder(server.base_url())
29071            .timeout(Duration::from_secs(2))
29072            .build()
29073            .expect("client");
29074        let observations = Arc::new(Mutex::new(Vec::new()));
29075        let observed = Arc::clone(&observations);
29076        let mut worker = Worker::new(client, "rust-snapshot-workers")
29077            .worker_id("rust-snapshot-worker")
29078            .poll_timeout(Duration::from_millis(10))
29079            .on_worker_heartbeat(move |observation| {
29080                observed
29081                    .lock()
29082                    .expect("heartbeat observations")
29083                    .push(observation.clone());
29084            });
29085
29086        worker.register_workflow("snapshot", |ctx, _input| async move {
29087            ctx.wait_signal("finish").await?;
29088            Ok(json!({"status": "finished"}))
29089        });
29090        worker.register_query("snapshot", "current", |ctx, _args| async move {
29091            let current = ctx
29092                .signals("increment")
29093                .iter()
29094                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
29095                .sum::<i64>();
29096            Ok(json!(current))
29097        });
29098        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
29099        worker
29100            .declare_workflow_signals("snapshot", &["finish"])
29101            .expect("declare finish signal");
29102
29103        worker
29104            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
29105            .await
29106            .expect("pending workflow and query poller must remain live until shutdown");
29107
29108        assert!(
29109            observations.lock().expect("heartbeat observations").len() >= 4,
29110            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
29111        );
29112        assert!(
29113            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
29114            "workflow polling must continue after empty replay acknowledgements"
29115        );
29116        assert!(
29117            server.request_count("/api/worker/query-tasks/poll") >= 2,
29118            "query polling must continue after serving the current query"
29119        );
29120        assert_eq!(
29121            server.request_body("/api/worker/register")["capabilities"],
29122            json!([
29123                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
29124                "workflow_entry_arguments_validation",
29125                DURABLE_SELECTION_CAPABILITY,
29126                MEMO_UPSERTS_CAPABILITY,
29127                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
29128                QUERY_TASKS_CAPABILITY,
29129                WORKFLOW_UPDATES_CAPABILITY,
29130                MESSAGE_STREAMS_CAPABILITY
29131            ])
29132        );
29133        assert_eq!(
29134            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
29135            json!({
29136                "queries": ["current"],
29137                "query_contracts": [{
29138                    "name": "current",
29139                    "parameters": [{
29140                        "name": "args", "position": 0, "required": false,
29141                        "variadic": true, "type": null, "allows_null": true,
29142                        "default_available": false, "default": null,
29143                    }],
29144                }],
29145                "signals": ["finish"],
29146                "signal_contracts": [{
29147                    "name": "finish",
29148                    "parameters": [{
29149                        "name": "args", "position": 0, "required": false,
29150                        "variadic": true, "type": null, "allows_null": true,
29151                        "default_available": false, "default": null,
29152                    }],
29153                }],
29154                "updates": ["replace"],
29155                "update_contracts": [{
29156                    "name": "replace",
29157                    "parameters": [{
29158                        "name": "args", "position": 0, "required": false,
29159                        "variadic": true, "type": null, "allows_null": true,
29160                        "default_available": false, "default": null,
29161                    }],
29162                }],
29163                "update_validators": [],
29164            })
29165        );
29166
29167        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
29168        assert_eq!(
29169            opened["commands"],
29170            json!([{
29171                "type": "open_signal_wait",
29172                "signal_name": "finish",
29173            }])
29174        );
29175
29176        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
29177            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
29178            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
29179            let failure = server.request_body(&fail_path);
29180            assert_eq!(
29181                failure["failure"]["type"],
29182                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
29183            );
29184            assert_eq!(server.request_count(&completion_path), 0);
29185        }
29186
29187        let query_completion =
29188            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
29189        assert_eq!(query_completion["result"], json!(8));
29190
29191        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
29192        assert_eq!(
29193            server.request_count(terminal_path),
29194            1,
29195            "the matching signal must settle the workflow exactly once"
29196        );
29197        let terminal = server.request_body(terminal_path);
29198        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
29199        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
29200        assert_eq!(
29201            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
29202                .expect("terminal workflow result"),
29203            json!({"status": "finished"})
29204        );
29205    }
29206
29207    #[tokio::test]
29208    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
29209        let server = MockWorkerServer::transient_worker_failures();
29210        let client = Client::builder(server.base_url())
29211            .timeout(Duration::from_secs(2))
29212            .build()
29213            .expect("client");
29214        let mut worker = Worker::new(client, "rust-workers")
29215            .worker_id("retry-worker")
29216            .poll_timeout(Duration::from_millis(10))
29217            .retry_policy(WorkerRetryPolicy {
29218                max_retries: 2,
29219                initial_backoff: Duration::from_millis(1),
29220                max_backoff: Duration::from_millis(1),
29221            });
29222        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29223        worker.register_activity(
29224            "counter.activity",
29225            |_ctx, _input| async move { Ok(Value::Null) },
29226        );
29227        worker.register_query(
29228            "counter",
29229            "current",
29230            |_ctx, _args| async move { Ok(json!(8)) },
29231        );
29232
29233        worker
29234            .run_until(tokio::time::sleep(Duration::from_millis(75)))
29235            .await
29236            .expect("transient failures must not stop the worker");
29237
29238        for path in [
29239            "/api/worker/heartbeat",
29240            "/api/worker/workflow-tasks/poll",
29241            "/api/worker/activity-tasks/poll",
29242            "/api/worker/query-tasks/poll",
29243        ] {
29244            assert!(
29245                server.request_count(path) >= 2,
29246                "{path} must continue after its transient failure"
29247            );
29248        }
29249    }
29250
29251    #[tokio::test]
29252    async fn worker_continues_after_long_poll_capacity_backpressure() {
29253        let server = MockWorkerServer::capacity_limited_activity_poll();
29254        let client = Client::builder(server.base_url())
29255            .timeout(Duration::from_secs(2))
29256            .build()
29257            .expect("client");
29258        let mut worker = Worker::new(client, "rust-workers")
29259            .worker_id("capacity-worker")
29260            .poll_timeout(Duration::from_millis(10))
29261            .retry_policy(WorkerRetryPolicy {
29262                max_retries: 0,
29263                initial_backoff: Duration::from_millis(1),
29264                max_backoff: Duration::from_millis(1),
29265            });
29266        worker.register_activity("capacity.activity", |_ctx, _input| async move {
29267            Ok(json!({"handled": true}))
29268        });
29269
29270        worker
29271            .run_until(tokio::time::sleep(Duration::from_millis(50)))
29272            .await
29273            .expect("capacity backpressure must not stop the worker");
29274
29275        assert!(
29276            server.request_count("/api/worker/activity-tasks/poll") >= 2,
29277            "the activity poller must continue after capacity backpressure"
29278        );
29279        assert_eq!(
29280            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
29281            1,
29282            "the worker must complete work returned after capacity recovers"
29283        );
29284    }
29285
29286    #[test]
29287    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
29288        let capacity = Error::Http {
29289            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
29290            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
29291        };
29292        assert_eq!(
29293            worker_poll_capacity_retry_after(&capacity),
29294            Some(Duration::from_secs(3))
29295        );
29296
29297        let rejected_capacity = Error::Http {
29298            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
29299            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
29300        };
29301        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
29302        assert!(!worker_operation_is_retryable(&rejected_capacity));
29303
29304        let ordinary_rate_limit = Error::Http {
29305            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
29306            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
29307                .to_string(),
29308        };
29309        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
29310        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
29311    }
29312
29313    #[tokio::test]
29314    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
29315        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29316            poll_failures_per_path: 8,
29317            heartbeat_failures: 8,
29318            ..MockWorkerBehavior::default()
29319        });
29320        let client = Client::builder(server.base_url())
29321            .timeout(Duration::from_secs(2))
29322            .build()
29323            .expect("client");
29324        let acknowledgements = Arc::new(AtomicUsize::new(0));
29325        let observed = Arc::clone(&acknowledgements);
29326        let mut worker = Worker::new(client, "rust-workers")
29327            .recover_transient_outages(true)
29328            .poll_timeout(Duration::from_millis(10))
29329            .retry_policy(WorkerRetryPolicy {
29330                max_retries: 2,
29331                initial_backoff: Duration::from_millis(2),
29332                max_backoff: Duration::from_millis(5),
29333            })
29334            .on_worker_heartbeat(move |_| {
29335                observed.fetch_add(1, Ordering::SeqCst);
29336            });
29337        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29338        worker.register_activity(
29339            "counter.activity",
29340            |_ctx, _input| async move { Ok(Value::Null) },
29341        );
29342        worker.register_query("counter", "current", |_ctx, _args| async move {
29343            Ok(Value::Null)
29344        });
29345
29346        worker
29347            .run_until(tokio::time::sleep(Duration::from_millis(500)))
29348            .await
29349            .expect("a recoverable outage must not stop the service worker");
29350
29351        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
29352        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
29353        for path in [
29354            "/api/worker/workflow-tasks/poll",
29355            "/api/worker/activity-tasks/poll",
29356            "/api/worker/query-tasks/poll",
29357        ] {
29358            let bodies = server.request_bodies(path);
29359            assert!(bodies.len() >= 10, "{path} must resume after recovery");
29360            let first = &bodies[0]["poll_request_id"];
29361            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
29362            for body in &bodies[..9] {
29363                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
29364            }
29365            assert_ne!(&bodies[9]["poll_request_id"], first);
29366            let times = server.request_times(path);
29367            for pair in times[..9].windows(2) {
29368                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
29369            }
29370        }
29371    }
29372
29373    #[tokio::test]
29374    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
29375        for heartbeat_outage in [false, true] {
29376            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29377                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
29378                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
29379                ..MockWorkerBehavior::default()
29380            });
29381            let client = Client::builder(server.base_url()).build().expect("client");
29382            let mut worker = Worker::new(client, "rust-workers")
29383                .recover_transient_outages(true)
29384                .retry_policy(WorkerRetryPolicy {
29385                    max_retries: 1,
29386                    initial_backoff: Duration::from_secs(5),
29387                    max_backoff: Duration::from_secs(5),
29388                });
29389            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29390            let started = Instant::now();
29391            worker
29392                .run_until(tokio::time::sleep(Duration::from_millis(200)))
29393                .await
29394                .expect("shutdown during an outage is a normal stop");
29395            assert!(started.elapsed() < Duration::from_secs(1));
29396            let path = if heartbeat_outage {
29397                "/api/worker/heartbeat"
29398            } else {
29399                "/api/worker/workflow-tasks/poll"
29400            };
29401            assert_eq!(server.request_count(path), 1);
29402            assert_eq!(
29403                server.request_count("/api/worker/registrations/mock-worker"),
29404                1
29405            );
29406        }
29407    }
29408
29409    #[tokio::test]
29410    async fn worker_outage_recovery_keeps_run_once_bounded() {
29411        let server = MockWorkerServer::unavailable_polls();
29412        let client = Client::builder(server.base_url()).build().expect("client");
29413        let mut worker = Worker::new(client, "rust-workers")
29414            .recover_transient_outages(true)
29415            .retry_policy(WorkerRetryPolicy {
29416                max_retries: 2,
29417                initial_backoff: Duration::from_millis(1),
29418                max_backoff: Duration::from_millis(1),
29419            });
29420        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29421        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
29422        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
29423    }
29424
29425    #[tokio::test]
29426    async fn worker_outage_recovery_respects_disabled_retries() {
29427        let server = MockWorkerServer::unavailable_polls();
29428        let client = Client::builder(server.base_url()).build().expect("client");
29429        let mut worker = Worker::new(client, "rust-workers")
29430            .recover_transient_outages(true)
29431            .retry_policy(WorkerRetryPolicy {
29432                max_retries: 0,
29433                ..WorkerRetryPolicy::default()
29434            });
29435        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29436        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
29437        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29438    }
29439
29440    #[tokio::test]
29441    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
29442        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29443            heartbeat_failures: usize::MAX,
29444            unauthorized_polls: true,
29445            ..MockWorkerBehavior::default()
29446        });
29447        let client = Client::builder(server.base_url()).build().expect("client");
29448        let mut worker = Worker::new(client, "rust-workers")
29449            .recover_transient_outages(true)
29450            .retry_policy(WorkerRetryPolicy {
29451                max_retries: 1,
29452                initial_backoff: Duration::from_secs(5),
29453                max_backoff: Duration::from_secs(5),
29454            });
29455        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29456        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
29457            .await
29458            .expect("fatal poll errors must interrupt heartbeat recovery")
29459            .expect_err("authentication failure is terminal");
29460        assert!(
29461            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
29462        );
29463        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29464    }
29465
29466    #[tokio::test]
29467    async fn worker_bounds_transport_retries() {
29468        let server = MockWorkerServer::unavailable_polls();
29469        let client = Client::builder(server.base_url())
29470            .timeout(Duration::from_secs(2))
29471            .build()
29472            .expect("client");
29473        let mut worker = Worker::new(client, "rust-workers")
29474            .worker_id("bounded-retry-worker")
29475            .poll_timeout(Duration::from_millis(10))
29476            .retry_policy(WorkerRetryPolicy {
29477                max_retries: 2,
29478                initial_backoff: Duration::from_millis(1),
29479                max_backoff: Duration::from_millis(1),
29480            });
29481        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29482
29483        let error = worker.run().await.expect_err("retry bound must terminate");
29484        assert!(matches!(error, Error::Transport(_)));
29485        assert_eq!(
29486            server.request_count("/api/worker/workflow-tasks/poll"),
29487            3,
29488            "one initial request plus exactly two retries"
29489        );
29490    }
29491
29492    #[tokio::test]
29493    async fn worker_retry_policy_can_disable_poll_retries() {
29494        let server = MockWorkerServer::unavailable_polls();
29495        let client = Client::builder(server.base_url())
29496            .timeout(Duration::from_secs(2))
29497            .build()
29498            .expect("client");
29499        let mut worker = Worker::new(client, "rust-workers")
29500            .worker_id("no-retry-worker")
29501            .poll_timeout(Duration::from_millis(10))
29502            .retry_policy(WorkerRetryPolicy {
29503                max_retries: 0,
29504                initial_backoff: Duration::from_millis(1),
29505                max_backoff: Duration::from_millis(1),
29506            });
29507        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29508
29509        let error = worker
29510            .run_once()
29511            .await
29512            .expect_err("disabled retries must return the first transport failure");
29513        assert!(matches!(error, Error::Transport(_)));
29514        assert_eq!(
29515            server.request_count("/api/worker/workflow-tasks/poll"),
29516            1,
29517            "max_retries=0 must send only the initial request"
29518        );
29519    }
29520
29521    #[tokio::test]
29522    async fn worker_does_not_retry_authentication_failures() {
29523        let server = MockWorkerServer::unauthorized_polls();
29524        let client = Client::builder(server.base_url())
29525            .timeout(Duration::from_secs(2))
29526            .build()
29527            .expect("client");
29528        let mut worker = Worker::new(client, "rust-workers")
29529            .worker_id("unauthorized-worker")
29530            .recover_transient_outages(true)
29531            .poll_timeout(Duration::from_millis(10));
29532        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29533
29534        let error = worker
29535            .run()
29536            .await
29537            .expect_err("authentication must terminate");
29538        let Error::Http { status, body } = error else {
29539            panic!("expected stable HTTP authentication error");
29540        };
29541        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
29542        assert!(body.contains("authentication_failed"));
29543        assert_eq!(
29544            server.request_count("/api/worker/workflow-tasks/poll"),
29545            1,
29546            "authentication failures must not be retried"
29547        );
29548    }
29549
29550    #[test]
29551    fn duplicate_registration_keeps_the_original_workflow() {
29552        let client = Client::new("http://127.0.0.1:9").expect("client");
29553        let mut worker = Worker::new(client, "registration-tests");
29554        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29555        let original = Arc::clone(&worker.workflows["same"].execute);
29556        worker
29557            .set_workflow_definition_sources("same", &["first workflow source"])
29558            .expect("source identity");
29559        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
29560        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
29561        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
29562        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
29563    }
29564
29565    #[test]
29566    fn duplicate_registration_keeps_the_original_activity() {
29567        let client = Client::new("http://127.0.0.1:9").expect("client");
29568        let mut worker = Worker::new(client, "registration-tests");
29569        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
29570        let original = Arc::clone(&worker.activities["same"]);
29571        worker.register_activity_avro_value("same", |_ctx, _input| async {
29572            Ok(AvroValue::String("second".into()))
29573        });
29574        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
29575    }
29576
29577    #[test]
29578    fn duplicate_registration_keeps_original_query_and_update_handlers() {
29579        let client = Client::new("http://127.0.0.1:9").expect("client");
29580        let mut worker = Worker::new(client, "registration-tests");
29581        worker.register_query("orders", "same", |_ctx, _input| async {
29582            Ok(json!("first"))
29583        });
29584        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
29585            panic!("snapshot query");
29586        };
29587        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
29588            Ok(json!("second"))
29589        });
29590        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
29591            panic!("duplicate replaced the query adapter");
29592        };
29593        assert!(Arc::ptr_eq(&original, retained));
29594        worker.register_update("orders", "same", |_ctx, _input| async {
29595            Ok(json!("first"))
29596        });
29597        let original = Arc::clone(&worker.updates["orders"]["same"]);
29598        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
29599            Ok(AvroValue::Null)
29600        });
29601        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
29602    }
29603
29604    #[tokio::test]
29605    async fn duplicate_registration_fails_before_server_contact() {
29606        let server = MockWorkerServer::start();
29607        let client = Client::builder(server.base_url()).build().expect("client");
29608        let mut worker =
29609            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
29610        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29611        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
29612        let error = worker
29613            .run_once()
29614            .await
29615            .expect_err("ambiguous worker must not poll");
29616        assert!(
29617            error.to_string().contains("duplicate_registration"),
29618            "{error}"
29619        );
29620        assert!(server.requests.lock().expect("requests").is_empty());
29621    }
29622
29623    #[derive(Clone, Debug)]
29624    struct CapturedRequest {
29625        headers: String,
29626        method: String,
29627        path: String,
29628        authorization: Option<String>,
29629        namespace: Option<String>,
29630        worker_protocol: Option<String>,
29631        control_protocol: Option<String>,
29632        body: String,
29633        received_at: Instant,
29634    }
29635
29636    struct MockWorkerServer {
29637        addr: SocketAddr,
29638        stop: Arc<AtomicBool>,
29639        requests: Arc<Mutex<Vec<CapturedRequest>>>,
29640        thread: Option<thread::JoinHandle<()>>,
29641    }
29642
29643    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
29644
29645    #[derive(Clone, Copy, Default)]
29646    struct MockWorkerBehavior {
29647        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
29648        request_override: Option<RequestOverride>,
29649        storage_refusals: usize,
29650        storage_path: Option<&'static str>,
29651        storage_unavailable: bool,
29652        storage_mid_poll: bool,
29653        storage_activity: bool,
29654        storage_query: bool,
29655        storage_wrong_poll_id: bool,
29656        reject_query_protocol: bool,
29657        reject_query_completion: bool,
29658        waiting_query_worker: bool,
29659        decline_registration: bool,
29660        complete_named_signal: bool,
29661        poll_failures_per_path: usize,
29662        long_poll_capacity_responses_per_path: usize,
29663        heartbeat_failures: usize,
29664        heartbeat_failure_request: Option<usize>,
29665        delayed_heartbeat_request: Option<usize>,
29666        heartbeat_response_delay: Duration,
29667        concurrent_requests: bool,
29668        unauthorized_polls: bool,
29669        reject_registration: bool,
29670        reject_registration_protocol: bool,
29671        reject_deregistration: bool,
29672        reject_deregistration_protocol: bool,
29673        cancelled_activity: bool,
29674        draining_polls: bool,
29675        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
29676        workflow_completion_status: Option<&'static str>,
29677        workflow_completion_body: Option<&'static str>,
29678    }
29679
29680    impl MockWorkerServer {
29681        fn start() -> Self {
29682            Self::start_with_behavior(MockWorkerBehavior::default())
29683        }
29684
29685        fn reject_query_protocol() -> Self {
29686            Self::start_with_behavior(MockWorkerBehavior {
29687                reject_query_protocol: true,
29688                ..MockWorkerBehavior::default()
29689            })
29690        }
29691
29692        fn reject_query_completion() -> Self {
29693            Self::start_with_behavior(MockWorkerBehavior {
29694                reject_query_completion: true,
29695                ..MockWorkerBehavior::default()
29696            })
29697        }
29698
29699        fn waiting_query_worker() -> Self {
29700            Self::start_with_behavior(MockWorkerBehavior {
29701                waiting_query_worker: true,
29702                complete_named_signal: true,
29703                ..MockWorkerBehavior::default()
29704            })
29705        }
29706
29707        fn transient_worker_failures() -> Self {
29708            Self::start_with_behavior(MockWorkerBehavior {
29709                poll_failures_per_path: 1,
29710                heartbeat_failures: 1,
29711                ..MockWorkerBehavior::default()
29712            })
29713        }
29714
29715        fn consecutive_poll_failures(count: usize) -> Self {
29716            Self::start_with_behavior(MockWorkerBehavior {
29717                poll_failures_per_path: count,
29718                ..MockWorkerBehavior::default()
29719            })
29720        }
29721
29722        fn capacity_limited_activity_poll() -> Self {
29723            Self::start_with_behavior(MockWorkerBehavior {
29724                long_poll_capacity_responses_per_path: 1,
29725                ..MockWorkerBehavior::default()
29726            })
29727        }
29728
29729        fn delayed_heartbeat_worker() -> Self {
29730            Self::start_with_behavior(MockWorkerBehavior {
29731                waiting_query_worker: true,
29732                delayed_heartbeat_request: Some(2),
29733                heartbeat_response_delay: Duration::from_millis(1_500),
29734                concurrent_requests: true,
29735                cancelled_activity: true,
29736                ..MockWorkerBehavior::default()
29737            })
29738        }
29739
29740        fn heartbeat_retry_worker() -> Self {
29741            Self::start_with_behavior(MockWorkerBehavior {
29742                waiting_query_worker: true,
29743                heartbeat_failure_request: Some(2),
29744                concurrent_requests: true,
29745                ..MockWorkerBehavior::default()
29746            })
29747        }
29748
29749        fn unavailable_polls() -> Self {
29750            Self::start_with_behavior(MockWorkerBehavior {
29751                poll_failures_per_path: usize::MAX,
29752                ..MockWorkerBehavior::default()
29753            })
29754        }
29755
29756        fn unauthorized_polls() -> Self {
29757            Self::start_with_behavior(MockWorkerBehavior {
29758                unauthorized_polls: true,
29759                ..MockWorkerBehavior::default()
29760            })
29761        }
29762
29763        fn rejected_registration() -> Self {
29764            Self::start_with_behavior(MockWorkerBehavior {
29765                reject_registration: true,
29766                ..MockWorkerBehavior::default()
29767            })
29768        }
29769
29770        fn rejected_registration_protocol() -> Self {
29771            Self::start_with_behavior(MockWorkerBehavior {
29772                reject_registration_protocol: true,
29773                ..MockWorkerBehavior::default()
29774            })
29775        }
29776
29777        fn declined_registration() -> Self {
29778            Self::start_with_behavior(MockWorkerBehavior {
29779                decline_registration: true,
29780                ..MockWorkerBehavior::default()
29781            })
29782        }
29783
29784        fn rejected_deregistration() -> Self {
29785            Self::start_with_behavior(MockWorkerBehavior {
29786                reject_deregistration: true,
29787                ..MockWorkerBehavior::default()
29788            })
29789        }
29790
29791        fn rejected_deregistration_protocol() -> Self {
29792            Self::start_with_behavior(MockWorkerBehavior {
29793                reject_deregistration_protocol: true,
29794                ..MockWorkerBehavior::default()
29795            })
29796        }
29797
29798        fn unauthorized_polls_and_rejected_deregistration() -> Self {
29799            Self::start_with_behavior(MockWorkerBehavior {
29800                unauthorized_polls: true,
29801                reject_deregistration: true,
29802                ..MockWorkerBehavior::default()
29803            })
29804        }
29805
29806        fn cancelled_activity() -> Self {
29807            Self::start_with_behavior(MockWorkerBehavior {
29808                cancelled_activity: true,
29809                ..MockWorkerBehavior::default()
29810            })
29811        }
29812
29813        fn draining_polls() -> Self {
29814            Self::start_with_behavior(MockWorkerBehavior {
29815                draining_polls: true,
29816                ..MockWorkerBehavior::default()
29817            })
29818        }
29819
29820        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
29821            Self::start_with_behavior(MockWorkerBehavior {
29822                invalid_task_payload_codec: Some(codec),
29823                ..MockWorkerBehavior::default()
29824            })
29825        }
29826
29827        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
29828            Self::start_with_behavior(MockWorkerBehavior {
29829                workflow_completion_status: Some(status),
29830                workflow_completion_body: Some(body),
29831                ..MockWorkerBehavior::default()
29832            })
29833        }
29834
29835        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
29836            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
29837            listener
29838                .set_nonblocking(true)
29839                .expect("configure mock listener");
29840            let addr = listener.local_addr().expect("mock server address");
29841            let stop = Arc::new(AtomicBool::new(false));
29842            let server_stop = Arc::clone(&stop);
29843            let requests = Arc::new(Mutex::new(Vec::new()));
29844            let server_requests = Arc::clone(&requests);
29845            let thread = thread::spawn(move || {
29846                let mut request_threads = Vec::new();
29847                while !server_stop.load(Ordering::SeqCst) {
29848                    match listener.accept() {
29849                        Ok((mut stream, _)) => {
29850                            if behavior.concurrent_requests {
29851                                let requests = Arc::clone(&server_requests);
29852                                request_threads.push(thread::spawn(move || {
29853                                    handle_mock_worker_request(&mut stream, &requests, behavior)
29854                                }));
29855                            } else {
29856                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
29857                            }
29858                        }
29859                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
29860                            let mut index = 0;
29861                            while index < request_threads.len() {
29862                                if request_threads[index].is_finished() {
29863                                    request_threads
29864                                        .swap_remove(index)
29865                                        .join()
29866                                        .expect("join mock request");
29867                                } else {
29868                                    index += 1;
29869                                }
29870                            }
29871                            thread::sleep(Duration::from_millis(5));
29872                        }
29873                        Err(_) => break,
29874                    }
29875                }
29876                for request_thread in request_threads {
29877                    request_thread.join().expect("join mock request");
29878                }
29879            });
29880
29881            Self {
29882                addr,
29883                stop,
29884                requests,
29885                thread: Some(thread),
29886            }
29887        }
29888
29889        fn base_url(&self) -> String {
29890            format!("http://{}", self.addr)
29891        }
29892
29893        fn worker_protocol_for(&self, path: &str) -> Option<String> {
29894            self.requests
29895                .lock()
29896                .expect("captured requests")
29897                .iter()
29898                .find(|request| request.path == path)
29899                .and_then(|request| request.worker_protocol.clone())
29900        }
29901
29902        fn control_protocol_for(&self, path: &str) -> Option<String> {
29903            self.requests
29904                .lock()
29905                .expect("captured requests")
29906                .iter()
29907                .find(|request| request.path == path)
29908                .and_then(|request| request.control_protocol.clone())
29909        }
29910
29911        fn method_for(&self, path: &str) -> Option<String> {
29912            self.requests
29913                .lock()
29914                .expect("captured requests")
29915                .iter()
29916                .find(|request| request.path == path)
29917                .map(|request| request.method.clone())
29918        }
29919
29920        fn authorization_for(&self, path: &str) -> Option<String> {
29921            self.requests
29922                .lock()
29923                .expect("captured requests")
29924                .iter()
29925                .find(|request| request.path == path)
29926                .and_then(|request| request.authorization.clone())
29927        }
29928
29929        fn namespace_for(&self, path: &str) -> Option<String> {
29930            self.requests
29931                .lock()
29932                .expect("captured requests")
29933                .iter()
29934                .find(|request| request.path == path)
29935                .and_then(|request| request.namespace.clone())
29936        }
29937
29938        fn request_count(&self, path: &str) -> usize {
29939            self.requests
29940                .lock()
29941                .expect("captured requests")
29942                .iter()
29943                .filter(|request| request.path == path)
29944                .count()
29945        }
29946
29947        fn captured_paths(&self) -> Vec<String> {
29948            self.requests
29949                .lock()
29950                .expect("captured requests")
29951                .iter()
29952                .map(|request| request.path.clone())
29953                .collect()
29954        }
29955
29956        fn request_times(&self, path: &str) -> Vec<Instant> {
29957            self.requests
29958                .lock()
29959                .expect("captured requests")
29960                .iter()
29961                .filter(|request| request.path == path)
29962                .map(|request| request.received_at)
29963                .collect()
29964        }
29965
29966        fn request_body(&self, path: &str) -> Value {
29967            let requests = self.requests.lock().expect("captured requests");
29968            let body = &requests
29969                .iter()
29970                .find(|request| request.path == path)
29971                .unwrap_or_else(|| panic!("missing request for {path}"))
29972                .body;
29973            serde_json::from_str(body).unwrap_or_else(|error| {
29974                panic!("invalid JSON request body for {path}: {error}: {body:?}")
29975            })
29976        }
29977
29978        fn request_bodies(&self, path: &str) -> Vec<Value> {
29979            self.requests
29980                .lock()
29981                .expect("captured requests")
29982                .iter()
29983                .filter(|request| request.path == path)
29984                .map(|request| {
29985                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
29986                        panic!(
29987                            "invalid JSON request body for {path}: {error}: {:?}",
29988                            request.body
29989                        )
29990                    })
29991                })
29992                .collect()
29993        }
29994    }
29995
29996    impl Drop for MockWorkerServer {
29997        fn drop(&mut self) {
29998            self.stop.store(true, Ordering::SeqCst);
29999            let _ = TcpStream::connect(self.addr);
30000
30001            if let Some(thread) = self.thread.take() {
30002                thread.join().expect("join mock server");
30003            }
30004        }
30005    }
30006
30007    fn handle_mock_worker_request(
30008        stream: &mut TcpStream,
30009        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
30010        behavior: MockWorkerBehavior,
30011    ) {
30012        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
30013        let mut buffer = [0_u8; 8192];
30014        let mut request = Vec::new();
30015
30016        loop {
30017            match stream.read(&mut buffer) {
30018                Ok(0) => break,
30019                Ok(read) => {
30020                    request.extend_from_slice(&buffer[..read]);
30021                    if mock_request_is_complete(&request) {
30022                        break;
30023                    }
30024                }
30025                Err(error)
30026                    if matches!(
30027                        error.kind(),
30028                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
30029                    ) =>
30030                {
30031                    break;
30032                }
30033                Err(_) => return,
30034            }
30035        }
30036
30037        let request = String::from_utf8_lossy(&request);
30038        let body = request
30039            .split_once("\r\n\r\n")
30040            .map(|(_, body)| body)
30041            .unwrap_or_default();
30042        let path = request
30043            .lines()
30044            .next()
30045            .and_then(|line| line.split_whitespace().nth(1))
30046            .unwrap_or_default();
30047        let method = request
30048            .lines()
30049            .next()
30050            .and_then(|line| line.split_whitespace().next())
30051            .unwrap_or_default();
30052        let authorization = request.lines().find_map(|line| {
30053            let (name, value) = line.split_once(':')?;
30054            name.eq_ignore_ascii_case("Authorization")
30055                .then(|| value.trim().to_string())
30056        });
30057        let namespace = request.lines().find_map(|line| {
30058            let (name, value) = line.split_once(':')?;
30059            name.eq_ignore_ascii_case("X-Namespace")
30060                .then(|| value.trim().to_string())
30061        });
30062        let worker_protocol = request.lines().find_map(|line| {
30063            let (name, value) = line.split_once(':')?;
30064            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
30065                .then(|| value.trim().to_string())
30066        });
30067        let control_protocol = request.lines().find_map(|line| {
30068            let (name, value) = line.split_once(':')?;
30069            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
30070                .then(|| value.trim().to_string())
30071        });
30072        let request_number = {
30073            let mut requests = requests.lock().expect("captured requests");
30074            requests.push(CapturedRequest {
30075                headers: request
30076                    .split_once("\r\n\r\n")
30077                    .map_or("", |(headers, _)| headers)
30078                    .to_owned(),
30079                method: method.to_string(),
30080                path: path.to_string(),
30081                authorization,
30082                namespace,
30083                worker_protocol: worker_protocol.clone(),
30084                control_protocol,
30085                body: body.to_string(),
30086                received_at: Instant::now(),
30087            });
30088            requests
30089                .iter()
30090                .filter(|request| request.path == path)
30091                .count()
30092        };
30093
30094        if let Some(response) = behavior
30095            .request_override
30096            .and_then(|handler| handler(path, body, request_number))
30097        {
30098            write_mock_response(stream, response.0, &response.1);
30099            return;
30100        }
30101        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
30102            write_mock_response(stream, response.0, &response.1);
30103            return;
30104        }
30105        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
30106            return;
30107        }
30108        let pressure_path = behavior
30109            .storage_path
30110            .is_some_and(|part| path.contains(part));
30111        let prior_failures = if path.ends_with("/poll") {
30112            behavior.poll_failures_per_path
30113        } else {
30114            0
30115        };
30116        if pressure_path
30117            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
30118        {
30119            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
30120            let poll_id = path
30121                .ends_with("/poll")
30122                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
30123            let mut refusal = storage_refusal(
30124                poll_id,
30125                behavior.storage_unavailable,
30126                behavior.storage_mid_poll,
30127            );
30128            if behavior.storage_wrong_poll_id {
30129                refusal["poll_request_id"] = json!("wrong-poll");
30130            }
30131            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
30132            return;
30133        }
30134        if path.contains("/storage-task/")
30135            || path.contains("/storage-activity/")
30136            || path.contains("/storage-query/")
30137        {
30138            write_mock_response(stream, "200 OK", "{}");
30139            return;
30140        }
30141        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
30142            write_mock_response(stream, "200 OK", &json!({"task":{
30143                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
30144                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
30145                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
30146                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
30147                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
30148            }}).to_string());
30149            return;
30150        }
30151        if behavior.storage_activity
30152            && path == "/api/worker/activity-tasks/poll"
30153            && request_number == 1
30154        {
30155            write_mock_response(stream, "200 OK", &json!({"task":{
30156                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
30157                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
30158                "attempt_number":7, "lease_owner":"storage-worker"
30159            }}).to_string());
30160            return;
30161        }
30162
30163        if path == "/api/worker/register" {
30164            if behavior.reject_registration_protocol {
30165                write_mock_response(
30166                    stream,
30167                    "400 Bad Request",
30168                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
30169                );
30170                return;
30171            }
30172            if behavior.reject_registration {
30173                write_mock_response(
30174                    stream,
30175                    "503 Service Unavailable",
30176                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
30177                );
30178                return;
30179            }
30180        }
30181
30182        if path.starts_with("/api/worker/registrations/") {
30183            if behavior.reject_deregistration_protocol {
30184                write_mock_response(
30185                    stream,
30186                    "400 Bad Request",
30187                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
30188                );
30189            } else if behavior.reject_deregistration {
30190                write_mock_response(
30191                    stream,
30192                    "403 Forbidden",
30193                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
30194                );
30195            } else {
30196                write_mock_response(
30197                    stream,
30198                    "200 OK",
30199                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
30200                );
30201            }
30202            return;
30203        }
30204
30205        let is_poll = matches!(
30206            path,
30207            "/api/worker/workflow-tasks/poll"
30208                | "/api/worker/activity-tasks/poll"
30209                | "/api/worker/query-tasks/poll"
30210        );
30211        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
30212            write_mock_response(
30213                stream,
30214                "429 Too Many Requests",
30215                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
30216            );
30217            return;
30218        }
30219        if is_poll && request_number <= behavior.poll_failures_per_path {
30220            return;
30221        }
30222        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
30223            return;
30224        }
30225        if path == "/api/worker/heartbeat"
30226            && behavior.heartbeat_failure_request == Some(request_number)
30227        {
30228            return;
30229        }
30230        if path == "/api/worker/heartbeat"
30231            && behavior.delayed_heartbeat_request == Some(request_number)
30232        {
30233            thread::sleep(behavior.heartbeat_response_delay);
30234        }
30235        if behavior.unauthorized_polls && is_poll {
30236            write_mock_response(
30237                stream,
30238                "401 Unauthorized",
30239                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
30240            );
30241            return;
30242        }
30243        if behavior.draining_polls && is_poll {
30244            write_mock_response(
30245                stream,
30246                "409 Conflict",
30247                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
30248            );
30249            return;
30250        }
30251
30252        if let Some(codec_case) = behavior.invalid_task_payload_codec {
30253            if is_poll && request_number == 1 {
30254                let mut task = match path {
30255                    "/api/worker/workflow-tasks/poll" => json!({
30256                        "task_id": "codec-workflow",
30257                        "workflow_type": "codec.workflow",
30258                        "payload_codec": DEFAULT_CODEC,
30259                        "workflow_task_attempt": 1,
30260                        "lease_owner": "codec-worker"
30261                    }),
30262                    "/api/worker/activity-tasks/poll" => json!({
30263                        "task_id": "codec-activity",
30264                        "activity_attempt_id": "codec-activity-attempt",
30265                        "activity_type": "codec.activity",
30266                        "payload_codec": DEFAULT_CODEC,
30267                        "attempt_number": 1,
30268                        "lease_owner": "codec-worker"
30269                    }),
30270                    "/api/worker/query-tasks/poll" => json!({
30271                        "query_task_id": "codec-query",
30272                        "query_task_attempt": 1,
30273                        "workflow_type": "codec.workflow",
30274                        "query_name": "known",
30275                        "payload_codec": DEFAULT_CODEC,
30276                        "lease_owner": "codec-worker"
30277                    }),
30278                    _ => unreachable!("is_poll limits task codec probe paths"),
30279                };
30280                codec_case.apply(&mut task);
30281                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
30282                return;
30283            }
30284
30285            if matches!(
30286                path,
30287                "/api/worker/workflow-tasks/codec-workflow/fail"
30288                    | "/api/worker/activity-tasks/codec-activity/fail"
30289                    | "/api/worker/query-tasks/codec-query/fail"
30290            ) {
30291                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
30292                return;
30293            }
30294        }
30295
30296        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
30297            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
30298            let body = format!(
30299                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
30300            );
30301            write_mock_response(stream, "400 Bad Request", &body);
30302            return;
30303        }
30304
30305        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
30306        {
30307            write_mock_response(
30308                stream,
30309                "409 Conflict",
30310                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
30311            );
30312            return;
30313        }
30314
30315        if behavior.workflow_completion_status.is_some()
30316            && path == "/api/worker/workflow-tasks/poll"
30317            && request_number == 1
30318        {
30319            write_mock_response(
30320                stream,
30321                "200 OK",
30322                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"}}"#,
30323            );
30324            return;
30325        }
30326
30327        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
30328            if let (Some(status), Some(body)) = (
30329                behavior.workflow_completion_status,
30330                behavior.workflow_completion_body,
30331            ) {
30332                write_mock_response(stream, status, body);
30333                return;
30334            }
30335        }
30336
30337        if behavior.waiting_query_worker {
30338            if behavior.complete_named_signal
30339                && path == "/api/worker/workflow-tasks/poll"
30340                && request_number == 1
30341            {
30342                let body = json!({
30343                    "task": {
30344                        "task_id": "snapshot-open",
30345                        "workflow_id": "snapshot-1",
30346                        "run_id": "snapshot-run-1",
30347                        "workflow_type": "snapshot",
30348                        "payload_codec": DEFAULT_CODEC,
30349                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30350                            .expect("Avro workflow arguments"),
30351                        "history_events": [],
30352                        "workflow_task_attempt": 1,
30353                        "lease_owner": "rust-snapshot-worker"
30354                    }
30355                })
30356                .to_string();
30357                write_mock_response(stream, "200 OK", &body);
30358                return;
30359            }
30360
30361            let signal_request = request_number - usize::from(behavior.complete_named_signal);
30362            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
30363            if path == "/api/worker/workflow-tasks/poll"
30364                && signal_request >= 1
30365                && signal_request <= signal_request_limit
30366            {
30367                let finish = behavior.complete_named_signal && signal_request == 3;
30368                let amounts = if signal_request == 1 {
30369                    vec![3]
30370                } else {
30371                    vec![3, 5]
30372                };
30373                let task_id = if signal_request == 1 {
30374                    "snapshot-wait-3"
30375                } else if finish {
30376                    "snapshot-finish"
30377                } else {
30378                    "snapshot-wait-5"
30379                };
30380                let mut history_events = std::iter::once(json!({
30381                    "event_type": "SignalWaitOpened",
30382                    "payload": {"sequence": 1, "signal_name": "finish"}
30383                }))
30384                .chain(amounts.iter().enumerate().map(|(index, amount)| {
30385                    json!({
30386                        "event_type": "SignalReceived",
30387                        "payload": {
30388                            "signal_id": format!("increment-{amount}"),
30389                            "signal_name": "increment",
30390                            "workflow_sequence": index + 2,
30391                            "payload_codec": DEFAULT_CODEC,
30392                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30393                                .expect("Avro signal envelope")
30394                        }
30395                    })
30396                }))
30397                .collect::<Vec<_>>();
30398                let (resume_id, resume_name, resume_arguments) = if finish {
30399                    history_events.push(json!({
30400                        "event_type": "SignalReceived",
30401                        "payload": {
30402                            "signal_id": "finish",
30403                            "signal_name": "finish",
30404                            "workflow_sequence": 4,
30405                            "payload_codec": DEFAULT_CODEC,
30406                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30407                                .expect("Avro finish signal envelope")
30408                        }
30409                    }));
30410                    (
30411                        "finish".to_string(),
30412                        "finish".to_string(),
30413                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
30414                            .expect("Avro finish resume signal"),
30415                    )
30416                } else {
30417                    let amount = amounts.last().expect("amount");
30418                    (
30419                        format!("increment-{amount}"),
30420                        "increment".to_string(),
30421                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30422                            .expect("Avro increment resume signal"),
30423                    )
30424                };
30425                let body = json!({
30426                    "task": {
30427                        "task_id": task_id,
30428                        "workflow_id": "snapshot-1",
30429                        "run_id": "snapshot-run-1",
30430                        "workflow_type": "snapshot",
30431                        "payload_codec": DEFAULT_CODEC,
30432                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30433                            .expect("Avro workflow arguments"),
30434                        "history_events": history_events,
30435                        "workflow_task_attempt": 1,
30436                        "workflow_signal_id": resume_id,
30437                        "signal_name": resume_name,
30438                        "signal_arguments": resume_arguments,
30439                        "lease_owner": "rust-snapshot-worker"
30440                    }
30441                })
30442                .to_string();
30443                write_mock_response(stream, "200 OK", &body);
30444                return;
30445            }
30446
30447            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
30448                let history_events = [3, 5]
30449                    .into_iter()
30450                    .enumerate()
30451                    .map(|(index, amount)| {
30452                        json!({
30453                            "event_type": "SignalReceived",
30454                            "payload": {
30455                                "signal_id": format!("increment-{amount}"),
30456                                "signal_name": "increment",
30457                                "workflow_sequence": index + 2,
30458                                "payload_codec": DEFAULT_CODEC,
30459                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30460                                    .expect("Avro query signal envelope")
30461                            }
30462                        })
30463                    })
30464                    .collect::<Vec<_>>();
30465                let body = json!({
30466                    "task": {
30467                        "query_task_id": "snapshot-current",
30468                        "query_task_attempt": 1,
30469                        "lease_owner": "rust-snapshot-worker",
30470                        "workflow_id": "snapshot-1",
30471                        "run_id": "snapshot-run-1",
30472                        "workflow_type": "snapshot",
30473                        "query_name": "current",
30474                        "payload_codec": DEFAULT_CODEC,
30475                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30476                            .expect("Avro workflow arguments"),
30477                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30478                            .expect("Avro query arguments"),
30479                        "history_events": history_events,
30480                        "run_status": "waiting"
30481                    }
30482                })
30483                .to_string();
30484                write_mock_response(stream, "200 OK", &body);
30485                return;
30486            }
30487
30488            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
30489                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
30490            {
30491                write_mock_response(
30492                    stream,
30493                    "200 OK",
30494                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
30495                );
30496                return;
30497            }
30498
30499            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
30500                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
30501                return;
30502            }
30503
30504            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
30505                write_mock_response(
30506                    stream,
30507                    "200 OK",
30508                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
30509                );
30510                return;
30511            }
30512
30513            if path == "/api/worker/query-tasks/snapshot-current/complete" {
30514                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
30515                return;
30516            }
30517        }
30518
30519        if matches!(
30520            path,
30521            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
30522        ) {
30523            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30524                .expect("typed mock result");
30525            let body = json!({
30526                "result": typed_fidelity_probe().into_json().expect("result projection"),
30527                "result_envelope": result,
30528            })
30529            .to_string();
30530            write_mock_response(stream, "200 OK", &body);
30531            return;
30532        }
30533
30534        if path == "/api/workflows/typed-1" {
30535            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30536                .expect("typed mock result");
30537            let body = json!({
30538                "workflow_id": "typed-1",
30539                "run_id": "run-typed-1",
30540                "workflow_type": "typed.echo",
30541                "status": "completed",
30542                "output": typed_fidelity_probe().into_json().expect("output projection"),
30543                "output_envelope": result,
30544            })
30545            .to_string();
30546            write_mock_response(stream, "200 OK", &body);
30547            return;
30548        }
30549
30550        let (status, body) = match path {
30551            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
30552            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
30553            "/api/workflows" => (
30554                "201 Created",
30555                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
30556            ),
30557            "/api/worker/register" if behavior.decline_registration => (
30558                "200 OK",
30559                r#"{"worker_id":"declined-worker","registered":false}"#,
30560            ),
30561            "/api/worker/register" if behavior.waiting_query_worker => (
30562                "200 OK",
30563                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
30564            ),
30565            "/api/worker/register" => (
30566                "200 OK",
30567                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
30568            ),
30569            "/api/worker/heartbeat" => ("200 OK", "{}"),
30570            "/api/worker/activity-tasks/poll"
30571                if behavior.cancelled_activity && request_number == 1 =>
30572            {
30573                (
30574                    "200 OK",
30575                    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"}}"#,
30576                )
30577            }
30578            "/api/worker/activity-tasks/poll"
30579                if behavior.long_poll_capacity_responses_per_path > 0
30580                    && request_number
30581                        == behavior
30582                            .long_poll_capacity_responses_per_path
30583                            .saturating_add(1) =>
30584            {
30585                (
30586                    "200 OK",
30587                    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"}}"#,
30588                )
30589            }
30590            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
30591                ("200 OK", r#"{"task":null}"#)
30592            }
30593            "/api/worker/query-tasks/poll"
30594                if behavior.reject_query_completion && request_number == 1 =>
30595            {
30596                (
30597                    "200 OK",
30598                    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"}}"#,
30599                )
30600            }
30601            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
30602            "/api/worker/query-tasks/query-capture/complete"
30603            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
30604            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
30605                "200 OK",
30606                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
30607            ),
30608            "/api/worker/activity-tasks/activity-cancel/complete" => (
30609                "409 Conflict",
30610                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
30611            ),
30612            "/api/worker/activity-tasks/activity-typed/complete"
30613            | "/api/worker/activity-tasks/activity-typed/fail"
30614            | "/api/worker/activity-tasks/capacity-activity/complete"
30615            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
30616            "/api/workflows/counter-1/query/current" => (
30617                "200 OK",
30618                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
30619            ),
30620            "/api/workflows/counter-1/query/missing" => (
30621                "404 Not Found",
30622                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
30623            ),
30624            "/api/workflows/wf-lifecycle/cancel" => (
30625                "200 OK",
30626                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
30627            ),
30628            "/api/workflows/wf-lifecycle/terminate" => (
30629                "200 OK",
30630                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
30631            ),
30632            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
30633                "200 OK",
30634                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
30635            ),
30636            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
30637                "200 OK",
30638                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
30639            ),
30640            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
30641                "202 Accepted",
30642                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
30643            ),
30644            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
30645                "200 OK",
30646                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}"#,
30647            ),
30648            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
30649                "409 Conflict",
30650                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
30651            ),
30652            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
30653            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
30654                "409 Conflict",
30655                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
30656            ),
30657            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
30658                "200 OK",
30659                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"}]}}"#,
30660            ),
30661            "/api/workflows/wf-cancelled" => (
30662                "200 OK",
30663                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
30664            ),
30665            "/api/workflows/wf-terminated" => (
30666                "200 OK",
30667                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
30668            ),
30669            "/api/workflows/wf-timed-out" => (
30670                "200 OK",
30671                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
30672            ),
30673            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
30674                "200 OK",
30675                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
30676            ),
30677            "/api/workflows/wf-selected" => (
30678                "200 OK",
30679                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
30680            ),
30681            "/api/workflows/wf-selected/runs/run-selected" => (
30682                "200 OK",
30683                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
30684            ),
30685            _ => ("404 Not Found", r#"{"message":"not found"}"#),
30686        };
30687        write_mock_response(stream, status, body);
30688    }
30689
30690    fn mock_request_is_complete(request: &[u8]) -> bool {
30691        let Some(header_end) = request
30692            .windows(4)
30693            .position(|window| window == b"\r\n\r\n")
30694            .map(|position| position + 4)
30695        else {
30696            return false;
30697        };
30698        let headers = String::from_utf8_lossy(&request[..header_end]);
30699        let content_length = headers.lines().find_map(|line| {
30700            let (name, value) = line.split_once(':')?;
30701            name.eq_ignore_ascii_case("content-length")
30702                .then(|| value.trim().parse::<usize>().ok())
30703                .flatten()
30704        });
30705
30706        request.len() >= header_end + content_length.unwrap_or(0)
30707    }
30708
30709    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
30710        let response = format!(
30711            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
30712            body.len()
30713        );
30714
30715        let _ = stream.write_all(response.as_bytes());
30716        let _ = stream.flush();
30717    }
30718
30719    fn activity_completion_backend_recovery(
30720        path: &str,
30721        _body: &str,
30722        request_number: usize,
30723    ) -> Option<(&'static str, String)> {
30724        match path {
30725            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
30726                "200 OK",
30727                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(),
30728            )),
30729            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
30730                "503 Service Unavailable",
30731                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(),
30732            )),
30733            "/api/worker/activity-tasks/recover-activity/complete" => Some((
30734                "200 OK",
30735                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30736            )),
30737            _ => None,
30738        }
30739    }
30740
30741    fn workflow_completion_backend_recovery(
30742        path: &str,
30743        _body: &str,
30744        request_number: usize,
30745    ) -> Option<(&'static str, String)> {
30746        match path {
30747            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
30748                "200 OK",
30749                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
30750            )),
30751            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
30752                "503 Service Unavailable",
30753                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(),
30754            )),
30755            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
30756                "200 OK",
30757                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30758            )),
30759            _ => None,
30760        }
30761    }
30762
30763    fn workflow_completion_lock_pressure(
30764        path: &str,
30765        body: &str,
30766        request_number: usize,
30767    ) -> Option<(&'static str, String)> {
30768        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
30769            return Some((
30770                "503 Service Unavailable",
30771                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
30772                    "outcome":"deferred", "recorded":false, "retryable":true,
30773                    "retry_after_seconds":1, "task_id":"recover-workflow",
30774                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
30775                    "backend":{"driver":"sqlite", "lock_pressure":true}})
30776                .to_string(),
30777            ));
30778        }
30779        workflow_completion_backend_recovery(path, body, request_number)
30780    }
30781
30782    fn workflow_completion_lock_pressure_forever(
30783        path: &str,
30784        body: &str,
30785        request_number: usize,
30786    ) -> Option<(&'static str, String)> {
30787        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
30788            return workflow_completion_lock_pressure(path, body, 1);
30789        }
30790        workflow_completion_lock_pressure(path, body, request_number)
30791    }
30792
30793    fn workflow_completion_lock_pressure_then_expired(
30794        path: &str,
30795        body: &str,
30796        request_number: usize,
30797    ) -> Option<(&'static str, String)> {
30798        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
30799            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
30800                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
30801        }
30802        workflow_completion_lock_pressure(path, body, request_number)
30803    }
30804
30805    fn workflow_completion_lock_pressure_then_slow(
30806        path: &str,
30807        body: &str,
30808        request_number: usize,
30809    ) -> Option<(&'static str, String)> {
30810        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
30811            thread::sleep(Duration::from_secs(2));
30812        }
30813        workflow_completion_lock_pressure(path, body, request_number)
30814    }
30815
30816    fn workflow_completion_pressure_then_backend_loss(
30817        path: &str,
30818        body: &str,
30819        request_number: usize,
30820    ) -> Option<(&'static str, String)> {
30821        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
30822            return Some((
30823                "503 Service Unavailable",
30824                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
30825                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
30826                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
30827                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
30828                .to_string(),
30829            ));
30830        }
30831        workflow_completion_lock_pressure(path, body, request_number)
30832    }
30833
30834    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
30835        let client = Client::builder(server.base_url())
30836            .timeout(Duration::from_secs(4))
30837            .build()
30838            .unwrap();
30839        let mut worker = Worker::new(client, "recover-queue")
30840            .worker_id("recover-worker")
30841            .poll_timeout(Duration::from_millis(10));
30842        worker.register_workflow("recover.workflow", move |_ctx, _args| {
30843            let calls = Arc::clone(&calls);
30844            async move {
30845                calls.fetch_add(1, Ordering::SeqCst);
30846                Ok(json!("done"))
30847            }
30848        });
30849        worker
30850    }
30851
30852    #[tokio::test]
30853    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
30854        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30855            request_override: Some(workflow_completion_lock_pressure_forever),
30856            ..MockWorkerBehavior::default()
30857        });
30858        let calls = Arc::new(AtomicUsize::new(0));
30859        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
30860            .with_storage_admission(Arc::new(AtomicBool::new(false)));
30861        worker
30862            .client
30863            .worker_storage_admission
30864            .as_mut()
30865            .unwrap()
30866            .workflow_completion_retry_deadline =
30867            Some(tokio::time::Instant::now() + Duration::from_millis(250));
30868        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
30869            .await
30870            .unwrap();
30871        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
30872        assert_eq!(calls.load(Ordering::SeqCst), 1);
30873        assert_eq!(
30874            server
30875                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
30876                .len(),
30877            1
30878        );
30879    }
30880
30881    #[tokio::test]
30882    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
30883        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30884            request_override: Some(workflow_completion_lock_pressure_then_slow),
30885            ..MockWorkerBehavior::default()
30886        });
30887        let calls = Arc::new(AtomicUsize::new(0));
30888        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
30889            .with_storage_admission(Arc::new(AtomicBool::new(false)));
30890        let start = tokio::time::Instant::now();
30891        worker
30892            .client
30893            .worker_storage_admission
30894            .as_mut()
30895            .unwrap()
30896            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
30897        assert!(matches!(
30898            worker.poll_workflow_once().await,
30899            Err(Error::Timeout)
30900        ));
30901        assert!(start.elapsed() < Duration::from_secs(2));
30902        assert_eq!(calls.load(Ordering::SeqCst), 1);
30903        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30904        assert_eq!(bodies.len(), 2);
30905        assert_eq!(bodies[0], bodies[1]);
30906    }
30907
30908    #[tokio::test]
30909    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
30910        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30911            request_override: Some(workflow_completion_pressure_then_backend_loss),
30912            ..MockWorkerBehavior::default()
30913        });
30914        let calls = Arc::new(AtomicUsize::new(0));
30915        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
30916            .with_storage_admission(Arc::new(AtomicBool::new(false)));
30917        let start = tokio::time::Instant::now();
30918        worker
30919            .client
30920            .worker_storage_admission
30921            .as_mut()
30922            .unwrap()
30923            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
30924        let result = worker.poll_workflow_once().await;
30925        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
30926        assert!(start.elapsed() < Duration::from_secs(2));
30927        assert_eq!(calls.load(Ordering::SeqCst), 1);
30928        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30929        assert_eq!(bodies.len(), 2);
30930        assert_eq!(bodies[0], bodies[1]);
30931    }
30932
30933    #[tokio::test]
30934    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
30935        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30936            request_override: Some(workflow_completion_lock_pressure_forever),
30937            ..MockWorkerBehavior::default()
30938        });
30939        let calls = Arc::new(AtomicUsize::new(0));
30940        let stop = Arc::new(AtomicBool::new(false));
30941        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
30942            .with_storage_admission(Arc::clone(&stop));
30943        let shutdown = async {
30944            while server
30945                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
30946                .is_empty()
30947            {
30948                tokio::time::sleep(Duration::from_millis(10)).await;
30949            }
30950            stop.store(true, Ordering::SeqCst);
30951        };
30952        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
30953            tokio::join!(worker.poll_workflow_once(), shutdown)
30954        })
30955        .await
30956        .unwrap();
30957        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
30958        assert_eq!(calls.load(Ordering::SeqCst), 1);
30959        assert_eq!(
30960            server
30961                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
30962                .len(),
30963            1
30964        );
30965    }
30966
30967    #[tokio::test]
30968    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
30969        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30970            request_override: Some(workflow_completion_lock_pressure_then_expired),
30971            ..MockWorkerBehavior::default()
30972        });
30973        let calls = Arc::new(AtomicUsize::new(0));
30974        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
30975        let result = worker.run_once().await;
30976        assert!(
30977            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
30978        );
30979        assert_eq!(calls.load(Ordering::SeqCst), 1);
30980        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30981        assert_eq!(bodies.len(), 2);
30982        assert_eq!(bodies[0], bodies[1]);
30983        assert!(server
30984            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
30985            .is_empty());
30986    }
30987
30988    #[tokio::test]
30989    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
30990        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30991            request_override: Some(workflow_completion_lock_pressure),
30992            ..MockWorkerBehavior::default()
30993        });
30994        let client = Client::builder(server.base_url())
30995            .timeout(Duration::from_secs(2))
30996            .build()
30997            .unwrap();
30998        let calls = Arc::new(AtomicUsize::new(0));
30999        let mut worker = Worker::new(client, "recover-queue")
31000            .worker_id("recover-worker")
31001            .recover_transient_outages(true)
31002            .poll_timeout(Duration::from_millis(10))
31003            .retry_policy(WorkerRetryPolicy {
31004                max_retries: 1,
31005                initial_backoff: Duration::from_millis(10),
31006                max_backoff: Duration::from_millis(10),
31007            });
31008        worker.register_workflow("recover.workflow", {
31009            let calls = Arc::clone(&calls);
31010            move |_ctx, _args| {
31011                let calls = Arc::clone(&calls);
31012                async move {
31013                    calls.fetch_add(1, Ordering::SeqCst);
31014                    Ok(json!("done"))
31015                }
31016            }
31017        });
31018        let start = tokio::time::Instant::now();
31019        assert_eq!(worker.run_once().await.unwrap(), 1);
31020        assert!(start.elapsed() >= Duration::from_secs(1));
31021        assert_eq!(calls.load(Ordering::SeqCst), 1);
31022        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
31023        assert_eq!(bodies.len(), 2);
31024        assert_eq!(bodies[0], bodies[1]);
31025    }
31026
31027    #[test]
31028    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
31029        let path = "/worker/workflow-tasks/recover-workflow/complete";
31030        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
31031        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
31032            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
31033            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
31034            "backend":{"driver":"sqlite", "lock_pressure":true}});
31035        let error = |body: Value| Error::Http {
31036            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
31037            body: body.to_string(),
31038        };
31039        assert_eq!(
31040            worker_deferred_workflow_completion_retry_after(
31041                &error(response.clone()),
31042                path,
31043                Some(&request)
31044            ),
31045            Some(Duration::from_secs(1))
31046        );
31047        for (field, value) in [
31048            ("reason", json!("backend_unavailable")),
31049            ("operation", json!("complete_activity_task")),
31050            ("task_id", json!("other-task")),
31051            ("lease_owner", json!("other-owner")),
31052            ("workflow_task_attempt", json!(4)),
31053            ("recorded", json!(true)),
31054            ("recorded", Value::Null),
31055            ("recorded", json!("false")),
31056            ("retryable", json!(false)),
31057            ("retry_after_seconds", json!(0)),
31058            ("retry_after_seconds", json!(-1)),
31059            ("retry_after_seconds", json!(1.0)),
31060            ("retry_after_seconds", json!("1")),
31061            ("retry_after_seconds", json!(6)),
31062            ("backend", json!({"lock_pressure":false})),
31063        ] {
31064            let mut invalid = response.clone();
31065            invalid[field] = value;
31066            assert_eq!(
31067                worker_deferred_workflow_completion_retry_after(
31068                    &error(invalid),
31069                    path,
31070                    Some(&request)
31071                ),
31072                None,
31073                "invalid {field}"
31074            );
31075        }
31076        for field in [
31077            "reason",
31078            "operation",
31079            "task_id",
31080            "lease_owner",
31081            "workflow_task_attempt",
31082            "recorded",
31083            "retryable",
31084            "retry_after_seconds",
31085            "backend",
31086        ] {
31087            let mut missing = response.clone();
31088            missing.as_object_mut().unwrap().remove(field);
31089            assert_eq!(
31090                worker_deferred_workflow_completion_retry_after(
31091                    &error(missing),
31092                    path,
31093                    Some(&request)
31094                ),
31095                None,
31096                "missing {field}"
31097            );
31098        }
31099        assert_eq!(
31100            worker_deferred_workflow_completion_retry_after(
31101                &error(response.clone()),
31102                "/worker/activity-tasks/recover-workflow/complete",
31103                Some(&request)
31104            ),
31105            None
31106        );
31107        assert_eq!(
31108            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
31109            None
31110        );
31111        let wrong_status = Error::Http {
31112            status: reqwest::StatusCode::CONFLICT,
31113            body: response.to_string(),
31114        };
31115        assert_eq!(
31116            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
31117            None
31118        );
31119    }
31120
31121    fn activity_completion_stale_after_backend_recovery(
31122        path: &str,
31123        body: &str,
31124        request_number: usize,
31125    ) -> Option<(&'static str, String)> {
31126        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
31127            return Some((
31128                "409 Conflict",
31129                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(),
31130            ));
31131        }
31132        activity_completion_backend_recovery(path, body, request_number)
31133    }
31134
31135    fn activity_completion_remains_unavailable(
31136        path: &str,
31137        body: &str,
31138        request_number: usize,
31139    ) -> Option<(&'static str, String)> {
31140        if path == "/api/worker/activity-tasks/recover-activity/complete" {
31141            return activity_completion_backend_recovery(path, body, 1);
31142        }
31143        activity_completion_backend_recovery(path, body, request_number)
31144    }
31145
31146    #[tokio::test]
31147    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
31148        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31149            request_override: Some(activity_completion_backend_recovery),
31150            ..MockWorkerBehavior::default()
31151        });
31152        let client = Client::builder(server.base_url())
31153            .timeout(Duration::from_secs(2))
31154            .build()
31155            .expect("client");
31156        let handler_calls = Arc::new(AtomicUsize::new(0));
31157        let mut worker = Worker::new(client, "recover-queue")
31158            .worker_id("recover-worker")
31159            .poll_timeout(Duration::from_millis(10));
31160        worker.register_activity("recover.activity", {
31161            let handler_calls = Arc::clone(&handler_calls);
31162            move |_ctx, _args| {
31163                let handler_calls = Arc::clone(&handler_calls);
31164                async move {
31165                    handler_calls.fetch_add(1, Ordering::SeqCst);
31166                    Ok(json!("done"))
31167                }
31168            }
31169        });
31170
31171        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
31172        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
31173        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
31174        assert_eq!(bodies.len(), 2);
31175        assert_eq!(bodies[0], bodies[1]);
31176    }
31177
31178    #[tokio::test]
31179    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
31180        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31181            request_override: Some(workflow_completion_backend_recovery),
31182            ..MockWorkerBehavior::default()
31183        });
31184        let client = Client::builder(server.base_url())
31185            .timeout(Duration::from_secs(2))
31186            .build()
31187            .expect("client");
31188        let handler_calls = Arc::new(AtomicUsize::new(0));
31189        let mut worker = Worker::new(client, "recover-queue")
31190            .worker_id("recover-worker")
31191            .poll_timeout(Duration::from_millis(10));
31192        worker.register_workflow("recover.workflow", {
31193            let handler_calls = Arc::clone(&handler_calls);
31194            move |_ctx, _args| {
31195                let handler_calls = Arc::clone(&handler_calls);
31196                async move {
31197                    handler_calls.fetch_add(1, Ordering::SeqCst);
31198                    Ok(json!("done"))
31199                }
31200            }
31201        });
31202
31203        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
31204        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
31205        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
31206        assert_eq!(bodies.len(), 2);
31207        assert_eq!(bodies[0], bodies[1]);
31208    }
31209
31210    #[tokio::test]
31211    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
31212        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31213            request_override: Some(activity_completion_stale_after_backend_recovery),
31214            ..MockWorkerBehavior::default()
31215        });
31216        let client = Client::builder(server.base_url())
31217            .timeout(Duration::from_secs(2))
31218            .build()
31219            .expect("client");
31220        let handler_calls = Arc::new(AtomicUsize::new(0));
31221        let mut worker = Worker::new(client, "recover-queue")
31222            .worker_id("recover-worker")
31223            .poll_timeout(Duration::from_millis(10));
31224        worker.register_activity("recover.activity", {
31225            let handler_calls = Arc::clone(&handler_calls);
31226            move |_ctx, _args| {
31227                let handler_calls = Arc::clone(&handler_calls);
31228                async move {
31229                    handler_calls.fetch_add(1, Ordering::SeqCst);
31230                    Ok(json!("done"))
31231                }
31232            }
31233        });
31234
31235        assert_eq!(
31236            worker
31237                .run_once()
31238                .await
31239                .expect("authoritative stale outcome"),
31240            1
31241        );
31242        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
31243        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
31244        assert_eq!(bodies.len(), 2);
31245        assert_eq!(bodies[0], bodies[1]);
31246    }
31247
31248    #[test]
31249    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
31250        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
31251        let response = json!({
31252            "reason":"backend_unavailable", "operation":"complete_activity_task",
31253            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
31254            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
31255            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
31256        });
31257        let path = "/worker/activity-tasks/recover-activity/complete";
31258        let error = |body: Value| Error::Http {
31259            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
31260            body: body.to_string(),
31261        };
31262        assert_eq!(
31263            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
31264            Some(Duration::from_secs(1))
31265        );
31266
31267        for (field, invalid) in [
31268            ("operation", json!("poll_activity_task")),
31269            ("outcome", json!("rejected")),
31270            ("worker_id", json!("another-worker")),
31271            ("task_queue", json!("recover-queue")),
31272            ("retryable", json!(false)),
31273            ("retry_after_seconds", json!(0)),
31274            ("task_id", json!("another-task")),
31275            ("lease_owner", json!("another-worker")),
31276            ("activity_attempt_id", json!("another-attempt")),
31277        ] {
31278            let mut invalid_response = response.clone();
31279            invalid_response[field] = invalid;
31280            assert_eq!(
31281                worker_fenced_completion_retry_after(
31282                    &error(invalid_response),
31283                    path,
31284                    Some(&request)
31285                ),
31286                None,
31287                "must not retry mismatched {field}"
31288            );
31289        }
31290        assert_eq!(
31291            worker_fenced_completion_retry_after(&error(response), path, None),
31292            None
31293        );
31294    }
31295
31296    #[tokio::test]
31297    async fn shutdown_interrupts_fenced_completion_backend_wait() {
31298        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31299            request_override: Some(activity_completion_remains_unavailable),
31300            ..MockWorkerBehavior::default()
31301        });
31302        let client = Client::builder(server.base_url())
31303            .timeout(Duration::from_secs(2))
31304            .build()
31305            .expect("client");
31306        let stop = Arc::new(AtomicBool::new(false));
31307        let worker = Worker::new(client, "recover-queue")
31308            .worker_id("recover-worker")
31309            .with_storage_admission(Arc::clone(&stop));
31310        let completion = tokio::spawn(async move {
31311            worker
31312                .client
31313                .complete_activity_task(
31314                    "recover-activity",
31315                    "recover-attempt",
31316                    "recover-worker",
31317                    json!("done"),
31318                    DEFAULT_CODEC,
31319                )
31320                .await
31321        });
31322        let path = "/api/worker/activity-tasks/recover-activity/complete";
31323        tokio::time::timeout(Duration::from_secs(2), async {
31324            while server.request_count(path) == 0 {
31325                tokio::time::sleep(Duration::from_millis(10)).await;
31326            }
31327        })
31328        .await
31329        .expect("first completion request");
31330        stop.store(true, Ordering::SeqCst);
31331        let error = tokio::time::timeout(Duration::from_secs(1), completion)
31332            .await
31333            .expect("shutdown must interrupt retry wait")
31334            .expect("completion task")
31335            .expect_err("backend is still unavailable");
31336        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
31337        assert_eq!(server.request_count(path), 1);
31338    }
31339}