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 nexus;
12mod query_authority;
13mod runtime_payloads;
14mod runtime_uploads;
15mod sticky_worker;
16mod sticky_workflow_cache;
17mod worker_session;
18mod workflow_hydration;
19
20pub use cancellation_context::{
21    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
22};
23pub use cancellation_scope::CancellationScopeOpenReceipt;
24#[doc(hidden)]
25pub use cancellation_scope_history::{
26    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
27};
28#[doc(hidden)]
29pub use cancellation_scope_replay::CancellationScopeRequested;
30
31pub use cooperative_cancellation::{
32    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
33    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
34    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
35    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
36};
37
38use std::{
39    any::{type_name, Any, TypeId},
40    collections::{BTreeMap, BTreeSet, HashMap},
41    future::Future,
42    io::{self, Read},
43    pin::Pin,
44    sync::{
45        atomic::{AtomicBool, Ordering},
46        Arc, Mutex, OnceLock,
47    },
48    task::{Context as TaskContext, Poll},
49    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
50};
51
52use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
53use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
54use chrono::DateTime;
55use futures_util::{
56    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
57};
58pub use local_activity::LocalActivityOptions;
59use serde::{
60    de::DeserializeOwned,
61    ser::{SerializeMap, SerializeSeq},
62    Deserialize, Deserializer, Serialize, Serializer,
63};
64pub use serde_json::{json, Value};
65use sha2::{Digest, Sha256};
66pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
67use thiserror::Error;
68pub use uuid::Uuid;
69pub use worker_session::{WorkerSession, WorkerSessionOptions};
70
71pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
72pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
73
74/// Select the worker request protocol without enabling optional capabilities.
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum WorkerProtocolVersion {
78    /// Compatibility with Servers that implement only worker protocol 1.19.
79    V119,
80    /// The default worker protocol.
81    #[default]
82    V120,
83}
84
85impl WorkerProtocolVersion {
86    fn as_str(self) -> &'static str {
87        match self {
88            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
89            Self::V120 => WORKER_PROTOCOL_VERSION,
90        }
91    }
92}
93const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
94/// First additive worker protocol that defines portable worker-affinity features.
95pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
96pub const CONTROL_PLANE_VERSION: &str = "2";
97pub const DEFAULT_CODEC: &str = "avro";
98pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
99/// Worker-registration capability for authored condition-wait occurrence identity.
100pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
101    "condition_wait_occurrence_identity";
102/// Worker-registration capability for portable memo upserts.
103pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
104/// Worker-registration capability for server-routed read-only queries.
105pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
106/// Worker-registration capability for canonical typed search attributes.
107pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
108/// Worker-registration capability for synchronous workflow updates.
109pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
110/// Worker-registration capability for durable named input streams.
111pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
112/// Worker-registration capability for persisted first-completion selection.
113pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
114pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
115pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
116pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
117pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
118pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
119/// First additive worker protocol that defines query-task transport.
120pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
121/// First additive worker protocol that defines typed search-attribute upserts.
122pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
123/// First additive worker protocol that defines portable memo upserts.
124pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
125/// First additive worker protocol that preserves declared search-attribute types.
126pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
127/// First additive worker protocol that defines external durable condition waits.
128pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
129/// First additive worker protocol that preserves authored condition-wait occurrences.
130pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
131/// First additive worker protocol that defines durable selection groups.
132pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
133
134pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
135    let Some((major, minor)) = version.split_once('.') else {
136        return false;
137    };
138    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
139}
140
141fn validate_user_signal_name(signal_name: &str) -> Result<()> {
142    if signal_name == MESSAGE_STREAM_SIGNAL {
143        return Err(Error::Codec(format!(
144            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
145        )));
146    }
147    Ok(())
148}
149
150const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
151const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
152    "Workflow task waiting for scheduled history.";
153const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
154const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
155const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
156const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
157const MAX_MEMO_ENTRIES: usize = 100;
158const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
159const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
160
161const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
162    "lease_expired",
163    "query_task_not_found",
164    "query_task_not_leased",
165    "query_task_timed_out",
166    "query_deadline_unavailable",
167    "lease_owner_mismatch",
168    "query_task_attempt_mismatch",
169];
170
171/// Manifest for the default service-worker profile.
172///
173/// Inline local execution is enabled separately by [`Worker::local_activities`].
174/// Local execution, sessions and caching require explicit Worker configuration.
175pub fn portable_worker_affinity_capability_manifest() -> Value {
176    json!({
177        "local_activities": {
178            "supported": false,
179            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
180            "reason": "rust_worker_does_not_execute_record_local_activity",
181        },
182        "worker_sessions": {
183            "supported": false,
184            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
185            "reason": "rust_worker_has_no_typed_session_lifecycle",
186        },
187        "sticky_execution": {
188            "supported": false,
189            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
190            "reason": "rust_worker_uses_complete_durable_history_replay",
191        },
192    })
193}
194
195/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
196pub const AVRO_VALUE_SCHEMA_JSON: &str =
197    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
198pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
199pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
200const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
201
202static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
203static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
204    OnceLock::new();
205
206#[derive(Clone, Copy)]
207enum RequestProtocol {
208    ControlPlane,
209    DefaultWorker,
210    Worker(&'static str),
211}
212
213pub type Result<T> = std::result::Result<T, Error>;
214
215pub use nexus::{
216    NexusOperationFailure, NexusOperationMode, NexusOperationResult, NexusServiceCall,
217    NexusServiceOptions, NexusWaitFor,
218};
219
220#[derive(Debug, Error)]
221#[non_exhaustive]
222pub enum Error {
223    #[error("transport error: {0}")]
224    Transport(#[from] reqwest::Error),
225    #[error(
226        "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"
227    )]
228    InvalidBaseUrl,
229    #[error("json error: {0}")]
230    Json(#[from] serde_json::Error),
231    #[error("http {status}: {body}")]
232    Http {
233        status: reqwest::StatusCode,
234        body: String,
235    },
236    #[error("codec error: {0}")]
237    Codec(String),
238    #[error(transparent)]
239    QueryFailed(QueryFailure),
240    #[error(transparent)]
241    Protocol(ProtocolFailure),
242    #[error(transparent)]
243    NonDeterministicReplay(ReplayFailure),
244    #[error(transparent)]
245    ChildWorkflowFailed(ChildWorkflowFailure),
246    #[error(transparent)]
247    ActivityFailed(ActivityFailure),
248    #[error(transparent)]
249    NexusOperationFailed(Box<NexusOperationFailure>),
250    #[error(transparent)]
251    ParallelFailed(ParallelFailure),
252    #[error(transparent)]
253    SagaCompensationFailed(SagaCompensationFailure),
254    #[error(transparent)]
255    InvalidParallelGroup(ParallelGroupError),
256    #[error(transparent)]
257    DurableOperationCancelled(DurableOperationCancelled),
258    #[error(transparent)]
259    WorkflowCancellationRequested(WorkflowCancellationRequested),
260    #[error(transparent)]
261    CooperativeCancellationRequested(CooperativeCancellationRequested),
262    #[error(transparent)]
263    CancellationScopeRequested(CancellationScopeRequested),
264    #[error(transparent)]
265    WorkflowCommandRejected(WorkflowCommandRejection),
266    #[error(transparent)]
267    WorkflowFailed(WorkflowTerminalOutcome),
268    #[error(transparent)]
269    WorkflowCancelled(WorkflowTerminalOutcome),
270    #[error(transparent)]
271    WorkflowTerminated(WorkflowTerminalOutcome),
272    #[error(transparent)]
273    WorkflowTimedOut(WorkflowTerminalOutcome),
274    #[error(transparent)]
275    ActivityTaskRejected(ActivityTaskRejection),
276    #[error("workflow handler {0:?} is not registered")]
277    WorkflowNotRegistered(String),
278    #[error("activity handler {0:?} is not registered")]
279    ActivityNotRegistered(String),
280    #[error(
281        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
282    )]
283    HandlerType {
284        handler_kind: HandlerKind,
285        handler_name: String,
286        value_kind: HandlerValueKind,
287        rust_type: &'static str,
288        message: String,
289    },
290    #[error("workflow future yielded without emitting a durable command")]
291    WorkflowYieldedWithoutCommand,
292    #[error(
293        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
294    )]
295    MissingWorkflowCommandIdentity,
296    #[error("workflow state lock is poisoned")]
297    WorkflowStatePoisoned,
298    #[error("timer duration is too large for the worker protocol")]
299    TimerDurationOverflow,
300    #[error(transparent)]
301    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
302    #[error(transparent)]
303    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
304    #[error("operation timed out")]
305    Timeout,
306    #[error(
307        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
308    )]
309    MissingRoleCredentials {
310        role: &'static str,
311        opposite_role: &'static str,
312    },
313    #[error("worker loop error: {0}")]
314    WorkerLoop(String),
315    #[error(
316        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
317    )]
318    UnsupportedUpdateValidators { workflow_type: String },
319    #[error("{primary}; worker deregistration also failed: {deregistration}")]
320    WorkerShutdown {
321        primary: Box<Error>,
322        deregistration: Box<Error>,
323    },
324    #[error("invalid child workflow options: {0}")]
325    InvalidChildWorkflowOptions(String),
326    #[error("invalid workflow memo update: {0}")]
327    InvalidMemoUpdate(String),
328    #[error(
329        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
330    )]
331    WorkflowMemoUpdatesUnavailable,
332    #[error("cooperative cancellation is unavailable: {0}")]
333    CooperativeCancellationUnavailable(String),
334    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
335    CancellationScopeExecutionUnavailable,
336    #[error("invalid cooperative cancellation: {0}")]
337    InvalidCooperativeCancellation(String),
338    #[error("activity execution no longer owns its claim: {0}")]
339    ActivityExecutionAbandoned(String),
340    #[error(transparent)]
341    InvalidActivityOptions(ActivityOptionsError),
342    #[error(transparent)]
343    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
344    #[doc(hidden)]
345    #[error("workflow requested continue as new")]
346    ContinueAsNew(ContinueAsNewRequest),
347}
348
349/// Handler namespaces checked independently within a Worker.
350#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
351pub enum RegistrationKind {
352    Workflow,
353    Activity,
354    Query,
355    Update,
356}
357
358impl std::fmt::Display for RegistrationKind {
359    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
360        formatter.write_str(match self {
361            Self::Workflow => "workflow",
362            Self::Activity => "activity",
363            Self::Query => "query",
364            Self::Update => "update",
365        })
366    }
367}
368
369/// The authoring adapter and source location of a handler registration.
370#[derive(Clone, Debug, PartialEq, Eq)]
371pub struct HandlerRegistration {
372    pub method: &'static str,
373    pub handler_type: &'static str,
374    pub file: &'static str,
375    pub line: u32,
376    pub column: u32,
377}
378
379impl std::fmt::Display for HandlerRegistration {
380    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
381        write!(
382            formatter,
383            "{} at {}:{}:{} ({})",
384            self.method, self.file, self.line, self.column, self.handler_type
385        )
386    }
387}
388
389/// Ambiguous local configuration, rejected before contacting Server.
390#[derive(Clone, Debug, Error, PartialEq, Eq)]
391#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
392pub struct DuplicateRegistrationError {
393    pub handler_kind: RegistrationKind,
394    pub handler_name: String,
395    /// Query/update registrations are scoped to their owning workflow type.
396    pub workflow_type: Option<String>,
397    pub first_definition: HandlerRegistration,
398    pub second_definition: HandlerRegistration,
399}
400
401impl From<DuplicateRegistrationError> for Error {
402    fn from(error: DuplicateRegistrationError) -> Self {
403        Self::WorkerLoop(error.to_string())
404    }
405}
406
407/// Validation failure for a durable condition-wait definition.
408#[derive(Clone, Debug, Error, PartialEq, Eq)]
409pub enum ConditionWaitOptionsError {
410    #[error("condition_key must be non-empty")]
411    EmptyKey,
412    #[error("condition_definition_fingerprint must be non-empty")]
413    EmptyPredicateIdentity,
414    #[error("condition timeout is too large for the worker protocol")]
415    TimeoutOverflow,
416}
417
418/// Stable identity and optional durable timeout for a condition wait.
419///
420/// `predicate_identity` is recorded as the worker protocol's
421/// `condition_definition_fingerprint` and must change whenever predicate
422/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
423/// is written inline; it derives this identity from the predicate tokens.
424#[derive(Clone, Debug, PartialEq, Eq)]
425pub struct ConditionWaitOptions {
426    condition_key: String,
427    predicate_identity: String,
428    timeout: Option<Duration>,
429}
430
431impl ConditionWaitOptions {
432    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
433        Self {
434            condition_key: condition_key.into(),
435            predicate_identity: predicate_identity.into(),
436            timeout: None,
437        }
438    }
439
440    pub fn timeout(mut self, timeout: Duration) -> Self {
441        self.timeout = Some(timeout);
442        self
443    }
444
445    fn validate(
446        &self,
447    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
448        let condition_key = self.condition_key.trim();
449        if condition_key.is_empty() {
450            return Err(ConditionWaitOptionsError::EmptyKey);
451        }
452        let predicate_identity = self.predicate_identity.trim();
453        if predicate_identity.is_empty() {
454            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
455        }
456        let timeout_seconds = self
457            .timeout
458            .map(|timeout| {
459                timeout
460                    .as_secs()
461                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
462                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
463            })
464            .transpose()?;
465
466        Ok(ValidatedConditionWaitOptions {
467            condition_key: condition_key.to_string(),
468            predicate_identity: predicate_identity.to_string(),
469            timeout_seconds,
470        })
471    }
472}
473
474#[derive(Clone, Debug, PartialEq, Eq)]
475struct ValidatedConditionWaitOptions {
476    condition_key: String,
477    predicate_identity: String,
478    timeout_seconds: Option<u64>,
479}
480
481const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
482
483/// Unambiguous terminal result of a durable condition wait.
484#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
485#[serde(rename_all = "snake_case")]
486pub enum ConditionWaitResult {
487    Satisfied,
488    TimedOut,
489}
490
491impl ConditionWaitResult {
492    pub fn is_satisfied(self) -> bool {
493        self == Self::Satisfied
494    }
495
496    pub fn is_timed_out(self) -> bool {
497        self == Self::TimedOut
498    }
499}
500
501/// Build the stable condition definition identity used by [`wait_condition!`].
502#[doc(hidden)]
503pub fn __condition_definition_fingerprint(source: &str) -> String {
504    let mut digest = Sha256::new();
505    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
506    digest.update(source.as_bytes());
507    format!("sha256:{:x}", digest.finalize())
508}
509
510/// Create a durable condition wait whose predicate definition is fingerprinted
511/// from its inline Rust tokens.
512///
513/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
514/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
515#[macro_export]
516macro_rules! wait_condition {
517    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
518        $ctx.wait_condition(
519            $crate::ConditionWaitOptions::new(
520                $key,
521                $crate::__condition_definition_fingerprint(concat!(
522                    module_path!(),
523                    "\0",
524                    stringify!($predicate)
525                )),
526            )
527            .timeout($timeout),
528            $predicate,
529        )
530    }};
531    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
532        $ctx.wait_condition(
533            $crate::ConditionWaitOptions::new(
534                $key,
535                $crate::__condition_definition_fingerprint(concat!(
536                    module_path!(),
537                    "\0",
538                    stringify!($predicate)
539                )),
540            ),
541            $predicate,
542        )
543    }};
544}
545
546const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
547const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
548const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
549const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
550const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
551
552/// Validation failure for a typed workflow search-attribute update.
553#[derive(Clone, Debug, Error, PartialEq, Eq)]
554pub enum SearchAttributeUpdateError {
555    #[error("search-attribute update requires at least one attribute")]
556    Empty,
557    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
558    InvalidKey(String),
559    #[error("search-attribute update exceeds the limit of 100 attributes")]
560    TooManyAttributes,
561    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
562    ValueTooLong {
563        key: String,
564        kind: &'static str,
565        limit: usize,
566    },
567    #[error(
568        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
569    )]
570    EmptyString(String),
571    #[error("search attribute {0:?} has a non-finite float value")]
572    NonFiniteFloat(String),
573    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
574    InvalidDateTime(String),
575    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
576    PayloadTooLarge,
577}
578
579/// One public typed search-attribute value.
580#[derive(Clone, Debug, PartialEq)]
581pub enum SearchAttributeValue {
582    String(String),
583    Keyword(String),
584    KeywordList(Vec<String>),
585    Int(i64),
586    Float(f64),
587    Bool(bool),
588    DateTime(String),
589    Delete,
590}
591
592impl SearchAttributeValue {
593    fn type_name(&self) -> Option<&'static str> {
594        match self {
595            Self::String(_) => Some("string"),
596            Self::Keyword(_) => Some("keyword"),
597            Self::KeywordList(_) => Some("keyword_list"),
598            Self::Int(_) => Some("int"),
599            Self::Float(_) => Some("float"),
600            Self::Bool(_) => Some("bool"),
601            Self::DateTime(_) => Some("datetime"),
602            Self::Delete => None,
603        }
604    }
605
606    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
607        let normalize_string = |value: String, kind: &'static str, limit: usize| {
608            let value = value.trim().to_string();
609            if value.is_empty() {
610                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
611            }
612            if value.len() > limit {
613                return Err(SearchAttributeUpdateError::ValueTooLong {
614                    key: key.to_string(),
615                    kind,
616                    limit,
617                });
618            }
619            Ok(value)
620        };
621
622        match self {
623            Self::String(value) => Ok(Self::String(normalize_string(
624                value,
625                "string",
626                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
627            )?)),
628            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
629                value,
630                "keyword",
631                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
632            )?)),
633            Self::KeywordList(values) => {
634                let values = values
635                    .into_iter()
636                    .map(|value| {
637                        let value = value.trim().to_string();
638                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
639                            return Err(SearchAttributeUpdateError::ValueTooLong {
640                                key: key.to_string(),
641                                kind: "keyword-list entry",
642                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
643                            });
644                        }
645                        Ok(value)
646                    })
647                    .collect::<std::result::Result<Vec<_>, _>>()?;
648                Ok(Self::KeywordList(values))
649            }
650            Self::Float(value) if !value.is_finite() => {
651                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
652            }
653            Self::DateTime(value) => {
654                let value =
655                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
656                if DateTime::parse_from_rfc3339(&value).is_err() {
657                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
658                }
659                Ok(Self::DateTime(value))
660            }
661            value => Ok(value),
662        }
663    }
664
665    fn into_json(self) -> Value {
666        match self {
667            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
668                Value::String(value)
669            }
670            Self::KeywordList(values) => {
671                Value::Array(values.into_iter().map(Value::String).collect())
672            }
673            Self::Int(value) => json!(value),
674            Self::Float(value) => json!(value),
675            Self::Bool(value) => json!(value),
676            Self::Delete => Value::Null,
677        }
678    }
679}
680
681/// Validated typed workflow-side search-attribute mutation.
682#[derive(Clone, Debug, Default, PartialEq)]
683pub struct SearchAttributeUpdate {
684    attributes: BTreeMap<String, SearchAttributeValue>,
685}
686
687impl SearchAttributeUpdate {
688    pub fn new() -> Self {
689        Self::default()
690    }
691
692    pub fn set(
693        mut self,
694        key: impl Into<String>,
695        value: SearchAttributeValue,
696    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
697        let key = key.into();
698        validate_search_attribute_key(&key)?;
699        if !self.attributes.contains_key(&key)
700            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
701        {
702            return Err(SearchAttributeUpdateError::TooManyAttributes);
703        }
704        self.attributes.insert(key.clone(), value.normalized(&key)?);
705        self.validate_size()?;
706        Ok(self)
707    }
708
709    pub fn string(
710        self,
711        key: impl Into<String>,
712        value: impl Into<String>,
713    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
714        self.set(key, SearchAttributeValue::String(value.into()))
715    }
716
717    pub fn keyword(
718        self,
719        key: impl Into<String>,
720        value: impl Into<String>,
721    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
722        self.set(key, SearchAttributeValue::Keyword(value.into()))
723    }
724
725    pub fn keyword_list<I, V>(
726        self,
727        key: impl Into<String>,
728        values: I,
729    ) -> std::result::Result<Self, SearchAttributeUpdateError>
730    where
731        I: IntoIterator<Item = V>,
732        V: Into<String>,
733    {
734        self.set(
735            key,
736            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
737        )
738    }
739
740    pub fn int(
741        self,
742        key: impl Into<String>,
743        value: i64,
744    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
745        self.set(key, SearchAttributeValue::Int(value))
746    }
747
748    pub fn float(
749        self,
750        key: impl Into<String>,
751        value: f64,
752    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
753        self.set(key, SearchAttributeValue::Float(value))
754    }
755
756    pub fn bool(
757        self,
758        key: impl Into<String>,
759        value: bool,
760    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
761        self.set(key, SearchAttributeValue::Bool(value))
762    }
763
764    pub fn datetime(
765        self,
766        key: impl Into<String>,
767        value: impl Into<String>,
768    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
769        self.set(key, SearchAttributeValue::DateTime(value.into()))
770    }
771
772    pub fn delete(
773        self,
774        key: impl Into<String>,
775    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
776        self.set(key, SearchAttributeValue::Delete)
777    }
778
779    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
780        let (attributes, _) = self.clone().into_wire_parts();
781        if serde_json::to_vec(&attributes)
782            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
783            .unwrap_or(true)
784        {
785            return Err(SearchAttributeUpdateError::PayloadTooLarge);
786        }
787        Ok(())
788    }
789
790    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
791        let mut attributes = serde_json::Map::new();
792        let mut attribute_types = BTreeMap::new();
793        for (key, value) in self.attributes {
794            if let Some(type_name) = value.type_name() {
795                attribute_types.insert(key.clone(), type_name.to_string());
796            }
797            attributes.insert(key, value.into_json());
798        }
799        (Value::Object(attributes), attribute_types)
800    }
801
802    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
803        if self.attributes.is_empty() {
804            return Err(SearchAttributeUpdateError::Empty);
805        }
806        self.validate_size()
807    }
808}
809
810fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
811    let valid = !key.is_empty()
812        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
813        && key
814            .bytes()
815            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
816    if valid {
817        Ok(())
818    } else {
819        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
820    }
821}
822
823/// The registered handler family reported by [`Error::HandlerType`].
824#[derive(Clone, Copy, Debug, PartialEq, Eq)]
825pub enum HandlerKind {
826    Workflow,
827    Activity,
828}
829
830impl std::fmt::Display for HandlerKind {
831    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
832        formatter.write_str(match self {
833            Self::Workflow => "workflow",
834            Self::Activity => "activity",
835        })
836    }
837}
838
839/// Whether a typed handler failed to adapt its input or result.
840#[derive(Clone, Copy, Debug, PartialEq, Eq)]
841pub enum HandlerValueKind {
842    Input,
843    Result,
844}
845
846impl std::fmt::Display for HandlerValueKind {
847    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
848        formatter.write_str(match self {
849            Self::Input => "input",
850            Self::Result => "result",
851        })
852    }
853}
854
855/// The lifecycle command sent to a workflow execution.
856#[derive(Clone, Copy, Debug, PartialEq, Eq)]
857pub enum WorkflowCommandKind {
858    Cancel,
859    Terminate,
860}
861
862impl WorkflowCommandKind {
863    fn as_str(self) -> &'static str {
864        match self {
865            Self::Cancel => "cancel",
866            Self::Terminate => "terminate",
867        }
868    }
869}
870
871/// Optional structured fields for a cancellation or termination request.
872#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
873pub struct WorkflowCommandOptions {
874    #[serde(skip_serializing_if = "Option::is_none")]
875    pub reason: Option<String>,
876    #[serde(skip_serializing_if = "Option::is_none")]
877    pub request_id: Option<String>,
878}
879
880/// Server-enforced timeout policy for a workflow start.
881///
882/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
883/// only bounds how long the caller waits. A server deadline produces a terminal
884/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
885/// `run_timeout`.
886#[derive(Clone, Debug, PartialEq, Eq)]
887pub struct WorkflowStartOptions {
888    pub execution_timeout_seconds: u64,
889    pub run_timeout_seconds: u64,
890}
891
892impl Default for WorkflowStartOptions {
893    fn default() -> Self {
894        Self {
895            execution_timeout_seconds: 3600,
896            run_timeout_seconds: 600,
897        }
898    }
899}
900
901impl WorkflowStartOptions {
902    pub fn new() -> Self {
903        Self::default()
904    }
905
906    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
907        self.execution_timeout_seconds = seconds;
908        self
909    }
910
911    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
912        self.run_timeout_seconds = seconds;
913        self
914    }
915
916    fn validate(&self) -> Result<()> {
917        if self.execution_timeout_seconds == 0 {
918            return Err(Error::Codec(
919                "execution_timeout_seconds must be at least 1".to_string(),
920            ));
921        }
922        if self.run_timeout_seconds == 0 {
923            return Err(Error::Codec(
924                "run_timeout_seconds must be at least 1".to_string(),
925            ));
926        }
927        if self.run_timeout_seconds > self.execution_timeout_seconds {
928            return Err(Error::Codec(
929                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
930            ));
931        }
932
933        Ok(())
934    }
935}
936
937/// Optional routing overrides for a continue-as-new transition.
938///
939/// Omitted values retain the current workflow type and task queue. Server-owned
940/// instance metadata is not accepted here and is carried by the server.
941#[derive(Clone, Debug, Default, PartialEq, Eq)]
942pub struct ContinueAsNewOptions {
943    pub workflow_type: Option<String>,
944    pub task_queue: Option<String>,
945}
946
947impl ContinueAsNewOptions {
948    pub fn new() -> Self {
949        Self::default()
950    }
951
952    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
953        self.workflow_type = Some(workflow_type.into());
954        self
955    }
956
957    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
958        self.task_queue = Some(task_queue.into());
959        self
960    }
961
962    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
963        for (field, value) in [
964            ("workflow_type", self.workflow_type.as_deref()),
965            ("task_queue", self.task_queue.as_deref()),
966        ] {
967            if value.is_some_and(|value| value.trim().is_empty()) {
968                return Err(ContinueAsNewOptionsError {
969                    field,
970                    message: format!("{field} must not be empty"),
971                });
972            }
973        }
974        Ok(())
975    }
976}
977
978/// A stable validation error raised before a continue-as-new command is emitted.
979#[derive(Clone, Debug, Error, PartialEq, Eq)]
980#[error("invalid continue-as-new option {field}: {message}")]
981pub struct ContinueAsNewOptionsError {
982    pub field: &'static str,
983    pub message: String,
984}
985
986/// Public history-budget information attached to the current workflow task.
987#[derive(Clone, Debug, Default, PartialEq, Eq)]
988pub struct WorkflowHistoryBudget {
989    pub event_count: u64,
990    pub size_bytes: Option<u64>,
991    pub continue_as_new_recommended: bool,
992    pub pressure: Option<String>,
993}
994
995#[doc(hidden)]
996#[derive(Clone, Debug)]
997pub struct ContinueAsNewRequest {
998    arguments: AvroValue,
999    options: ContinueAsNewOptions,
1000}
1001
1002impl WorkflowCommandOptions {
1003    pub fn new() -> Self {
1004        Self::default()
1005    }
1006
1007    pub fn reason(mut self, reason: impl Into<String>) -> Self {
1008        self.reason = Some(reason.into());
1009        self
1010    }
1011
1012    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1013        self.request_id = Some(request_id.into());
1014        self
1015    }
1016}
1017
1018/// The accepted, machine-readable result of a lifecycle command.
1019#[derive(Clone, Debug, PartialEq)]
1020pub struct WorkflowCommandResult {
1021    pub command: WorkflowCommandKind,
1022    pub workflow_id: String,
1023    pub run_id: Option<String>,
1024    pub outcome: Option<String>,
1025    pub reason: Option<String>,
1026    pub command_status: Option<String>,
1027    pub raw: Value,
1028}
1029
1030/// A new run continuing a failed run from its recorded activity boundary.
1031#[derive(Clone, Debug, PartialEq)]
1032pub struct WorkflowRedriveResult {
1033    pub workflow_id: String,
1034    pub source_run_id: String,
1035    pub run_id: String,
1036    pub resume_step_sequence: u64,
1037    pub raw: Value,
1038}
1039
1040/// A stable rejection returned by instance- or selected-run lifecycle commands.
1041#[derive(Clone, Debug, Error)]
1042#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1043pub struct WorkflowCommandRejection {
1044    pub command: WorkflowCommandKind,
1045    pub status: u16,
1046    pub reason: String,
1047    pub message: String,
1048    pub workflow_id: String,
1049    pub run_id: Option<String>,
1050    pub target_scope: Option<String>,
1051    pub body: Value,
1052}
1053
1054/// Stable terminal categories returned by [`WorkflowHandle::result`].
1055#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1056pub enum WorkflowTerminalKind {
1057    Failed,
1058    Cancelled,
1059    Terminated,
1060    TimedOut,
1061}
1062
1063/// A typed terminal workflow outcome with durable identity and failure metadata.
1064///
1065/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1066/// of parsing its display representation. Fields remain `None` when an older
1067/// server did not publish that metadata.
1068#[derive(Clone, Debug, Error)]
1069#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1070pub struct WorkflowTerminalOutcome {
1071    pub kind: WorkflowTerminalKind,
1072    pub workflow_id: String,
1073    pub run_id: Option<String>,
1074    pub reason: String,
1075    pub failure_category: Option<String>,
1076    pub failure_id: Option<String>,
1077    pub exception_type: Option<String>,
1078    pub exception_class: Option<String>,
1079    pub non_retryable: Option<bool>,
1080    pub message: Option<String>,
1081    pub exception: Option<Value>,
1082    pub raw: Value,
1083}
1084
1085/// A worker-side activity settlement or heartbeat rejected by durable state.
1086#[derive(Clone, Debug, Error)]
1087#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1088pub struct ActivityTaskRejection {
1089    pub operation: String,
1090    pub status: u16,
1091    pub reason: String,
1092    pub task_id: String,
1093    pub activity_attempt_id: String,
1094    pub cancel_requested: bool,
1095    pub can_continue: Option<bool>,
1096    pub run_closed_reason: Option<String>,
1097    pub body: Value,
1098}
1099
1100/// Stable validation categories for [`ActivityOptions`].
1101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1102pub enum ActivityOptionsErrorKind {
1103    EmptyTaskQueue,
1104    EmptyRetryPolicy,
1105    InvalidMaxAttempts,
1106    BackoffWithoutRetryBudget,
1107    TooManyBackoffIntervals,
1108    InvalidBackoffCoefficient,
1109    BackoffGenerationTooLarge,
1110    BackoffOverflow,
1111    EmptyNonRetryableErrorType,
1112    TimeoutNotPositive,
1113    MissingTotalTimeout,
1114    TimeoutOverflow,
1115    TimeoutOrder,
1116}
1117
1118/// A machine-readable activity-options validation failure.
1119#[derive(Clone, Debug, Error, PartialEq, Eq)]
1120#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1121pub struct ActivityOptionsError {
1122    pub kind: ActivityOptionsErrorKind,
1123    pub field: Option<&'static str>,
1124    pub message: String,
1125}
1126
1127impl ActivityOptionsError {
1128    fn new(
1129        kind: ActivityOptionsErrorKind,
1130        field: Option<&'static str>,
1131        message: impl Into<String>,
1132    ) -> Self {
1133        Self {
1134            kind,
1135            field,
1136            message: message.into(),
1137        }
1138    }
1139}
1140
1141/// Stable terminal categories returned when an awaited activity does not succeed.
1142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1143pub enum ActivityFailureKind {
1144    Failed,
1145    Cancelled,
1146    TimedOut,
1147}
1148
1149/// A stable, machine-readable terminal activity failure.
1150///
1151/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1152/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1153#[derive(Clone, Debug, Error, PartialEq)]
1154#[error("activity failed ({reason}): {message}")]
1155pub struct ActivityFailure {
1156    pub kind: ActivityFailureKind,
1157    pub reason: String,
1158    pub message: String,
1159    pub activity_execution_id: Option<String>,
1160    pub activity_attempt_id: Option<String>,
1161    pub activity_type: Option<String>,
1162    pub activity_class: Option<String>,
1163    pub attempt_number: Option<u64>,
1164    pub failure_id: Option<String>,
1165    pub failure_category: Option<String>,
1166    pub timeout_kind: Option<String>,
1167    pub non_retryable: bool,
1168    pub exception_type: Option<String>,
1169    pub exception_class: Option<String>,
1170    pub code: Option<Value>,
1171    pub exception: Option<Value>,
1172}
1173
1174/// Stable terminal categories returned when an awaited child does not succeed.
1175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1176pub enum ChildWorkflowFailureKind {
1177    Failed,
1178    Cancelled,
1179    Terminated,
1180}
1181
1182/// A stable, machine-readable child workflow failure delivered to its parent.
1183///
1184/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1185/// of parsing the display message. Child and parent identifiers retain the
1186/// relationship recorded in durable history across worker restarts.
1187#[derive(Clone, Debug, Error)]
1188#[error("child workflow failed ({reason}): {message}")]
1189pub struct ChildWorkflowFailure {
1190    pub kind: ChildWorkflowFailureKind,
1191    pub reason: String,
1192    pub message: String,
1193    pub parent_workflow_id: Option<String>,
1194    pub parent_workflow_run_id: Option<String>,
1195    pub child_workflow_id: Option<String>,
1196    pub child_workflow_run_id: Option<String>,
1197    pub child_workflow_type: Option<String>,
1198    pub failure_id: Option<String>,
1199    pub failure_category: Option<String>,
1200    pub exception_type: Option<String>,
1201    pub exception_class: Option<String>,
1202    pub non_retryable: bool,
1203    pub code: Option<Value>,
1204    pub exception: Option<Value>,
1205}
1206
1207/// The identity of one durable workflow execution.
1208#[derive(Clone, Debug, PartialEq, Eq)]
1209pub struct WorkflowIdentity {
1210    pub workflow_id: Option<String>,
1211    pub run_id: Option<String>,
1212}
1213
1214/// A successful child result together with its durable parent-child identity.
1215#[derive(Clone, Debug, PartialEq)]
1216pub struct ChildWorkflowResult {
1217    pub parent: WorkflowIdentity,
1218    pub child: WorkflowIdentity,
1219    pub child_workflow_type: Option<String>,
1220    pub result: Value,
1221}
1222
1223/// Lossless successful child result for fixed Avro Value workflows.
1224#[derive(Clone, Debug, PartialEq)]
1225pub struct ChildWorkflowAvroResult {
1226    pub parent: WorkflowIdentity,
1227    pub child: WorkflowIdentity,
1228    pub child_workflow_type: Option<String>,
1229    pub result: AvroValue,
1230}
1231
1232/// Stable user-facing identity for one member of a durable selection group.
1233#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1234#[serde(untagged)]
1235pub enum SelectionKey {
1236    Index(usize),
1237    Name(String),
1238}
1239
1240impl From<usize> for SelectionKey {
1241    fn from(value: usize) -> Self {
1242        Self::Index(value)
1243    }
1244}
1245
1246impl From<String> for SelectionKey {
1247    fn from(value: String) -> Self {
1248        Self::Name(value)
1249    }
1250}
1251
1252impl From<&str> for SelectionKey {
1253    fn from(value: &str) -> Self {
1254        Self::Name(value.to_string())
1255    }
1256}
1257
1258/// Typed result of explicitly awaiting a cancelled non-winning operation.
1259#[derive(Clone, Debug, Error, PartialEq, Eq)]
1260#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1261pub struct DurableOperationCancelled {
1262    pub selection_group_id: String,
1263    pub member_key: SelectionKey,
1264    pub member_index: usize,
1265    pub operation_kind: String,
1266    pub operation_identity: String,
1267}
1268
1269/// Stable identity for one enclosing deterministic parallel group.
1270///
1271/// The same fields are attached to every ordinary activity, timer, or child
1272/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1273/// no Rust-specific wire command is introduced.
1274#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1275pub struct ParallelGroupMetadata {
1276    pub parallel_group_id: String,
1277    pub parallel_group_kind: String,
1278    pub parallel_group_base_sequence: u64,
1279    pub parallel_group_size: usize,
1280    pub parallel_group_index: usize,
1281    #[serde(default, skip_serializing_if = "Option::is_none")]
1282    pub parallel_group_mode: Option<String>,
1283    #[serde(default, skip_serializing_if = "Option::is_none")]
1284    pub selection_member_key: Option<SelectionKey>,
1285    #[serde(default, skip_serializing_if = "Option::is_none")]
1286    pub selection_member_index: Option<usize>,
1287    #[serde(default, skip_serializing_if = "Option::is_none")]
1288    pub selection_member_base_sequence: Option<u64>,
1289    #[serde(default, skip_serializing_if = "Option::is_none")]
1290    pub selection_member_size: Option<usize>,
1291    #[serde(default, skip_serializing_if = "Option::is_none")]
1292    pub selection_member_kind: Option<String>,
1293}
1294
1295/// One input-ordered result returned by [`WorkflowContext::parallel`].
1296#[derive(Clone, Debug, PartialEq)]
1297pub enum ParallelResult {
1298    Activity(Value),
1299    ChildWorkflow(ChildWorkflowResult),
1300    Timer,
1301    Signal(Vec<Value>),
1302    Condition(ConditionWaitResult),
1303    Group(Vec<ParallelResult>),
1304}
1305
1306/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1307#[derive(Clone, Debug, PartialEq)]
1308pub enum ParallelAvroResult {
1309    Activity(AvroValue),
1310    ChildWorkflow(ChildWorkflowAvroResult),
1311    Timer,
1312    Signal(Vec<AvroValue>),
1313    Condition(ConditionWaitResult),
1314    Group(Vec<ParallelAvroResult>),
1315}
1316
1317impl ParallelAvroResult {
1318    fn into_json_result(self) -> Result<ParallelResult> {
1319        match self {
1320            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1321            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1322                parent: result.parent,
1323                child: result.child,
1324                child_workflow_type: result.child_workflow_type,
1325                result: result.result.into_json()?,
1326            })),
1327            Self::Timer => Ok(ParallelResult::Timer),
1328            Self::Signal(values) => Ok(ParallelResult::Signal(
1329                values
1330                    .into_iter()
1331                    .map(AvroValue::into_json)
1332                    .collect::<Result<Vec<_>>>()?,
1333            )),
1334            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1335            Self::Group(results) => Ok(ParallelResult::Group(
1336                results
1337                    .into_iter()
1338                    .map(Self::into_json_result)
1339                    .collect::<Result<Vec<_>>>()?,
1340            )),
1341        }
1342    }
1343}
1344
1345/// One successful leaf retained when another parallel member failed.
1346#[derive(Clone, Debug, PartialEq)]
1347pub struct ParallelCompletion {
1348    pub member_path: Vec<usize>,
1349    pub result: ParallelResult,
1350}
1351
1352/// A deterministic join failed after some siblings had already completed.
1353///
1354/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1355/// error. `completed` is declaration ordered and contains only durable
1356/// successes observed in the same replay. Late sibling completions can add
1357/// entries on a later replay without changing `member_path` or the selected
1358/// positional failure.
1359#[derive(Debug, Error)]
1360#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1361pub struct ParallelFailure {
1362    pub group_id: String,
1363    pub member_path: Vec<usize>,
1364    pub group_path: Vec<ParallelGroupMetadata>,
1365    pub completed: Vec<ParallelCompletion>,
1366    #[source]
1367    pub cause: Box<Error>,
1368}
1369
1370/// Stable validation error returned before an invalid group emits commands.
1371#[derive(Clone, Debug, Error, PartialEq, Eq)]
1372#[error("invalid deterministic parallel group ({reason}): {message}")]
1373pub struct ParallelGroupError {
1374    pub reason: &'static str,
1375    pub member_path: Vec<usize>,
1376    pub message: String,
1377}
1378
1379/// Cooperative workflow cancellation observed at an author-controlled point.
1380#[derive(Clone, Debug, Error, PartialEq, Eq)]
1381#[error("workflow cancellation was requested")]
1382pub struct WorkflowCancellationRequested;
1383
1384/// A forward saga failure followed by a terminal compensation failure.
1385#[derive(Debug, Error)]
1386#[error(
1387    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1388)]
1389pub struct SagaCompensationFailure {
1390    pub initiating_failure: Box<Error>,
1391    pub compensation_failure: Box<Error>,
1392    pub compensation_activity_type: String,
1393    pub compensation_registration_order: usize,
1394}
1395
1396/// Server behavior when a parent closes while its child is still open.
1397#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1398pub enum ParentClosePolicy {
1399    #[default]
1400    Abandon,
1401    /// Legacy terminal cancellation without cooperative cleanup.
1402    RequestCancel,
1403    /// Request cooperative cleanup with the original lineage and deadline.
1404    RequestCancellation,
1405    Terminate,
1406}
1407
1408impl ParentClosePolicy {
1409    fn as_str(self) -> &'static str {
1410        match self {
1411            Self::Abandon => "abandon",
1412            Self::RequestCancel => "request_cancel",
1413            Self::RequestCancellation => "request_cancellation",
1414            Self::Terminate => "terminate",
1415        }
1416    }
1417}
1418
1419/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1420#[non_exhaustive]
1421#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1422pub enum CancellationPolicy {
1423    /// Request cancellation and continue without waiting. Historical Activity default.
1424    TryCancel,
1425    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1426    WaitCancellationCompleted,
1427    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1428    #[default]
1429    Abandon,
1430}
1431
1432impl CancellationPolicy {
1433    fn as_str(self) -> &'static str {
1434        match self {
1435            Self::TryCancel => "try_cancel",
1436            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1437            Self::Abandon => "abandon",
1438        }
1439    }
1440}
1441
1442/// Durable retry policy for one child workflow invocation.
1443#[derive(Clone, Debug, Default, PartialEq, Eq)]
1444pub struct ChildWorkflowRetryPolicy {
1445    pub max_attempts: Option<u32>,
1446    pub backoff_seconds: Vec<u64>,
1447    pub non_retryable_error_types: Vec<String>,
1448}
1449
1450/// Options recorded with a child-workflow command.
1451///
1452/// The task queue is mandatory so routing is explicit and replay-stable.
1453#[derive(Clone, Debug, PartialEq, Eq)]
1454pub struct ChildWorkflowOptions {
1455    pub task_queue: String,
1456    pub parent_close_policy: ParentClosePolicy,
1457    pub cancellation_policy: CancellationPolicy,
1458    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1459    pub execution_timeout_seconds: Option<u64>,
1460    pub run_timeout_seconds: Option<u64>,
1461}
1462
1463impl ChildWorkflowOptions {
1464    pub fn new(task_queue: impl Into<String>) -> Self {
1465        Self {
1466            task_queue: task_queue.into(),
1467            parent_close_policy: ParentClosePolicy::Abandon,
1468            cancellation_policy: CancellationPolicy::Abandon,
1469            retry_policy: None,
1470            execution_timeout_seconds: None,
1471            run_timeout_seconds: None,
1472        }
1473    }
1474
1475    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1476        self.parent_close_policy = policy;
1477        self
1478    }
1479
1480    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1481        self.cancellation_policy = policy;
1482        self
1483    }
1484
1485    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1486        self.retry_policy = Some(policy);
1487        self
1488    }
1489
1490    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1491        self.execution_timeout_seconds = Some(seconds);
1492        self
1493    }
1494
1495    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1496        self.run_timeout_seconds = Some(seconds);
1497        self
1498    }
1499}
1500
1501/// Backoff intervals for one durable activity retry policy.
1502#[derive(Clone, Debug, PartialEq, Eq)]
1503pub enum ActivityBackoff {
1504    /// Use these intervals between attempts. The server repeats the final
1505    /// interval if the retry budget contains more attempts than entries.
1506    /// All entries are retained, including those beyond the retry budget.
1507    Explicit(Vec<Duration>),
1508    /// Generate one interval for every retry using integer exponential growth.
1509    Exponential {
1510        initial_interval: Duration,
1511        coefficient: u32,
1512        maximum_interval: Option<Duration>,
1513    },
1514}
1515
1516/// Durable server-side retry policy for one activity execution.
1517#[derive(Clone, Debug, Default, PartialEq, Eq)]
1518pub struct ActivityRetryPolicy {
1519    pub max_attempts: Option<u32>,
1520    pub backoff: Option<ActivityBackoff>,
1521    pub non_retryable_error_types: Vec<String>,
1522}
1523
1524impl ActivityRetryPolicy {
1525    /// Start a policy with a finite attempt budget, including the first attempt.
1526    pub fn new(max_attempts: u32) -> Self {
1527        Self {
1528            max_attempts: Some(max_attempts),
1529            ..Self::default()
1530        }
1531    }
1532
1533    /// Preserve the complete explicit list independently of the attempt budget.
1534    /// Unused entries remain part of the policy compared during replay.
1535    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1536        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1537        self
1538    }
1539
1540    pub fn exponential_backoff(
1541        mut self,
1542        initial_interval: Duration,
1543        coefficient: u32,
1544        maximum_interval: Option<Duration>,
1545    ) -> Self {
1546        self.backoff = Some(ActivityBackoff::Exponential {
1547            initial_interval,
1548            coefficient,
1549            maximum_interval,
1550        });
1551        self
1552    }
1553
1554    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1555        self.non_retryable_error_types.push(error_type.into());
1556        self
1557    }
1558
1559    pub fn non_retryable_error_types(
1560        mut self,
1561        error_types: impl IntoIterator<Item = impl Into<String>>,
1562    ) -> Self {
1563        self.non_retryable_error_types
1564            .extend(error_types.into_iter().map(Into::into));
1565        self
1566    }
1567}
1568
1569/// Options recorded atomically on one deterministic `schedule_activity` command.
1570///
1571/// Durations are rounded up to whole seconds when encoded, so the server never
1572/// receives a shorter timeout or backoff than the caller requested.
1573#[derive(Clone, Debug, Default, PartialEq, Eq)]
1574pub struct ActivityOptions {
1575    pub task_queue: Option<String>,
1576    pub retry_policy: Option<ActivityRetryPolicy>,
1577    pub start_to_close_timeout: Option<Duration>,
1578    pub schedule_to_start_timeout: Option<Duration>,
1579    pub schedule_to_close_timeout: Option<Duration>,
1580    pub heartbeat_timeout: Option<Duration>,
1581    pub cancellation_policy: Option<CancellationPolicy>,
1582}
1583
1584impl ActivityOptions {
1585    pub fn new() -> Self {
1586        Self::default()
1587    }
1588
1589    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1590        self.task_queue = Some(task_queue.into());
1591        self
1592    }
1593
1594    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1595        self.retry_policy = Some(policy);
1596        self
1597    }
1598
1599    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1600        self.start_to_close_timeout = Some(timeout);
1601        self
1602    }
1603
1604    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1605        self.schedule_to_start_timeout = Some(timeout);
1606        self
1607    }
1608
1609    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1610        self.schedule_to_close_timeout = Some(timeout);
1611        self
1612    }
1613
1614    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1615        self.heartbeat_timeout = Some(timeout);
1616        self
1617    }
1618
1619    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1620        self.cancellation_policy = Some(policy);
1621        self
1622    }
1623
1624    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1625        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1626            && self.schedule_to_close_timeout.is_none()
1627        {
1628            return Err(ActivityOptionsError::new(
1629                ActivityOptionsErrorKind::MissingTotalTimeout,
1630                Some("schedule_to_close_timeout"),
1631                "remote Activity Abandon requires a finite positive total timeout",
1632            ));
1633        }
1634        if self
1635            .task_queue
1636            .as_deref()
1637            .is_some_and(|queue| queue.trim().is_empty())
1638        {
1639            return Err(ActivityOptionsError::new(
1640                ActivityOptionsErrorKind::EmptyTaskQueue,
1641                Some("task_queue"),
1642                "task_queue must not be empty",
1643            ));
1644        }
1645
1646        for (field, value) in [
1647            ("start_to_close_timeout", self.start_to_close_timeout),
1648            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1649            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1650            ("heartbeat_timeout", self.heartbeat_timeout),
1651        ] {
1652            if value.is_some_and(|value| value.is_zero()) {
1653                return Err(ActivityOptionsError::new(
1654                    ActivityOptionsErrorKind::TimeoutNotPositive,
1655                    Some(field),
1656                    format!("{field} must be positive"),
1657                ));
1658            }
1659        }
1660
1661        validate_timeout_order(
1662            "heartbeat_timeout",
1663            self.heartbeat_timeout,
1664            "start_to_close_timeout",
1665            self.start_to_close_timeout,
1666        )?;
1667        validate_timeout_order(
1668            "start_to_close_timeout",
1669            self.start_to_close_timeout,
1670            "schedule_to_close_timeout",
1671            self.schedule_to_close_timeout,
1672        )?;
1673        validate_timeout_order(
1674            "schedule_to_start_timeout",
1675            self.schedule_to_start_timeout,
1676            "schedule_to_close_timeout",
1677            self.schedule_to_close_timeout,
1678        )?;
1679
1680        Ok(ValidatedActivityOptions {
1681            task_queue: self.task_queue.clone(),
1682            retry_policy: self
1683                .retry_policy
1684                .as_ref()
1685                .map(validate_activity_retry_policy)
1686                .transpose()?,
1687            start_to_close_timeout: timeout_seconds(
1688                "start_to_close_timeout",
1689                self.start_to_close_timeout,
1690            )?,
1691            schedule_to_start_timeout: timeout_seconds(
1692                "schedule_to_start_timeout",
1693                self.schedule_to_start_timeout,
1694            )?,
1695            schedule_to_close_timeout: timeout_seconds(
1696                "schedule_to_close_timeout",
1697                self.schedule_to_close_timeout,
1698            )?,
1699            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1700            cancellation_policy: self.cancellation_policy,
1701        })
1702    }
1703}
1704
1705/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1706///
1707/// Constructors capture arguments but perform no I/O. The join validates the
1708/// complete tree, attaches the existing parallel-group metadata to every
1709/// ordinary command, schedules all leaves, and then suspends.
1710pub enum ParallelOperation {
1711    Activity {
1712        activity_type: String,
1713        options: ActivityOptions,
1714        arguments: Result<AvroValue>,
1715    },
1716    ChildWorkflow {
1717        workflow_type: String,
1718        options: ChildWorkflowOptions,
1719        arguments: Result<AvroValue>,
1720    },
1721    Timer(Duration),
1722    Signal(String),
1723    Condition {
1724        options: ConditionWaitOptions,
1725        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1726    },
1727    Group(Vec<ParallelOperation>),
1728}
1729
1730impl ParallelOperation {
1731    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1732        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1733    }
1734
1735    pub fn activity_with_options<T: Serialize>(
1736        activity_type: impl Into<String>,
1737        options: ActivityOptions,
1738        args: T,
1739    ) -> Self {
1740        Self::Activity {
1741            activity_type: activity_type.into(),
1742            options,
1743            arguments: AvroValue::from_serialize(&args),
1744        }
1745    }
1746
1747    pub fn child_workflow<T: Serialize>(
1748        workflow_type: impl Into<String>,
1749        options: ChildWorkflowOptions,
1750        args: T,
1751    ) -> Self {
1752        Self::ChildWorkflow {
1753            workflow_type: workflow_type.into(),
1754            options,
1755            arguments: AvroValue::from_serialize(&args),
1756        }
1757    }
1758
1759    pub fn timer(duration: Duration) -> Self {
1760        Self::Timer(duration)
1761    }
1762
1763    pub fn signal(signal_name: impl Into<String>) -> Self {
1764        Self::Signal(signal_name.into())
1765    }
1766
1767    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1768    where
1769        F: Fn() -> Result<bool> + Send + 'static,
1770    {
1771        Self::Condition {
1772            options,
1773            predicate: Box::new(predicate),
1774        }
1775    }
1776
1777    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1778        Self::Group(operations)
1779    }
1780}
1781
1782#[derive(Clone, Debug)]
1783struct ValidatedActivityOptions {
1784    task_queue: Option<String>,
1785    retry_policy: Option<Value>,
1786    start_to_close_timeout: Option<u64>,
1787    schedule_to_start_timeout: Option<u64>,
1788    schedule_to_close_timeout: Option<u64>,
1789    heartbeat_timeout: Option<u64>,
1790    cancellation_policy: Option<CancellationPolicy>,
1791}
1792
1793fn validate_timeout_order(
1794    smaller_name: &'static str,
1795    smaller: Option<Duration>,
1796    larger_name: &'static str,
1797    larger: Option<Duration>,
1798) -> std::result::Result<(), ActivityOptionsError> {
1799    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1800        return Err(ActivityOptionsError::new(
1801            ActivityOptionsErrorKind::TimeoutOrder,
1802            Some(smaller_name),
1803            format!("{smaller_name} must be <= {larger_name}"),
1804        ));
1805    }
1806    Ok(())
1807}
1808
1809fn timeout_seconds(
1810    field: &'static str,
1811    value: Option<Duration>,
1812) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1813    value
1814        .map(|value| {
1815            activity_protocol_seconds(value).ok_or_else(|| {
1816                ActivityOptionsError::new(
1817                    ActivityOptionsErrorKind::TimeoutOverflow,
1818                    Some(field),
1819                    format!("{field} is too large for the worker protocol"),
1820                )
1821            })
1822        })
1823        .transpose()
1824}
1825
1826fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1827    value
1828        .as_secs()
1829        .checked_add(u64::from(value.subsec_nanos() > 0))
1830}
1831
1832fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1833    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1834}
1835
1836fn validate_activity_retry_policy(
1837    policy: &ActivityRetryPolicy,
1838) -> std::result::Result<Value, ActivityOptionsError> {
1839    if policy.max_attempts.is_none()
1840        && policy.backoff.is_none()
1841        && policy.non_retryable_error_types.is_empty()
1842    {
1843        return Err(ActivityOptionsError::new(
1844            ActivityOptionsErrorKind::EmptyRetryPolicy,
1845            Some("retry_policy"),
1846            "retry_policy must configure at least one field",
1847        ));
1848    }
1849    if policy.max_attempts == Some(0) {
1850        return Err(ActivityOptionsError::new(
1851            ActivityOptionsErrorKind::InvalidMaxAttempts,
1852            Some("retry_policy.max_attempts"),
1853            "max_attempts must be >= 1",
1854        ));
1855    }
1856    if policy
1857        .non_retryable_error_types
1858        .iter()
1859        .any(|error_type| error_type.trim().is_empty())
1860    {
1861        return Err(ActivityOptionsError::new(
1862            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
1863            Some("retry_policy.non_retryable_error_types"),
1864            "non_retryable_error_types must not contain empty values",
1865        ));
1866    }
1867
1868    let backoff_seconds = match &policy.backoff {
1869        None => None,
1870        Some(backoff) => {
1871            let max_attempts = policy.max_attempts.ok_or_else(|| {
1872                ActivityOptionsError::new(
1873                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
1874                    Some("retry_policy.backoff"),
1875                    "backoff requires max_attempts",
1876                )
1877            })?;
1878            let retry_count = max_attempts.saturating_sub(1) as usize;
1879            let intervals = match backoff {
1880                ActivityBackoff::Explicit(intervals) => intervals.clone(),
1881                ActivityBackoff::Exponential {
1882                    initial_interval,
1883                    coefficient,
1884                    maximum_interval,
1885                } => {
1886                    if *coefficient < 1 {
1887                        return Err(ActivityOptionsError::new(
1888                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
1889                            Some("retry_policy.backoff.coefficient"),
1890                            "backoff coefficient must be >= 1",
1891                        ));
1892                    }
1893                    if retry_count > 10_000 {
1894                        return Err(ActivityOptionsError::new(
1895                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
1896                            Some("retry_policy.max_attempts"),
1897                            "generated backoff supports at most 10000 retry intervals",
1898                        ));
1899                    }
1900                    let mut current = *initial_interval;
1901                    let mut intervals = Vec::with_capacity(retry_count);
1902                    for _ in 0..retry_count {
1903                        let interval = maximum_interval
1904                            .map(|maximum| current.min(maximum))
1905                            .unwrap_or(current);
1906                        intervals.push(interval);
1907                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
1908                            break;
1909                        }
1910                        current = current.checked_mul(*coefficient).ok_or_else(|| {
1911                            ActivityOptionsError::new(
1912                                ActivityOptionsErrorKind::BackoffOverflow,
1913                                Some("retry_policy.backoff"),
1914                                "generated backoff interval overflowed",
1915                            )
1916                        })?;
1917                    }
1918                    intervals
1919                }
1920            };
1921            Some(
1922                intervals
1923                    .into_iter()
1924                    .map(|interval| {
1925                        activity_protocol_seconds(interval).ok_or_else(|| {
1926                            ActivityOptionsError::new(
1927                                ActivityOptionsErrorKind::BackoffOverflow,
1928                                Some("retry_policy.backoff"),
1929                                "backoff interval is too large for the worker protocol",
1930                            )
1931                        })
1932                    })
1933                    .collect::<std::result::Result<Vec<_>, _>>()?,
1934            )
1935        }
1936    };
1937
1938    let mut encoded = serde_json::Map::new();
1939    if let Some(max_attempts) = policy.max_attempts {
1940        encoded.insert("max_attempts".to_string(), json!(max_attempts));
1941    }
1942    if let Some(backoff_seconds) = backoff_seconds {
1943        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
1944    }
1945    if !policy.non_retryable_error_types.is_empty() {
1946        let mut canonical_error_types = Vec::new();
1947        for error_type in policy
1948            .non_retryable_error_types
1949            .iter()
1950            .map(|error_type| error_type.trim())
1951        {
1952            if !canonical_error_types.contains(&error_type) {
1953                canonical_error_types.push(error_type);
1954            }
1955        }
1956        encoded.insert(
1957            "non_retryable_error_types".to_string(),
1958            json!(canonical_error_types),
1959        );
1960    }
1961    Ok(Value::Object(encoded))
1962}
1963
1964/// A stable, machine-readable failure raised when workflow code no longer
1965/// reconstructs the durable command stream recorded in history.
1966#[derive(Clone, Debug, Error)]
1967#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
1968pub struct ReplayFailure {
1969    pub reason: String,
1970    pub sequence: Option<u64>,
1971    pub expected: Option<String>,
1972    pub actual: Option<String>,
1973    pub message: String,
1974}
1975
1976impl ReplayFailure {
1977    fn new(
1978        reason: impl Into<String>,
1979        sequence: Option<u64>,
1980        expected: Option<String>,
1981        actual: Option<String>,
1982        message: impl Into<String>,
1983    ) -> Self {
1984        Self {
1985            reason: reason.into(),
1986            sequence,
1987            expected,
1988            actual,
1989            message: message.into(),
1990        }
1991    }
1992}
1993
1994/// A stable, machine-readable workflow query or query-task settlement failure.
1995#[derive(Clone, Debug, Error)]
1996#[error("query failed ({reason}, HTTP {status}): {message}")]
1997pub struct QueryFailure {
1998    pub status: u16,
1999    pub reason: String,
2000    pub message: String,
2001    pub body: Value,
2002}
2003
2004/// A stable failure returned when a server rejects an SDK protocol version.
2005#[derive(Clone, Debug, Error)]
2006#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
2007pub struct ProtocolFailure {
2008    pub status: u16,
2009    pub reason: String,
2010    pub message: String,
2011    pub supported_version: Option<String>,
2012    pub requested_version: Option<String>,
2013    pub body: Value,
2014}
2015
2016#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2017pub struct PayloadEnvelope {
2018    pub codec: String,
2019    pub blob: String,
2020}
2021
2022impl PayloadEnvelope {
2023    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2024        encode_payload(value, DEFAULT_CODEC)
2025    }
2026
2027    /// Encode an explicit typed value, including the bytes branch that JSON
2028    /// serialization cannot represent.
2029    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2030        encode_avro_value(value)
2031    }
2032}
2033
2034/// Native adapter for the fixed language-neutral Avro Value schema.
2035#[derive(Clone, Debug)]
2036pub enum AvroValue {
2037    Null,
2038    Boolean(bool),
2039    Long(i64),
2040    Double(f64),
2041    Bytes(Vec<u8>),
2042    String(String),
2043    Array(Vec<AvroValue>),
2044    Map(BTreeMap<String, AvroValue>),
2045}
2046
2047impl PartialEq for AvroValue {
2048    fn eq(&self, other: &Self) -> bool {
2049        match (self, other) {
2050            (Self::Null, Self::Null) => true,
2051            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2052            (Self::Long(left), Self::Long(right)) => left == right,
2053            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2054            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2055            (Self::String(left), Self::String(right)) => left == right,
2056            (Self::Array(left), Self::Array(right)) => left == right,
2057            (Self::Map(left), Self::Map(right)) => left == right,
2058            _ => false,
2059        }
2060    }
2061}
2062
2063impl AvroValue {
2064    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2065        Self::from_serde_value(
2066            serde_value::to_value(value).map_err(|error| {
2067                Error::Codec(format!("could not adapt value for Avro: {error}"))
2068            })?,
2069        )
2070    }
2071
2072    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2073        use serde_value::Value as SerdeValue;
2074
2075        match value {
2076            SerdeValue::Unit => Ok(Self::Null),
2077            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2078            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2079            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2080            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2081            SerdeValue::I64(value) => Ok(Self::Long(value)),
2082            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2083            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2084            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2085            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2086                Error::Codec(
2087                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2088                        .to_string(),
2089                )
2090            }),
2091            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2092            SerdeValue::F64(value) => Self::finite_double(value),
2093            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2094            SerdeValue::String(value) => Ok(Self::String(value)),
2095            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2096            SerdeValue::Option(None) => Ok(Self::Null),
2097            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2098                Self::from_serde_value(*value)
2099            }
2100            SerdeValue::Seq(values) => values
2101                .into_iter()
2102                .map(Self::from_serde_value)
2103                .collect::<Result<Vec<_>>>()
2104                .map(Self::Array),
2105            SerdeValue::Map(values) => values
2106                .into_iter()
2107                .map(|(key, value)| {
2108                    let SerdeValue::String(key) = key else {
2109                        return Err(Error::Codec(
2110                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2111                        ));
2112                    };
2113
2114                    Ok((key, Self::from_serde_value(value)?))
2115                })
2116                .collect::<Result<BTreeMap<_, _>>>()
2117                .map(Self::Map),
2118        }
2119    }
2120
2121    fn finite_double(value: f64) -> Result<Self> {
2122        if !value.is_finite() {
2123            return Err(Error::Codec(
2124                "non_finite_float: Avro Value doubles must be finite".to_string(),
2125            ));
2126        }
2127
2128        Ok(Self::Double(value))
2129    }
2130
2131    fn into_json(self) -> Result<Value> {
2132        match self {
2133            Self::Null => Ok(Value::Null),
2134            Self::Boolean(value) => Ok(Value::Bool(value)),
2135            Self::Long(value) => Ok(Value::Number(value.into())),
2136            Self::Double(value) => serde_json::Number::from_f64(value)
2137                .map(Value::Number)
2138                .ok_or_else(|| {
2139                    Error::Codec(
2140                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2141                    )
2142                }),
2143            Self::Bytes(value) => Ok(json!({
2144                "$type": "bytes",
2145                "base64": BASE64.encode(value),
2146            })),
2147            Self::String(value) => Ok(Value::String(value)),
2148            Self::Array(values) => values
2149                .into_iter()
2150                .map(Self::into_json)
2151                .collect::<Result<Vec<_>>>()
2152                .map(Value::Array),
2153            Self::Map(values) => values
2154                .into_iter()
2155                .map(|(key, value)| Ok((key, value.into_json()?)))
2156                .collect::<Result<serde_json::Map<_, _>>>()
2157                .map(Value::Object),
2158        }
2159    }
2160
2161    fn into_serde_value(self) -> serde_value::Value {
2162        use serde_value::Value as SerdeValue;
2163
2164        match self {
2165            Self::Null => SerdeValue::Unit,
2166            Self::Boolean(value) => SerdeValue::Bool(value),
2167            Self::Long(value) => SerdeValue::I64(value),
2168            Self::Double(value) => SerdeValue::F64(value),
2169            Self::Bytes(value) => SerdeValue::Bytes(value),
2170            Self::String(value) => SerdeValue::String(value),
2171            Self::Array(values) => {
2172                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2173            }
2174            Self::Map(values) => SerdeValue::Map(
2175                values
2176                    .into_iter()
2177                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2178                    .collect(),
2179            ),
2180        }
2181    }
2182
2183    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2184        self.into_serde_value().deserialize_into().map_err(|error| {
2185            Error::Codec(format!(
2186                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2187            ))
2188        })
2189    }
2190}
2191
2192impl Serialize for AvroValue {
2193    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2194    where
2195        S: Serializer,
2196    {
2197        match self {
2198            Self::Null => serializer.serialize_unit(),
2199            Self::Boolean(value) => serializer.serialize_bool(*value),
2200            Self::Long(value) => serializer.serialize_i64(*value),
2201            Self::Double(value) => serializer.serialize_f64(*value),
2202            Self::Bytes(value) => serializer.serialize_bytes(value),
2203            Self::String(value) => serializer.serialize_str(value),
2204            Self::Array(values) => {
2205                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2206                for value in values {
2207                    sequence.serialize_element(value)?;
2208                }
2209                sequence.end()
2210            }
2211            Self::Map(values) => {
2212                let mut map = serializer.serialize_map(Some(values.len()))?;
2213                for (key, value) in values {
2214                    map.serialize_entry(key, value)?;
2215                }
2216                map.end()
2217            }
2218        }
2219    }
2220}
2221
2222pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2223    let datum = avro_value_to_datum(value)?;
2224    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2225        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2226    let mut bytes = Vec::with_capacity(datum.len() + 10);
2227    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2228    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2229    bytes.extend_from_slice(&datum);
2230    Ok(PayloadEnvelope {
2231        codec: DEFAULT_CODEC.to_string(),
2232        blob: BASE64.encode(bytes),
2233    })
2234}
2235
2236pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2237    if envelope.codec != DEFAULT_CODEC {
2238        return Err(unsupported_payload_codec(&envelope.codec));
2239    }
2240    decode_avro_value_blob(&envelope.blob)
2241}
2242
2243pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2244    let blob = match codec {
2245        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2246        other => return Err(unsupported_payload_codec(other)),
2247    };
2248
2249    Ok(PayloadEnvelope {
2250        codec: codec.to_string(),
2251        blob,
2252    })
2253}
2254
2255pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2256    match envelope.codec.as_str() {
2257        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2258        other => Err(unsupported_payload_codec(other)),
2259    }
2260}
2261
2262fn handler_type_error<T>(
2263    handler_kind: HandlerKind,
2264    handler_name: &str,
2265    value_kind: HandlerValueKind,
2266    message: impl Into<String>,
2267) -> Error {
2268    Error::HandlerType {
2269        handler_kind,
2270        handler_name: handler_name.to_string(),
2271        value_kind,
2272        rust_type: type_name::<T>(),
2273        message: message.into(),
2274    }
2275}
2276
2277fn decode_handler_input<T: DeserializeOwned>(
2278    arguments: AvroValue,
2279    handler_kind: HandlerKind,
2280    handler_name: &str,
2281) -> Result<T> {
2282    let argument = match arguments {
2283        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2284            arguments.pop().expect("one typed handler argument")
2285        }
2286        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2287        AvroValue::Array(arguments) => {
2288            return Err(handler_type_error::<T>(
2289                handler_kind,
2290                handler_name,
2291                HandlerValueKind::Input,
2292                format!(
2293                    "typed handlers accept one request value, but the task carried {} arguments",
2294                    arguments.len()
2295                ),
2296            ));
2297        }
2298        argument => argument,
2299    };
2300
2301    argument.deserialize().map_err(|error| {
2302        handler_type_error::<T>(
2303            handler_kind,
2304            handler_name,
2305            HandlerValueKind::Input,
2306            error.to_string(),
2307        )
2308    })
2309}
2310
2311fn decode_workflow_entry<T: DeserializeOwned>(
2312    arguments: AvroValue,
2313    workflow_type: &str,
2314) -> Result<T> {
2315    decode_handler_input(arguments, HandlerKind::Workflow, workflow_type).map_err(|_| {
2316        // Serde errors may contain recorded values. The entry refusal exposes
2317        // only the registered workflow and expected Rust type.
2318        handler_type_error::<T>(
2319            HandlerKind::Workflow,
2320            workflow_type,
2321            HandlerValueKind::Input,
2322            "workflow_entry_arguments_mismatch: restore compatible entry code before retrying the original task",
2323        )
2324    })
2325}
2326
2327fn encode_handler_result<T: Serialize>(
2328    result: &T,
2329    handler_kind: HandlerKind,
2330    handler_name: &str,
2331) -> Result<AvroValue> {
2332    AvroValue::from_serialize(result).map_err(|error| {
2333        handler_type_error::<T>(
2334            handler_kind,
2335            handler_name,
2336            HandlerValueKind::Result,
2337            error.to_string(),
2338        )
2339    })
2340}
2341
2342fn decode_handler_result<T: DeserializeOwned>(
2343    result: AvroValue,
2344    handler_kind: HandlerKind,
2345    handler_name: &str,
2346) -> Result<T> {
2347    result.deserialize().map_err(|error| {
2348        handler_type_error::<T>(
2349            handler_kind,
2350            handler_name,
2351            HandlerValueKind::Result,
2352            error.to_string(),
2353        )
2354    })
2355}
2356
2357#[cfg(test)]
2358fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2359    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2360}
2361
2362fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2363    validate_payload_codec(fallback_codec)?;
2364
2365    if value.is_null() {
2366        return Ok(Value::Null);
2367    }
2368
2369    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2370        return decode_blob(blob, codec);
2371    }
2372
2373    if let Some(blob) = value.as_str() {
2374        return decode_blob(blob, fallback_codec);
2375    }
2376
2377    Err(untagged_payload_value())
2378}
2379
2380fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2381    let envelope = match codec {
2382        DEFAULT_CODEC => encode_avro_value(value)?,
2383        other => return Err(unsupported_payload_codec(other)),
2384    };
2385    Ok(serde_json::to_value(envelope)?)
2386}
2387
2388fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2389    validate_payload_codec(fallback_codec)?;
2390
2391    if value.is_null() {
2392        return Ok(AvroValue::Null);
2393    }
2394
2395    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2396        validate_payload_codec(codec)?;
2397        return decode_avro_value_blob(blob);
2398    }
2399
2400    if let Some(blob) = value.as_str() {
2401        return match fallback_codec {
2402            DEFAULT_CODEC => decode_avro_value_blob(blob),
2403            other => Err(unsupported_payload_codec(other)),
2404        };
2405    }
2406
2407    Err(untagged_payload_value())
2408}
2409
2410fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2411    match value {
2412        AvroValue::Null => AvroValue::Array(Vec::new()),
2413        AvroValue::Array(_) => value,
2414        other => AvroValue::Array(vec![other]),
2415    }
2416}
2417
2418fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2419    match codec {
2420        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2421        other => Err(unsupported_payload_codec(other)),
2422    }
2423}
2424
2425fn validate_payload_codec(codec: &str) -> Result<()> {
2426    match codec {
2427        DEFAULT_CODEC => Ok(()),
2428        MISSING_TASK_PAYLOAD_CODEC => {
2429            Err(invalid_task_payload_codec("task payload_codec is missing"))
2430        }
2431        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2432        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2433            "task payload_codec must be a string",
2434        )),
2435        other => Err(unsupported_payload_codec(other)),
2436    }
2437}
2438
2439fn invalid_task_payload_codec(reason: &str) -> Error {
2440    Error::Codec(format!(
2441        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2442    ))
2443}
2444
2445fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2446    let Some(object) = value.as_object() else {
2447        return Ok(None);
2448    };
2449    if !object.contains_key("codec") && !object.contains_key("blob") {
2450        return Ok(None);
2451    }
2452
2453    let codec = object
2454        .get("codec")
2455        .and_then(Value::as_str)
2456        .ok_or_else(invalid_payload_envelope)?;
2457    validate_payload_codec(codec)?;
2458    let blob = object
2459        .get("blob")
2460        .and_then(Value::as_str)
2461        .ok_or_else(invalid_payload_envelope)?;
2462    Ok(Some((codec, blob)))
2463}
2464
2465fn invalid_payload_envelope() -> Error {
2466    Error::Codec(
2467        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2468            .to_string(),
2469    )
2470}
2471
2472fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2473    for command in commands {
2474        let Some(command) = command.as_object() else {
2475            continue;
2476        };
2477        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2478            continue;
2479        };
2480        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2481            continue;
2482        };
2483
2484        if let Some(codec) = command.get("payload_codec") {
2485            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2486            validate_payload_codec(codec)?;
2487        }
2488
2489        let payload = command
2490            .get(payload_field)
2491            .ok_or_else(invalid_payload_envelope)?;
2492        if runtime_payloads::Reference::parse(payload)?.is_none() {
2493            validate_outbound_payload_envelope(payload)?;
2494        }
2495    }
2496    Ok(())
2497}
2498
2499fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2500    if commands.iter().any(|command| {
2501        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2502            && command
2503                .get("condition_wait_occurrence_id")
2504                .and_then(Value::as_str)
2505                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2506    }) {
2507        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2508    } else if commands.iter().any(|command| {
2509        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2510            && command.get("attribute_types").is_some()
2511    }) {
2512        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2513    } else if commands
2514        .iter()
2515        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2516    {
2517        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2518    } else if commands
2519        .iter()
2520        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2521    {
2522        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2523    } else if commands.iter().any(|command| {
2524        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2525    }) {
2526        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2527    } else {
2528        MINIMUM_WORKER_PROTOCOL_VERSION
2529    }
2530}
2531
2532fn workflow_completion_protocol_version_with_message_streams(
2533    commands: &[Value],
2534    has_message_stream_metadata: bool,
2535) -> &'static str {
2536    let command_protocol = workflow_completion_protocol_version(commands);
2537    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2538        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2539    } else {
2540        command_protocol
2541    }
2542}
2543
2544fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2545    match command_type {
2546        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2547        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2548        "start_service_operation" => Some("request_payload"),
2549        "upsert_memo" => Some("entries"),
2550        _ => None,
2551    }
2552}
2553
2554fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2555    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2556        return Err(untagged_payload_value());
2557    };
2558    validate_payload_codec(codec)?;
2559    decode_avro_value_blob(blob)?;
2560    Ok(())
2561}
2562
2563fn unsupported_payload_codec(codec: &str) -> Error {
2564    Error::Codec(format!(
2565        "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"
2566    ))
2567}
2568
2569fn untagged_payload_value() -> Error {
2570    Error::Codec(
2571        "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"
2572            .to_string(),
2573    )
2574}
2575
2576fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2577    let bytes = BASE64.decode(blob).map_err(|err| {
2578        Error::Codec(format!(
2579            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2580        ))
2581    })?;
2582
2583    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2584        return Err(unsupported_payload_codec("json"));
2585    }
2586
2587    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2588        return Err(Error::Codec(
2589            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2590        ));
2591    }
2592
2593    let fingerprint: [u8; 8] = bytes[2..10]
2594        .try_into()
2595        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2596    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2597        return Err(Error::Codec(format!(
2598            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2599            fingerprint
2600                .iter()
2601                .map(|byte| format!("{byte:02x}"))
2602                .collect::<String>()
2603        )));
2604    }
2605
2606    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2607    // The current fingerprint selects the current immutable schema, so reader
2608    // resolution would only re-walk the same recursive union. Future retained
2609    // writer fingerprints supply a distinct reader schema in this branch.
2610    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2611    if datum_reader.truncated {
2612        return Err(Error::Codec(
2613            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2614        ));
2615    }
2616    let datum = datum.map_err(|err| {
2617        Error::Codec(format!(
2618            "invalid_payload_framing: malformed Avro Value datum: {err}"
2619        ))
2620    })?;
2621    if datum_reader.remaining() != 0 {
2622        return Err(Error::Codec(format!(
2623            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2624            datum_reader.remaining()
2625        )));
2626    }
2627    avro_value_from_datum(datum)
2628}
2629
2630struct StrictAvroDatumReader<'a> {
2631    bytes: &'a [u8],
2632    offset: usize,
2633    truncated: bool,
2634}
2635
2636impl<'a> StrictAvroDatumReader<'a> {
2637    fn new(bytes: &'a [u8]) -> Self {
2638        Self {
2639            bytes,
2640            offset: 0,
2641            truncated: false,
2642        }
2643    }
2644
2645    fn remaining(&self) -> usize {
2646        self.bytes.len() - self.offset
2647    }
2648}
2649
2650impl Read for StrictAvroDatumReader<'_> {
2651    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2652        let count = buffer.len().min(self.remaining());
2653        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2654        self.offset += count;
2655        if count < buffer.len() {
2656            self.truncated = true;
2657        }
2658
2659        Ok(count)
2660    }
2661}
2662
2663fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2664    let branch = match value {
2665        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2666        AvroValue::Boolean(value) => AvroDatum::Union(
2667            1,
2668            Box::new(AvroDatum::Record(vec![(
2669                "boolean".to_string(),
2670                AvroDatum::Boolean(*value),
2671            )])),
2672        ),
2673        AvroValue::Long(value) => AvroDatum::Union(
2674            2,
2675            Box::new(AvroDatum::Record(vec![(
2676                "long".to_string(),
2677                AvroDatum::Long(*value),
2678            )])),
2679        ),
2680        AvroValue::Double(value) => {
2681            if !value.is_finite() {
2682                return Err(Error::Codec(
2683                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2684                ));
2685            }
2686            AvroDatum::Union(
2687                3,
2688                Box::new(AvroDatum::Record(vec![(
2689                    "double".to_string(),
2690                    AvroDatum::Double(*value),
2691                )])),
2692            )
2693        }
2694        AvroValue::Bytes(value) => AvroDatum::Union(
2695            4,
2696            Box::new(AvroDatum::Record(vec![(
2697                "bytes".to_string(),
2698                AvroDatum::Bytes(value.clone()),
2699            )])),
2700        ),
2701        AvroValue::String(value) => AvroDatum::Union(
2702            5,
2703            Box::new(AvroDatum::Record(vec![(
2704                "string".to_string(),
2705                AvroDatum::String(value.clone()),
2706            )])),
2707        ),
2708        AvroValue::Array(values) => AvroDatum::Union(
2709            6,
2710            Box::new(AvroDatum::Record(vec![(
2711                "items".to_string(),
2712                AvroDatum::Array(
2713                    values
2714                        .iter()
2715                        .map(avro_value_to_datum)
2716                        .collect::<Result<Vec<_>>>()?,
2717                ),
2718            )])),
2719        ),
2720        AvroValue::Map(values) => AvroDatum::Union(
2721            7,
2722            Box::new(AvroDatum::Record(vec![(
2723                "entries".to_string(),
2724                AvroDatum::Array(
2725                    values
2726                        .iter()
2727                        .map(|(key, value)| {
2728                            Ok(AvroDatum::Record(vec![
2729                                ("key".to_string(), AvroDatum::String(key.clone())),
2730                                ("value".to_string(), avro_value_to_datum(value)?),
2731                            ]))
2732                        })
2733                        .collect::<Result<Vec<_>>>()?,
2734                ),
2735            )])),
2736        ),
2737    };
2738    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2739}
2740
2741fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2742    let AvroDatum::Record(mut outer) = datum else {
2743        return Err(Error::Codec(
2744            "invalid_payload_framing: datum is not a Value record".to_string(),
2745        ));
2746    };
2747    let (_, branch) = outer
2748        .pop()
2749        .filter(|(name, _)| name == "value")
2750        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2751    let AvroDatum::Union(_, branch) = branch else {
2752        return Err(Error::Codec(
2753            "invalid_payload_framing: invalid Value union".to_string(),
2754        ));
2755    };
2756    match *branch {
2757        AvroDatum::Null => Ok(AvroValue::Null),
2758        AvroDatum::Record(mut fields) => {
2759            let (name, value) = fields.pop().ok_or_else(|| {
2760                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2761            })?;
2762            match (name.as_str(), value) {
2763                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2764                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2765                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2766                    Ok(AvroValue::Double(value))
2767                }
2768                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2769                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2770                ("items", AvroDatum::Array(values)) => values
2771                    .into_iter()
2772                    .map(avro_value_from_datum)
2773                    .collect::<Result<Vec<_>>>()
2774                    .map(AvroValue::Array),
2775                ("entries", AvroDatum::Map(values)) => values
2776                    .into_iter()
2777                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2778                    .collect::<Result<BTreeMap<_, _>>>()
2779                    .map(AvroValue::Map),
2780                _ => Err(Error::Codec(
2781                    "invalid_payload_framing: unknown Value branch".to_string(),
2782                )),
2783            }
2784        }
2785        _ => Err(Error::Codec(
2786            "invalid_payload_framing: invalid Value branch".to_string(),
2787        )),
2788    }
2789}
2790
2791fn avro_value_schema() -> Result<&'static Schema> {
2792    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2793        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2794            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2795    }) {
2796        Ok(schema) => Ok(schema),
2797        Err(message) => Err(Error::Codec(message.clone())),
2798    }
2799}
2800
2801fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2802    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2803        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2804        // have the same block representation when each ordered array record
2805        // contains the map key followed by its value, so this encoding-only
2806        // adaptation lets the official encoder retain BTreeMap wire order.
2807        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2808            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2809        let entries_schema = schema
2810            .pointer_mut("/fields/0/type/7/fields/0/type")
2811            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2812        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2813            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2814        }
2815        *entries_schema = json!({
2816            "type": "array",
2817            "items": {
2818                "type": "record",
2819                "name": "MapEntry",
2820                "fields": [
2821                    {"name": "key", "type": "string"},
2822                    {"name": "value", "type": "Value"}
2823                ]
2824            }
2825        });
2826        Schema::parse_str(&schema.to_string())
2827            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2828    }) {
2829        Ok(schema) => Ok(schema),
2830        Err(message) => Err(Error::Codec(message.clone())),
2831    }
2832}
2833
2834#[derive(Clone, Debug)]
2835pub struct Client {
2836    http: reqwest::Client,
2837    hydration_timeout: Duration,
2838    base_url: String,
2839    token: Option<String>,
2840    control_token: Option<String>,
2841    worker_token: Option<String>,
2842    namespace: String,
2843    max_external_payload_bytes: usize,
2844    worker_storage_admission: Option<WorkerStorageAdmission>,
2845    cooperative_worker_protocol: bool,
2846    worker_protocol_version: WorkerProtocolVersion,
2847    local_activities_enabled: bool,
2848    worker_sessions_enabled: bool,
2849    max_concurrent_worker_sessions: usize,
2850    worker_build_id: Option<String>,
2851    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2852    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2853}
2854
2855impl Client {
2856    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2857        Self::builder(base_url).build()
2858    }
2859
2860    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2861        ClientBuilder {
2862            base_url: base_url.into(),
2863            token: None,
2864            control_token: None,
2865            worker_token: None,
2866            namespace: "default".to_string(),
2867            timeout: Duration::from_secs(60),
2868            max_external_payload_bytes: 64 * 1024 * 1024,
2869            worker_protocol_version: WorkerProtocolVersion::default(),
2870        }
2871    }
2872
2873    pub async fn health(&self) -> Result<Value> {
2874        self.request_json(
2875            reqwest::Method::GET,
2876            "/health",
2877            RequestProtocol::ControlPlane,
2878            Option::<&Value>::None,
2879        )
2880        .await
2881    }
2882
2883    pub async fn cluster_info(&self) -> Result<Value> {
2884        self.request_json(
2885            reqwest::Method::GET,
2886            "/cluster/info",
2887            RequestProtocol::ControlPlane,
2888            Option::<&Value>::None,
2889        )
2890        .await
2891    }
2892
2893    pub async fn start_workflow<T: Serialize>(
2894        &self,
2895        workflow_type: &str,
2896        task_queue: &str,
2897        workflow_id: &str,
2898        input: T,
2899    ) -> Result<WorkflowHandle> {
2900        self.start_workflow_with_options(
2901            workflow_type,
2902            task_queue,
2903            workflow_id,
2904            WorkflowStartOptions::default(),
2905            input,
2906        )
2907        .await
2908    }
2909
2910    /// Start a workflow with explicit server-enforced execution and run
2911    /// deadlines.
2912    pub async fn start_workflow_with_options<T: Serialize>(
2913        &self,
2914        workflow_type: &str,
2915        task_queue: &str,
2916        workflow_id: &str,
2917        options: WorkflowStartOptions,
2918        input: T,
2919    ) -> Result<WorkflowHandle> {
2920        options.validate()?;
2921        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2922        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2923        let body = json!({
2924            "workflow_id": workflow_id,
2925            "workflow_type": workflow_type,
2926            "task_queue": task_queue,
2927            "input": input_envelope,
2928            "execution_timeout_seconds": options.execution_timeout_seconds,
2929            "run_timeout_seconds": options.run_timeout_seconds
2930        });
2931
2932        let data: Value = self
2933            .request_json(
2934                reqwest::Method::POST,
2935                "/workflows",
2936                RequestProtocol::ControlPlane,
2937                Some(&body),
2938            )
2939            .await?;
2940
2941        Ok(WorkflowHandle {
2942            client: self.clone(),
2943            workflow_id: data
2944                .get("workflow_id")
2945                .and_then(Value::as_str)
2946                .unwrap_or(workflow_id)
2947                .to_string(),
2948            run_id: data
2949                .get("run_id")
2950                .and_then(Value::as_str)
2951                .map(str::to_string),
2952            workflow_type: data
2953                .get("workflow_type")
2954                .and_then(Value::as_str)
2955                .unwrap_or(workflow_type)
2956                .to_string(),
2957        })
2958    }
2959
2960    pub async fn signal_workflow<T: Serialize>(
2961        &self,
2962        workflow_id: &str,
2963        signal_name: &str,
2964        input: T,
2965    ) -> Result<Value> {
2966        self.signal_workflow_target(workflow_id, None, signal_name, input)
2967            .await
2968    }
2969
2970    /// Append one idempotently identified item to an instance-scoped input stream.
2971    pub async fn append_message_stream<T: Serialize>(
2972        &self,
2973        workflow_id: &str,
2974        stream_name: &str,
2975        message_id: &str,
2976        input: T,
2977    ) -> Result<Value> {
2978        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2979        let body = json!({
2980            "message_id": message_id,
2981            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2982        });
2983        self.request_json(
2984            reqwest::Method::POST,
2985            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2986            RequestProtocol::ControlPlane,
2987            Some(&body),
2988        )
2989        .await
2990    }
2991
2992    /// Signal only if `run_id` is still the current run for this instance.
2993    pub async fn signal_workflow_run<T: Serialize>(
2994        &self,
2995        workflow_id: &str,
2996        run_id: &str,
2997        signal_name: &str,
2998        input: T,
2999    ) -> Result<Value> {
3000        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
3001            .await
3002    }
3003
3004    async fn signal_workflow_target<T: Serialize>(
3005        &self,
3006        workflow_id: &str,
3007        run_id: Option<&str>,
3008        signal_name: &str,
3009        input: T,
3010    ) -> Result<Value> {
3011        validate_user_signal_name(signal_name)?;
3012        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3013        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3014        let body = json!({
3015            "input": input_envelope
3016        });
3017        let path = match run_id {
3018            Some(run_id) => {
3019                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
3020            }
3021            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
3022        };
3023        self.request_json(
3024            reqwest::Method::POST,
3025            &path,
3026            RequestProtocol::ControlPlane,
3027            Some(&body),
3028        )
3029        .await
3030    }
3031
3032    /// Close the current run as cancelled immediately.
3033    ///
3034    /// Server revokes open tasks and timers without resuming workflow code for
3035    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3036    /// request on a supporting runtime and opted-in worker.
3037    pub async fn cancel_workflow(
3038        &self,
3039        workflow_id: &str,
3040        options: WorkflowCommandOptions,
3041    ) -> Result<WorkflowCommandResult> {
3042        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3043            .await
3044    }
3045
3046    /// Close the selected run as cancelled, only if `run_id` is still current.
3047    pub async fn cancel_workflow_run(
3048        &self,
3049        workflow_id: &str,
3050        run_id: &str,
3051        options: WorkflowCommandOptions,
3052    ) -> Result<WorkflowCommandResult> {
3053        self.workflow_command(
3054            workflow_id,
3055            Some(run_id),
3056            WorkflowCommandKind::Cancel,
3057            options,
3058        )
3059        .await
3060    }
3061
3062    /// Forcefully terminate the current run for an instance.
3063    pub async fn terminate_workflow(
3064        &self,
3065        workflow_id: &str,
3066        options: WorkflowCommandOptions,
3067    ) -> Result<WorkflowCommandResult> {
3068        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3069            .await
3070    }
3071
3072    /// Forcefully terminate only if `run_id` is still current.
3073    pub async fn terminate_workflow_run(
3074        &self,
3075        workflow_id: &str,
3076        run_id: &str,
3077        options: WorkflowCommandOptions,
3078    ) -> Result<WorkflowCommandResult> {
3079        self.workflow_command(
3080            workflow_id,
3081            Some(run_id),
3082            WorkflowCommandKind::Terminate,
3083            options,
3084        )
3085        .await
3086    }
3087
3088    /// Continue a failed run from its recorded activity failure boundary.
3089    pub async fn redrive_workflow_run(
3090        &self,
3091        workflow_id: &str,
3092        failed_run_id: &str,
3093        request_id: Option<&str>,
3094    ) -> Result<WorkflowRedriveResult> {
3095        let body = request_id
3096            .map(|id| json!({"request_id": id}))
3097            .unwrap_or_else(|| json!({}));
3098        let data: Value = self
3099            .request_json(
3100                reqwest::Method::POST,
3101                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3102                RequestProtocol::ControlPlane,
3103                Some(&body),
3104            )
3105            .await?;
3106        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3107            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3108        {
3109            return Err(Error::Codec(
3110                "redrive response was not accepted".to_string(),
3111            ));
3112        }
3113        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3114            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3115        {
3116            return Err(Error::Codec(
3117                "redrive response does not match the requested source run".to_string(),
3118            ));
3119        }
3120        let run_id = data
3121            .get("run_id")
3122            .and_then(Value::as_str)
3123            .filter(|id| !id.is_empty() && *id != failed_run_id)
3124            .ok_or_else(|| {
3125                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3126            })?;
3127        let resume_step_sequence = data
3128            .get("resume_step_sequence")
3129            .and_then(Value::as_u64)
3130            .filter(|sequence| *sequence > 0)
3131            .ok_or_else(|| {
3132                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3133            })?;
3134        Ok(WorkflowRedriveResult {
3135            workflow_id: workflow_id.to_string(),
3136            source_run_id: failed_run_id.to_string(),
3137            run_id: run_id.to_string(),
3138            resume_step_sequence,
3139            raw: data,
3140        })
3141    }
3142
3143    async fn workflow_command(
3144        &self,
3145        workflow_id: &str,
3146        run_id: Option<&str>,
3147        command: WorkflowCommandKind,
3148        options: WorkflowCommandOptions,
3149    ) -> Result<WorkflowCommandResult> {
3150        let path = match run_id {
3151            Some(run_id) => format!(
3152                "/workflows/{workflow_id}/runs/{run_id}/{}",
3153                command.as_str()
3154            ),
3155            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3156        };
3157        let data = match self
3158            .request_json(
3159                reqwest::Method::POST,
3160                &path,
3161                RequestProtocol::ControlPlane,
3162                Some(&options),
3163            )
3164            .await
3165        {
3166            Ok(data) => data,
3167            Err(Error::Http { status, body }) => {
3168                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3169                    command,
3170                    status,
3171                    body,
3172                    workflow_id,
3173                    run_id,
3174                )));
3175            }
3176            Err(error) => return Err(error),
3177        };
3178
3179        Ok(workflow_command_result(command, data, workflow_id, run_id))
3180    }
3181
3182    /// Execute a named, read-only query against a running or completed workflow.
3183    ///
3184    /// Arguments and results use the platform payload envelope. Server and
3185    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3186    /// reason, HTTP status, and original response body.
3187    pub async fn query_workflow<T: Serialize>(
3188        &self,
3189        workflow_id: &str,
3190        query_name: &str,
3191        input: T,
3192    ) -> Result<Value> {
3193        self.query_workflow_target(workflow_id, None, query_name, input)
3194            .await
3195    }
3196
3197    /// Query only if `run_id` is still current, preventing accidental retargeting.
3198    pub async fn query_workflow_run<T: Serialize>(
3199        &self,
3200        workflow_id: &str,
3201        run_id: &str,
3202        query_name: &str,
3203        input: T,
3204    ) -> Result<Value> {
3205        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3206            .await
3207    }
3208
3209    /// Query a workflow and return the lossless fixed Avro Value result.
3210    pub async fn query_workflow_avro_value<T: Serialize>(
3211        &self,
3212        workflow_id: &str,
3213        query_name: &str,
3214        input: T,
3215    ) -> Result<AvroValue> {
3216        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3217            .await
3218    }
3219
3220    /// Query a selected run and return the lossless fixed Avro Value result.
3221    pub async fn query_workflow_run_avro_value<T: Serialize>(
3222        &self,
3223        workflow_id: &str,
3224        run_id: &str,
3225        query_name: &str,
3226        input: T,
3227    ) -> Result<AvroValue> {
3228        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3229            .await
3230    }
3231
3232    async fn query_workflow_avro_value_target<T: Serialize>(
3233        &self,
3234        workflow_id: &str,
3235        run_id: Option<&str>,
3236        query_name: &str,
3237        input: T,
3238    ) -> Result<AvroValue> {
3239        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3240        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3241        let path = match run_id {
3242            Some(run_id) => {
3243                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3244            }
3245            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3246        };
3247        let response: Value = match self
3248            .request_json(
3249                reqwest::Method::POST,
3250                &path,
3251                RequestProtocol::ControlPlane,
3252                Some(&body),
3253            )
3254            .await
3255        {
3256            Ok(response) => response,
3257            Err(Error::Http { status, body }) => {
3258                return Err(Error::QueryFailed(query_failure(status, body)));
3259            }
3260            Err(error) => return Err(error),
3261        };
3262
3263        let envelope = response
3264            .get("result_envelope")
3265            .filter(|envelope| !envelope.is_null())
3266            .ok_or_else(|| {
3267                Error::Codec(
3268                    "missing_payload_envelope: typed query result requires result_envelope"
3269                        .to_string(),
3270                )
3271            })?;
3272        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3273    }
3274
3275    async fn query_workflow_target<T: Serialize>(
3276        &self,
3277        workflow_id: &str,
3278        run_id: Option<&str>,
3279        query_name: &str,
3280        input: T,
3281    ) -> Result<Value> {
3282        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3283        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3284        let body = json!({
3285            "input": input_envelope
3286        });
3287        let path = match run_id {
3288            Some(run_id) => {
3289                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3290            }
3291            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3292        };
3293        let response: Value = match self
3294            .request_json(
3295                reqwest::Method::POST,
3296                &path,
3297                RequestProtocol::ControlPlane,
3298                Some(&body),
3299            )
3300            .await
3301        {
3302            Ok(response) => response,
3303            Err(Error::Http { status, body }) => {
3304                return Err(Error::QueryFailed(query_failure(status, body)));
3305            }
3306            Err(error) => return Err(error),
3307        };
3308
3309        if let Some(envelope) = response
3310            .get("result_envelope")
3311            .filter(|envelope| !envelope.is_null())
3312        {
3313            return decode_wire_value(envelope, DEFAULT_CODEC);
3314        }
3315
3316        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3317    }
3318
3319    /// Send a synchronous update using fixed Avro Value arguments.
3320    pub async fn update_workflow<T: Serialize>(
3321        &self,
3322        workflow_id: &str,
3323        update_name: &str,
3324        input: T,
3325        request_id: Option<&str>,
3326    ) -> Result<Value> {
3327        let response = self
3328            .update_workflow_response(workflow_id, update_name, input, request_id)
3329            .await?;
3330        if let Some(envelope) = response
3331            .get("result_envelope")
3332            .filter(|envelope| !envelope.is_null())
3333        {
3334            return decode_wire_value(envelope, DEFAULT_CODEC);
3335        }
3336        Ok(response.get("result").cloned().unwrap_or(response))
3337    }
3338
3339    /// Send a synchronous update and retain a bytes-capable Avro result.
3340    pub async fn update_workflow_avro_value<T: Serialize>(
3341        &self,
3342        workflow_id: &str,
3343        update_name: &str,
3344        input: T,
3345        request_id: Option<&str>,
3346    ) -> Result<AvroValue> {
3347        let response = self
3348            .update_workflow_response(workflow_id, update_name, input, request_id)
3349            .await?;
3350        let envelope = response
3351            .get("result_envelope")
3352            .filter(|envelope| !envelope.is_null())
3353            .ok_or_else(|| {
3354                Error::Codec(
3355                    "missing_payload_envelope: typed update result requires result_envelope"
3356                        .to_string(),
3357                )
3358            })?;
3359        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3360    }
3361
3362    async fn update_workflow_response<T: Serialize>(
3363        &self,
3364        workflow_id: &str,
3365        update_name: &str,
3366        input: T,
3367        request_id: Option<&str>,
3368    ) -> Result<Value> {
3369        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3370        let mut body = json!({
3371            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3372            "wait_for": "completed",
3373        });
3374        if let Some(request_id) = request_id {
3375            body["request_id"] = json!(request_id);
3376        }
3377        self.request_json(
3378            reqwest::Method::POST,
3379            &format!("/workflows/{workflow_id}/update/{update_name}"),
3380            RequestProtocol::ControlPlane,
3381            Some(&body),
3382        )
3383        .await
3384    }
3385
3386    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3387        let path = format!("/workflows/{workflow_id}");
3388        let mut data: WorkflowDescription = self
3389            .request_json(
3390                reqwest::Method::GET,
3391                &path,
3392                RequestProtocol::ControlPlane,
3393                Option::<&Value>::None,
3394            )
3395            .await?;
3396        data.decode_payloads()?;
3397        Ok(data)
3398    }
3399
3400    /// Describe one selected run, including historical terminal runs.
3401    pub async fn describe_workflow_run(
3402        &self,
3403        workflow_id: &str,
3404        run_id: &str,
3405    ) -> Result<WorkflowDescription> {
3406        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3407        let mut data: WorkflowDescription = self
3408            .request_json(
3409                reqwest::Method::GET,
3410                &path,
3411                RequestProtocol::ControlPlane,
3412                Option::<&Value>::None,
3413            )
3414            .await?;
3415        data.decode_payloads()?;
3416        Ok(data)
3417    }
3418
3419    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3420        let mut path = format!(
3421            "/workflows/{}/runs/{}/streams",
3422            percent_encode_path_segment(workflow_id),
3423            percent_encode_path_segment(run_id),
3424        );
3425        if let Some(stream_name) = stream_name {
3426            path.push('/');
3427            path.push_str(&percent_encode_path_segment(stream_name));
3428        }
3429        path
3430    }
3431
3432    /// List the run-scoped output streams already opened by a workflow.
3433    pub async fn list_workflow_streams(
3434        &self,
3435        workflow_id: &str,
3436        run_id: &str,
3437    ) -> Result<Vec<WorkflowStreamDescription>> {
3438        let response: WorkflowStreamListResponse = self
3439            .request_json(
3440                reqwest::Method::GET,
3441                &Self::workflow_stream_path(workflow_id, run_id, None),
3442                RequestProtocol::ControlPlane,
3443                Option::<&Value>::None,
3444            )
3445            .await?;
3446        Ok(response.streams)
3447    }
3448
3449    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3450    pub async fn describe_workflow_stream(
3451        &self,
3452        workflow_id: &str,
3453        run_id: &str,
3454        stream_name: &str,
3455    ) -> Result<WorkflowStreamDescription> {
3456        let response: WorkflowStreamDescriptionResponse = self
3457            .request_json(
3458                reqwest::Method::GET,
3459                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3460                RequestProtocol::ControlPlane,
3461                Option::<&Value>::None,
3462            )
3463            .await?;
3464        Ok(response.stream)
3465    }
3466
3467    /// Read one bounded page beginning at a zero-based offset.
3468    ///
3469    /// Delivery is at least once: persist `next_offset` only after processing
3470    /// the page. The future is cancellation-safe; dropping it cancels the
3471    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3472    /// service contract.
3473    pub async fn subscribe_workflow_stream(
3474        &self,
3475        workflow_id: &str,
3476        run_id: &str,
3477        stream_name: &str,
3478        from_offset: u64,
3479        max_items: usize,
3480        wait: Duration,
3481    ) -> Result<WorkflowStreamPage> {
3482        let max_items = max_items.clamp(1, 500);
3483        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3484        let path = format!(
3485            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3486            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3487        );
3488        let response: WorkflowStreamPageResponse = self
3489            .request_json_with_timeout(
3490                reqwest::Method::GET,
3491                &path,
3492                RequestProtocol::ControlPlane,
3493                Option::<&Value>::None,
3494                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3495            )
3496            .await?;
3497
3498        let items = response
3499            .items
3500            .into_iter()
3501            .map(|raw| {
3502                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3503                let envelope = raw.get("payload").cloned();
3504                let payload = envelope
3505                    .as_ref()
3506                    .filter(|value| value.get("blob").is_some())
3507                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3508                    .transpose()?
3509                    .map(AvroValue::into_json)
3510                    .transpose()?;
3511                Ok(WorkflowStreamItem {
3512                    offset,
3513                    payload,
3514                    payload_envelope: envelope,
3515                    payload_reference: raw
3516                        .get("payload_reference")
3517                        .and_then(Value::as_str)
3518                        .map(str::to_string),
3519                    payload_codec: raw
3520                        .get("payload_codec")
3521                        .and_then(Value::as_str)
3522                        .map(str::to_string),
3523                    idempotency_key: raw
3524                        .get("idempotency_key")
3525                        .and_then(Value::as_str)
3526                        .map(str::to_string),
3527                    item_type: raw
3528                        .get("item_type")
3529                        .and_then(Value::as_str)
3530                        .map(str::to_string),
3531                    content_type: raw
3532                        .get("content_type")
3533                        .and_then(Value::as_str)
3534                        .map(str::to_string),
3535                    origin: raw
3536                        .get("origin")
3537                        .and_then(Value::as_str)
3538                        .map(str::to_string),
3539                    origin_reference: raw
3540                        .get("origin_reference")
3541                        .and_then(Value::as_str)
3542                        .map(str::to_string),
3543                    emitted_at: raw
3544                        .get("emitted_at")
3545                        .and_then(Value::as_str)
3546                        .map(str::to_string),
3547                    raw,
3548                })
3549            })
3550            .collect::<Result<Vec<_>>>()?;
3551        Ok(WorkflowStreamPage {
3552            stream: response.stream,
3553            items,
3554            next_offset: response.next_offset,
3555            terminal: response.terminal,
3556        })
3557    }
3558
3559    /// Append inline Avro envelopes or opaque external payload references.
3560    pub async fn append_workflow_stream(
3561        &self,
3562        workflow_id: &str,
3563        run_id: &str,
3564        stream_name: &str,
3565        items: &[WorkflowStreamAppendItem],
3566        max_pending_items: Option<u64>,
3567    ) -> Result<WorkflowStreamAppendResult> {
3568        if items.is_empty() {
3569            return Err(Error::Codec(
3570                "workflow_stream_items_empty: append requires at least one item".to_string(),
3571            ));
3572        }
3573        let mut body = json!({
3574            "items": items
3575                .iter()
3576                .map(|item| item.wire_value(None))
3577                .collect::<Vec<_>>(),
3578        });
3579        if let Some(max_pending_items) = max_pending_items {
3580            if max_pending_items == 0 {
3581                return Err(Error::Codec(
3582                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3583                        .to_string(),
3584                ));
3585            }
3586            body["max_pending_items"] = json!(max_pending_items);
3587        }
3588        let response: WorkflowStreamAppendResponse = self
3589            .request_json(
3590                reqwest::Method::POST,
3591                &format!(
3592                    "{}/items",
3593                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3594                ),
3595                RequestProtocol::ControlPlane,
3596                Some(&body),
3597            )
3598            .await?;
3599        Ok(WorkflowStreamAppendResult {
3600            stream: response.stream,
3601            accepted_offsets: response.accepted_offsets,
3602            accepted: response.accepted,
3603            deduped: response.deduped,
3604        })
3605    }
3606
3607    /// Close a stream, or mark it errored when `error_reason` is supplied.
3608    pub async fn close_workflow_stream(
3609        &self,
3610        workflow_id: &str,
3611        run_id: &str,
3612        stream_name: &str,
3613        error_reason: Option<&str>,
3614        retention_seconds: Option<u64>,
3615    ) -> Result<WorkflowStreamDescription> {
3616        let mut body = json!({});
3617        if let Some(error_reason) = error_reason {
3618            body["error_reason"] = json!(error_reason);
3619        }
3620        if let Some(retention_seconds) = retention_seconds {
3621            if retention_seconds == 0 {
3622                return Err(Error::Codec(
3623                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3624                        .to_string(),
3625                ));
3626            }
3627            body["retention_seconds"] = json!(retention_seconds);
3628        }
3629        let response: WorkflowStreamDescriptionResponse = self
3630            .request_json(
3631                reqwest::Method::POST,
3632                &format!(
3633                    "{}/close",
3634                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3635                ),
3636                RequestProtocol::ControlPlane,
3637                Some(&body),
3638            )
3639            .await?;
3640        Ok(response.stream)
3641    }
3642
3643    pub async fn register_worker(
3644        &self,
3645        worker_id: &str,
3646        task_queue: &str,
3647        supported_workflow_types: Vec<String>,
3648        supported_activity_types: Vec<String>,
3649        max_concurrent_workflow_tasks: usize,
3650        max_concurrent_activity_tasks: usize,
3651    ) -> Result<RegisterWorkerResponse> {
3652        self.register_worker_with_capabilities(
3653            worker_id,
3654            task_queue,
3655            supported_workflow_types,
3656            supported_activity_types,
3657            max_concurrent_workflow_tasks,
3658            max_concurrent_activity_tasks,
3659            Vec::new(),
3660        )
3661        .await
3662    }
3663
3664    /// Register a worker and explicitly advertise additive worker capabilities.
3665    pub async fn register_worker_with_capabilities(
3666        &self,
3667        worker_id: &str,
3668        task_queue: &str,
3669        supported_workflow_types: Vec<String>,
3670        supported_activity_types: Vec<String>,
3671        max_concurrent_workflow_tasks: usize,
3672        max_concurrent_activity_tasks: usize,
3673        capabilities: Vec<String>,
3674    ) -> Result<RegisterWorkerResponse> {
3675        self.register_worker_with_command_contracts(
3676            worker_id,
3677            task_queue,
3678            supported_workflow_types,
3679            supported_activity_types,
3680            max_concurrent_workflow_tasks,
3681            max_concurrent_activity_tasks,
3682            capabilities,
3683            Value::Object(serde_json::Map::new()),
3684        )
3685        .await
3686    }
3687
3688    /// Register a worker and advertise its named query and update handlers.
3689    ///
3690    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3691    /// so a workflow contract with a non-empty or malformed
3692    /// `update_validators` declaration returns
3693    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3694    #[allow(clippy::too_many_arguments)]
3695    pub async fn register_worker_with_command_contracts(
3696        &self,
3697        worker_id: &str,
3698        task_queue: &str,
3699        supported_workflow_types: Vec<String>,
3700        supported_activity_types: Vec<String>,
3701        max_concurrent_workflow_tasks: usize,
3702        max_concurrent_activity_tasks: usize,
3703        capabilities: Vec<String>,
3704        workflow_command_contracts: Value,
3705    ) -> Result<RegisterWorkerResponse> {
3706        self.register_worker_with_definition_fingerprints(
3707            worker_id,
3708            task_queue,
3709            supported_workflow_types,
3710            supported_activity_types,
3711            max_concurrent_workflow_tasks,
3712            max_concurrent_activity_tasks,
3713            capabilities,
3714            workflow_command_contracts,
3715            None,
3716        )
3717        .await
3718    }
3719
3720    #[allow(clippy::too_many_arguments)]
3721    async fn register_worker_with_definition_fingerprints(
3722        &self,
3723        worker_id: &str,
3724        task_queue: &str,
3725        supported_workflow_types: Vec<String>,
3726        supported_activity_types: Vec<String>,
3727        max_concurrent_workflow_tasks: usize,
3728        max_concurrent_activity_tasks: usize,
3729        capabilities: Vec<String>,
3730        workflow_command_contracts: Value,
3731        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3732    ) -> Result<RegisterWorkerResponse> {
3733        if let Some(contracts) = workflow_command_contracts.as_object() {
3734            for (workflow_type, contract) in contracts {
3735                let Some(update_validators) = contract.get("update_validators") else {
3736                    continue;
3737                };
3738                if !update_validators
3739                    .as_array()
3740                    .is_some_and(|validators| validators.is_empty())
3741                {
3742                    return Err(Error::UnsupportedUpdateValidators {
3743                        workflow_type: workflow_type.clone(),
3744                    });
3745                }
3746            }
3747        }
3748
3749        let mut body = json!({
3750            "worker_id": worker_id,
3751            "task_queue": task_queue,
3752            "runtime": "rust",
3753            "sdk_version": SDK_VERSION,
3754            "supported_workflow_types": supported_workflow_types,
3755            "supported_activity_types": supported_activity_types,
3756            "capabilities": capabilities,
3757            "capability_manifest": portable_worker_affinity_capability_manifest(),
3758            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3759            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3760        });
3761        if capabilities
3762            .iter()
3763            .any(|capability| capability == "nexus_cooperative_cancellation")
3764        {
3765            body["capability_manifest"]["nexus_cooperative_cancellation"] = json!({
3766                "supported":true, "minimum_protocol_version":"1.20",
3767                "implementation":"owned_workflow_run_canonical_delivery", "binding_kinds":["workflow_run"],
3768            });
3769        }
3770        if let Some(build_id) = &self.worker_build_id {
3771            if build_id.is_empty() || build_id.len() > 255 {
3772                return Err(Error::WorkerLoop(
3773                    "worker build ID must contain 1 to 255 bytes".into(),
3774                ));
3775            }
3776            body["build_id"] = json!(build_id);
3777        }
3778        if self.sticky_cache.is_some() {
3779            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
3780                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
3781                "implementation":"bounded_durable_history_cache"});
3782        }
3783        if self.local_activities_enabled {
3784            body["capability_manifest"]["local_activities"] = json!({"supported":true,
3785                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3786        }
3787        if self.worker_sessions_enabled {
3788            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
3789                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3790            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
3791        }
3792        if workflow_command_contracts
3793            .as_object()
3794            .is_some_and(|contracts| !contracts.is_empty())
3795        {
3796            body["workflow_command_contracts"] = workflow_command_contracts;
3797        }
3798        if let Some(fingerprints) = workflow_definition_fingerprints {
3799            body["workflow_definition_fingerprints"] = json!(fingerprints);
3800        }
3801
3802        let response: Value = self
3803            .request_json(
3804                reqwest::Method::POST,
3805                "/worker/register",
3806                RequestProtocol::DefaultWorker,
3807                Some(&body),
3808            )
3809            .await?;
3810        if self.sticky_cache.is_some() {
3811            self.confirm_sticky_registration(&response, worker_id, task_queue)
3812                .await?;
3813        }
3814        if self.local_activities_enabled || self.worker_sessions_enabled {
3815            let compatible = response["registered"].as_bool() == Some(true)
3816                && response["worker_id"].as_str() == Some(worker_id)
3817                && response["namespace"].as_str() == Some(self.namespace.as_str())
3818                && response["task_queue"].as_str() == Some(task_queue)
3819                && response["protocol_version"]
3820                    .as_str()
3821                    .and_then(|version| version.strip_prefix("1."))
3822                    .and_then(|minor| minor.parse::<u64>().ok())
3823                    .is_some_and(|minor| minor >= 18)
3824                && (!self.local_activities_enabled
3825                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
3826                        == Some(true))
3827                && (!self.worker_sessions_enabled
3828                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
3829                        == Some(true)
3830                        && response["capabilities"].as_array().is_some_and(|accepted| {
3831                            capabilities.iter().all(|capability| {
3832                                accepted
3833                                    .iter()
3834                                    .any(|value| value.as_str() == Some(capability.as_str()))
3835                            })
3836                        })));
3837            if !compatible {
3838                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
3839                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
3840                } else {
3841                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
3842                });
3843                if response["registered"] == true
3844                    && response["worker_id"].as_str() == Some(worker_id)
3845                {
3846                    if let Err(deregistration) =
3847                        self.deregister_worker_registration(worker_id).await
3848                    {
3849                        return Err(Error::WorkerShutdown {
3850                            primary: Box::new(error),
3851                            deregistration: Box::new(deregistration),
3852                        });
3853                    }
3854                }
3855                return Err(error);
3856            }
3857        }
3858        if self.cooperative_worker_protocol {
3859            let compatible = response["registered"].as_bool() == Some(true)
3860                && response["worker_id"].as_str() == Some(worker_id)
3861                && response["namespace"].as_str() == Some(self.namespace.as_str())
3862                && response["task_queue"].as_str() == Some(task_queue)
3863                && response["protocol_version"]
3864                    .as_str()
3865                    .is_some_and(cooperative_cancellation::supports_protocol)
3866                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
3867                    == Some(true)
3868                && (!capabilities
3869                    .iter()
3870                    .any(|capability| capability == "nexus_cooperative_cancellation")
3871                    || nexus::installed_cooperation(&response["server_capabilities"]))
3872                && response["capabilities"].as_array().is_some_and(|accepted| {
3873                    capabilities.iter().all(|capability| {
3874                        accepted
3875                            .iter()
3876                            .any(|value| value.as_str() == Some(capability.as_str()))
3877                    })
3878                });
3879            if !compatible {
3880                let error = Error::CooperativeCancellationUnavailable(
3881                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3882                );
3883                if response["registered"].as_bool() == Some(true)
3884                    && response["worker_id"].as_str() == Some(worker_id)
3885                {
3886                    if let Err(deregistration) =
3887                        self.deregister_worker_registration(worker_id).await
3888                    {
3889                        return Err(Error::WorkerShutdown {
3890                            primary: Box::new(error),
3891                            deregistration: Box::new(deregistration),
3892                        });
3893                    }
3894                }
3895                return Err(error);
3896            }
3897        }
3898        Ok(serde_json::from_value(response)?)
3899    }
3900
3901    /// Gracefully remove one worker's registration through the worker plane.
3902    ///
3903    /// This operation is separate from operator-facing worker management. It
3904    /// uses worker-protocol authentication and returns the server's lease
3905    /// recovery result.
3906    pub async fn deregister_worker_registration(
3907        &self,
3908        worker_id: &str,
3909    ) -> Result<WorkerDeregistrationEnvelope> {
3910        let path = format!(
3911            "/worker/registrations/{}",
3912            percent_encode_path_segment(worker_id)
3913        );
3914        self.request_json(
3915            reqwest::Method::DELETE,
3916            &path,
3917            RequestProtocol::DefaultWorker,
3918            Option::<&Value>::None,
3919        )
3920        .await
3921    }
3922
3923    /// Long-poll for an ephemeral, read-only workflow query task.
3924    pub async fn poll_query_task(
3925        &self,
3926        worker_id: &str,
3927        task_queue: &str,
3928        timeout: Duration,
3929    ) -> Result<Option<QueryTask>> {
3930        Ok(self
3931            .poll_query_task_response(worker_id, task_queue, timeout)
3932            .await?
3933            .task)
3934    }
3935
3936    /// Poll a query task while preserving server stop and drain metadata.
3937    pub async fn poll_query_task_response(
3938        &self,
3939        worker_id: &str,
3940        task_queue: &str,
3941        timeout: Duration,
3942    ) -> Result<PollQueryTaskResponse> {
3943        let poll_request_id = unique_request_id("rust-query-poll");
3944        self.poll_query_task_response_with_request_id(
3945            worker_id,
3946            task_queue,
3947            timeout,
3948            &poll_request_id,
3949            1,
3950        )
3951        .await
3952    }
3953
3954    async fn poll_query_task_response_with_request_id(
3955        &self,
3956        worker_id: &str,
3957        task_queue: &str,
3958        timeout: Duration,
3959        poll_request_id: &str,
3960        transport_retries: usize,
3961    ) -> Result<PollQueryTaskResponse> {
3962        let timeout_seconds = long_poll_timeout_seconds(timeout);
3963        let body = json!({
3964            "worker_id": worker_id,
3965            "task_queue": task_queue,
3966            "poll_request_id": poll_request_id,
3967            "timeout_seconds": timeout_seconds,
3968        });
3969        self.poll_request_json(
3970            "/worker/query-tasks/poll",
3971            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3972            &body,
3973            timeout + Duration::from_secs(5),
3974            transport_retries,
3975        )
3976        .await
3977    }
3978
3979    /// Complete a query task without appending workflow history.
3980    pub async fn complete_query_task<T: Serialize>(
3981        &self,
3982        query_task_id: &str,
3983        lease_owner: &str,
3984        query_task_attempt: u64,
3985        result: T,
3986        codec: &str,
3987    ) -> Result<Value> {
3988        let typed_result = AvroValue::from_serialize(&result)?;
3989        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3990        self.complete_query_task_with_envelope(
3991            query_task_id,
3992            lease_owner,
3993            query_task_attempt,
3994            typed_result.into_json()?,
3995            result_envelope,
3996        )
3997        .await
3998    }
3999
4000    async fn complete_query_task_with_envelope(
4001        &self,
4002        query_task_id: &str,
4003        lease_owner: &str,
4004        query_task_attempt: u64,
4005        result: Value,
4006        result_envelope: Value,
4007    ) -> Result<Value> {
4008        let body = json!({
4009            "lease_owner": lease_owner,
4010            "query_task_attempt": query_task_attempt,
4011            "result": result,
4012            "result_envelope": result_envelope,
4013        });
4014        let path = format!("/worker/query-tasks/{query_task_id}/complete");
4015        let response = self
4016            .request_json(
4017                reqwest::Method::POST,
4018                &path,
4019                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4020                Some(&body),
4021            )
4022            .await;
4023        query_task_response(response)
4024    }
4025
4026    /// Report a stable machine-readable query-task failure.
4027    pub async fn fail_query_task(
4028        &self,
4029        query_task_id: &str,
4030        lease_owner: &str,
4031        query_task_attempt: u64,
4032        message: impl Into<String>,
4033        reason: impl Into<String>,
4034        failure_type: impl Into<String>,
4035    ) -> Result<Value> {
4036        let body = json!({
4037            "lease_owner": lease_owner,
4038            "query_task_attempt": query_task_attempt,
4039            "failure": {
4040                "message": message.into(),
4041                "reason": reason.into(),
4042                "type": failure_type.into(),
4043            }
4044        });
4045        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4046        let response = self
4047            .request_json(
4048                reqwest::Method::POST,
4049                &path,
4050                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4051                Some(&body),
4052            )
4053            .await;
4054        query_task_response(response)
4055    }
4056
4057    pub async fn heartbeat_worker(
4058        &self,
4059        worker_id: &str,
4060        workflow_available: usize,
4061        activity_available: usize,
4062    ) -> Result<Value> {
4063        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4064            .await
4065    }
4066
4067    async fn heartbeat_worker_with_sessions(
4068        &self,
4069        worker_id: &str,
4070        workflow_available: usize,
4071        activity_available: usize,
4072        session_available: Option<usize>,
4073    ) -> Result<Value> {
4074        let mut body = json!({
4075            "worker_id": worker_id,
4076            "task_slots": {
4077                "workflow_available": workflow_available,
4078                "activity_available": activity_available
4079            },
4080            "process_metrics": {
4081                "process_id": std::process::id(),
4082                "process_uptime_seconds": 0
4083            }
4084        });
4085
4086        if let Some(available) = session_available {
4087            body["task_slots"]["session_available"] = json!(available);
4088        }
4089
4090        self.request_json(
4091            reqwest::Method::POST,
4092            "/worker/heartbeat",
4093            RequestProtocol::DefaultWorker,
4094            Some(&body),
4095        )
4096        .await
4097    }
4098
4099    pub async fn poll_workflow_task(
4100        &self,
4101        worker_id: &str,
4102        task_queue: &str,
4103        timeout: Duration,
4104    ) -> Result<Option<WorkflowTask>> {
4105        Ok(self
4106            .poll_workflow_task_response(worker_id, task_queue, timeout)
4107            .await?
4108            .task)
4109    }
4110
4111    pub async fn poll_workflow_task_response(
4112        &self,
4113        worker_id: &str,
4114        task_queue: &str,
4115        timeout: Duration,
4116    ) -> Result<PollWorkflowTaskResponse> {
4117        let poll_request_id = unique_request_id("rust-workflow-poll");
4118        self.poll_workflow_task_response_with_request_id(
4119            worker_id,
4120            task_queue,
4121            timeout,
4122            &poll_request_id,
4123            1,
4124        )
4125        .await
4126    }
4127
4128    async fn poll_workflow_task_response_with_request_id(
4129        &self,
4130        worker_id: &str,
4131        task_queue: &str,
4132        timeout: Duration,
4133        poll_request_id: &str,
4134        transport_retries: usize,
4135    ) -> Result<PollWorkflowTaskResponse> {
4136        let body = json!({
4137            "worker_id": worker_id,
4138            "task_queue": task_queue,
4139            "poll_request_id": poll_request_id,
4140            "timeout_seconds": long_poll_timeout_seconds(timeout),
4141            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4142        });
4143        let mut wire: Value = self
4144            .poll_request_json_unresolved(
4145                "/worker/workflow-tasks/poll",
4146                RequestProtocol::DefaultWorker,
4147                &body,
4148                timeout + Duration::from_secs(5),
4149                transport_retries,
4150            )
4151            .await?;
4152        let claim =
4153            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4154        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4155            self.resolve_runtime_payloads(
4156                &mut wire,
4157                "/worker/workflow-tasks/poll",
4158                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4159            )
4160            .await?;
4161            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4162            if let Some(task) = data.task.as_mut() {
4163                self.fetch_remaining_workflow_history(worker_id, task)
4164                    .await?;
4165            }
4166            Ok(data)
4167        })
4168        .await?;
4169        Ok(data)
4170    }
4171
4172    async fn fetch_remaining_workflow_history(
4173        &self,
4174        worker_id: &str,
4175        task: &mut WorkflowTask,
4176    ) -> Result<()> {
4177        let mut next_token = task.next_history_page_token.clone();
4178        let mut seen = BTreeSet::new();
4179
4180        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4181            if seen.len() >= 128 || !seen.insert(token.clone()) {
4182                return Err(Error::Codec(
4183                    "workflow history pagination exceeded its page bound or repeated a token"
4184                        .into(),
4185                ));
4186            }
4187            let lease_owner = task
4188                .lease_owner
4189                .clone()
4190                .unwrap_or_else(|| worker_id.to_string());
4191            let page = self
4192                .workflow_task_history_page(
4193                    &task.task_id,
4194                    &lease_owner,
4195                    task.workflow_task_attempt,
4196                    &token,
4197                )
4198                .await?;
4199
4200            task.append_history_page(page);
4201
4202            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4203                return Err(Error::Codec(
4204                    "workflow history pagination returned the same page token".to_string(),
4205                ));
4206            }
4207
4208            next_token = task.next_history_page_token.clone();
4209        }
4210
4211        Ok(())
4212    }
4213
4214    async fn workflow_task_history_page(
4215        &self,
4216        task_id: &str,
4217        lease_owner: &str,
4218        workflow_task_attempt: u64,
4219        next_history_page_token: &str,
4220    ) -> Result<WorkflowTaskHistoryPage> {
4221        let body = json!({
4222            "lease_owner": lease_owner,
4223            "workflow_task_attempt": workflow_task_attempt,
4224            "next_history_page_token": next_history_page_token
4225        });
4226        let path = format!("/worker/workflow-tasks/{task_id}/history");
4227
4228        self.request_json(
4229            reqwest::Method::POST,
4230            &path,
4231            RequestProtocol::DefaultWorker,
4232            Some(&body),
4233        )
4234        .await
4235    }
4236
4237    pub async fn complete_workflow_task(
4238        &self,
4239        task_id: &str,
4240        lease_owner: &str,
4241        workflow_task_attempt: u64,
4242        commands: Vec<Value>,
4243    ) -> Result<Value> {
4244        self.complete_workflow_task_with_message_streams(
4245            task_id,
4246            lease_owner,
4247            workflow_task_attempt,
4248            commands,
4249            Vec::new(),
4250            Vec::new(),
4251            None,
4252        )
4253        .await
4254    }
4255
4256    #[allow(clippy::too_many_arguments)]
4257    async fn complete_workflow_task_with_message_streams(
4258        &self,
4259        task_id: &str,
4260        lease_owner: &str,
4261        workflow_task_attempt: u64,
4262        commands: Vec<Value>,
4263        message_stream_cursors: Vec<Value>,
4264        message_stream_waits: Vec<Value>,
4265        sticky_cache: Option<Value>,
4266    ) -> Result<Value> {
4267        validate_workflow_task_commands(&commands)?;
4268        let has_message_stream_metadata =
4269            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4270        if has_message_stream_metadata
4271            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4272        {
4273            return Err(Error::Codec(
4274                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4275                    .to_string(),
4276            ));
4277        }
4278        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4279            &commands,
4280            has_message_stream_metadata,
4281        );
4282        let protocol_version = if sticky_cache.is_some()
4283            && protocol_version
4284                .strip_prefix("1.")
4285                .and_then(|minor| minor.parse::<u64>().ok())
4286                .is_some_and(|minor| minor < 18)
4287        {
4288            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4289        } else {
4290            protocol_version
4291        };
4292        let mut body = json!({
4293            "lease_owner": lease_owner,
4294            "workflow_task_attempt": workflow_task_attempt,
4295            "commands": commands
4296        });
4297        if !message_stream_cursors.is_empty() {
4298            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4299        }
4300        if !message_stream_waits.is_empty() {
4301            body["message_stream_waits"] = Value::Array(message_stream_waits);
4302        }
4303        if let Some(claim) = sticky_cache {
4304            body["sticky_cache"] = claim;
4305        }
4306        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4307        self.request_json(
4308            reqwest::Method::POST,
4309            &path,
4310            RequestProtocol::Worker(protocol_version),
4311            Some(&body),
4312        )
4313        .await
4314    }
4315
4316    pub async fn fail_workflow_task(
4317        &self,
4318        task_id: &str,
4319        lease_owner: &str,
4320        workflow_task_attempt: u64,
4321        message: impl Into<String>,
4322    ) -> Result<Value> {
4323        self.fail_workflow_task_with_type(
4324            task_id,
4325            lease_owner,
4326            workflow_task_attempt,
4327            message,
4328            "RustWorkflowTaskFailure",
4329        )
4330        .await
4331    }
4332
4333    async fn fail_workflow_task_with_type(
4334        &self,
4335        task_id: &str,
4336        lease_owner: &str,
4337        workflow_task_attempt: u64,
4338        message: impl Into<String>,
4339        failure_type: &str,
4340    ) -> Result<Value> {
4341        self.fail_workflow_task_with_failure(
4342            task_id,
4343            lease_owner,
4344            workflow_task_attempt,
4345            json!({"message": message.into(), "type": failure_type}),
4346        )
4347        .await
4348    }
4349
4350    async fn fail_workflow_task_with_failure(
4351        &self,
4352        task_id: &str,
4353        lease_owner: &str,
4354        workflow_task_attempt: u64,
4355        failure: Value,
4356    ) -> Result<Value> {
4357        let body = json!({
4358            "lease_owner": lease_owner,
4359            "workflow_task_attempt": workflow_task_attempt,
4360            "failure": failure,
4361        });
4362        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4363        self.request_json(
4364            reqwest::Method::POST,
4365            &path,
4366            RequestProtocol::DefaultWorker,
4367            Some(&body),
4368        )
4369        .await
4370    }
4371
4372    pub async fn poll_activity_task(
4373        &self,
4374        worker_id: &str,
4375        task_queue: &str,
4376        timeout: Duration,
4377    ) -> Result<Option<ActivityTask>> {
4378        Ok(self
4379            .poll_activity_task_response(worker_id, task_queue, timeout)
4380            .await?
4381            .task)
4382    }
4383
4384    /// Poll an activity task while preserving server stop and drain metadata.
4385    pub async fn poll_activity_task_response(
4386        &self,
4387        worker_id: &str,
4388        task_queue: &str,
4389        timeout: Duration,
4390    ) -> Result<PollActivityTaskResponse> {
4391        let poll_request_id = unique_request_id("rust-activity-poll");
4392        self.poll_activity_task_response_with_request_id(
4393            worker_id,
4394            task_queue,
4395            timeout,
4396            &poll_request_id,
4397            1,
4398        )
4399        .await
4400        .map(worker_session::SessionPollResponse::ordinary)
4401    }
4402
4403    async fn poll_activity_task_response_with_request_id(
4404        &self,
4405        worker_id: &str,
4406        task_queue: &str,
4407        timeout: Duration,
4408        poll_request_id: &str,
4409        transport_retries: usize,
4410    ) -> Result<worker_session::SessionPollResponse> {
4411        let body = json!({
4412            "worker_id": worker_id,
4413            "task_queue": task_queue,
4414            "poll_request_id": poll_request_id,
4415            "timeout_seconds": long_poll_timeout_seconds(timeout),
4416        });
4417        let mut wire: Value = self
4418            .poll_request_json_unresolved(
4419                "/worker/activity-tasks/poll",
4420                RequestProtocol::DefaultWorker,
4421                &body,
4422                timeout + Duration::from_secs(5),
4423                transport_retries,
4424            )
4425            .await?;
4426        let claim = activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?;
4427        let mut data: worker_session::SessionPollResponse =
4428            activity_hydration::HydrationClaim::protect(claim.as_ref(), self, async {
4429                self.resolve_runtime_payloads(
4430                    &mut wire,
4431                    "/worker/activity-tasks/poll",
4432                    RequestProtocol::DefaultWorker,
4433                )
4434                .await?;
4435                Ok(serde_json::from_value(wire)?)
4436            })
4437            .await?;
4438        if let Some(task) = data.task.as_mut() {
4439            task.hydration_claim = claim;
4440        }
4441        Ok(data)
4442    }
4443
4444    pub async fn complete_activity_task<T: Serialize>(
4445        &self,
4446        task_id: &str,
4447        activity_attempt_id: &str,
4448        lease_owner: &str,
4449        result: T,
4450        codec: &str,
4451    ) -> Result<Value> {
4452        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4453        let body = json!({
4454            "activity_attempt_id": activity_attempt_id,
4455            "lease_owner": lease_owner,
4456            "result": result
4457        });
4458        let path = format!("/worker/activity-tasks/{task_id}/complete");
4459        activity_task_response(
4460            self.request_json(
4461                reqwest::Method::POST,
4462                &path,
4463                RequestProtocol::DefaultWorker,
4464                Some(&body),
4465            )
4466            .await,
4467            "complete",
4468            task_id,
4469            activity_attempt_id,
4470        )
4471    }
4472
4473    pub async fn fail_activity_task(
4474        &self,
4475        task_id: &str,
4476        activity_attempt_id: &str,
4477        lease_owner: &str,
4478        message: impl Into<String>,
4479        non_retryable: bool,
4480    ) -> Result<Value> {
4481        let body = json!({
4482            "activity_attempt_id": activity_attempt_id,
4483            "lease_owner": lease_owner,
4484            "failure": {
4485                "message": message.into(),
4486                "type": "RustActivityFailure",
4487                "non_retryable": non_retryable
4488            }
4489        });
4490        let path = format!("/worker/activity-tasks/{task_id}/fail");
4491        activity_task_response(
4492            self.request_json(
4493                reqwest::Method::POST,
4494                &path,
4495                RequestProtocol::DefaultWorker,
4496                Some(&body),
4497            )
4498            .await,
4499            "fail",
4500            task_id,
4501            activity_attempt_id,
4502        )
4503    }
4504
4505    /// Record a flat map of scalar/null activity progress metadata.
4506    ///
4507    /// Heartbeat details use the Server's bounded JSON progress contract.
4508    /// They are not workflow payload envelopes.
4509    pub async fn heartbeat_activity_task<T: Serialize>(
4510        &self,
4511        task_id: &str,
4512        activity_attempt_id: &str,
4513        lease_owner: &str,
4514        details: T,
4515    ) -> Result<ActivityHeartbeatResponse> {
4516        serde_json::from_value(
4517            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4518                .await?,
4519        )
4520        .map_err(Error::from)
4521    }
4522
4523    async fn heartbeat_activity_task_value<T: Serialize>(
4524        &self,
4525        task_id: &str,
4526        activity_attempt_id: &str,
4527        lease_owner: &str,
4528        details: T,
4529    ) -> Result<Value> {
4530        let details = AvroValue::from_serialize(&details)?.into_json()?;
4531        let body = json!({
4532            "activity_attempt_id": activity_attempt_id,
4533            "lease_owner": lease_owner,
4534            "details": details
4535        });
4536        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4537        activity_task_response(
4538            self.request_json(
4539                reqwest::Method::POST,
4540                &path,
4541                RequestProtocol::DefaultWorker,
4542                Some(&body),
4543            )
4544            .await,
4545            "heartbeat",
4546            task_id,
4547            activity_attempt_id,
4548        )
4549    }
4550
4551    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4552        &self,
4553        method: reqwest::Method,
4554        path: &str,
4555        protocol: RequestProtocol,
4556        body: Option<&B>,
4557    ) -> Result<T> {
4558        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4559            .await
4560    }
4561
4562    async fn request_json_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 mut value: Value = self
4571            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4572            .await?;
4573        let protocol = match protocol {
4574            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4575                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4576            }
4577            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4578        };
4579        self.resolve_runtime_payloads(&mut value, path, protocol)
4580            .await?;
4581        Ok(serde_json::from_value(value)?)
4582    }
4583
4584    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4585        &self,
4586        method: reqwest::Method,
4587        path: &str,
4588        protocol: RequestProtocol,
4589        body: Option<&B>,
4590        timeout: Duration,
4591    ) -> Result<T> {
4592        let protocol = match protocol {
4593            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4594                let selected = self.worker_protocol_version.as_str();
4595                if self.cooperative_worker_protocol
4596                    && !cooperative_cancellation::supports_protocol(selected)
4597                {
4598                    return Err(Error::CooperativeCancellationUnavailable(
4599                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4600                    ));
4601                }
4602                if let RequestProtocol::Worker(minimum) = protocol {
4603                    let supported = minimum
4604                        .strip_prefix("1.")
4605                        .and_then(|minor| minor.parse::<u64>().ok())
4606                        .zip(
4607                            selected
4608                                .strip_prefix("1.")
4609                                .and_then(|minor| minor.parse::<u64>().ok()),
4610                        )
4611                        .is_some_and(|(minimum, selected)| selected >= minimum);
4612                    if !supported {
4613                        return Err(Error::WorkerLoop(format!(
4614                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4615                        )));
4616                    }
4617                }
4618                RequestProtocol::Worker(selected)
4619            }
4620            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4621        };
4622        let auth_token = self.auth_token(protocol)?;
4623        let mut request = self
4624            .http
4625            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4626            .timeout(timeout)
4627            .header(reqwest::header::ACCEPT, "application/json")
4628            .header(reqwest::header::CONTENT_TYPE, "application/json")
4629            .header("X-Namespace", &self.namespace);
4630
4631        match protocol {
4632            RequestProtocol::DefaultWorker => {
4633                request = request.header(
4634                    "X-Durable-Workflow-Protocol-Version",
4635                    self.worker_protocol_version.as_str(),
4636                );
4637            }
4638            RequestProtocol::Worker(version) => {
4639                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4640            }
4641            RequestProtocol::ControlPlane => {
4642                request = request.header(
4643                    "X-Durable-Workflow-Control-Plane-Version",
4644                    CONTROL_PLANE_VERSION,
4645                );
4646            }
4647        }
4648
4649        if let Some(token) = auth_token {
4650            request = request.bearer_auth(token);
4651        }
4652
4653        if let Some(body) = body {
4654            let mut body = serde_json::to_value(body)?;
4655            if matches!(
4656                method,
4657                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4658            ) {
4659                self.externalize_runtime_payloads(&mut body, path, protocol)
4660                    .await?;
4661            }
4662            request = request.json(&body);
4663        }
4664
4665        let request = request.build()?;
4666        let request_body = request
4667            .body()
4668            .and_then(reqwest::Body::as_bytes)
4669            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4670        let poll_request_id = path.ends_with("/poll").then(|| {
4671            request_body
4672                .as_ref()
4673                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4674                .unwrap_or_default()
4675        });
4676        let mut storage_retries = 0_usize;
4677        let mut deferred_workflow_completion = false;
4678
4679        loop {
4680            // Keep the serialized body and lease/poll identity across admission pauses.
4681            let receive = async {
4682                let response = self
4683                    .http
4684                    .execute(request.try_clone().ok_or_else(|| {
4685                        Error::WorkerLoop("worker request body cannot be retried".to_string())
4686                    })?)
4687                    .await?;
4688                let status = response.status();
4689                Ok::<_, Error>((status, response.bytes().await?))
4690            };
4691            let retry_deadline = self
4692                .worker_storage_admission
4693                .as_ref()
4694                .and_then(|admission| admission.workflow_completion_retry_deadline);
4695            if deferred_workflow_completion
4696                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
4697            {
4698                return Err(Error::Timeout);
4699            }
4700            let (status, bytes) = match retry_deadline.filter(|_| deferred_workflow_completion) {
4701                Some(deadline) => tokio::time::timeout_at(deadline, receive)
4702                    .await
4703                    .map_err(|_| Error::Timeout)??,
4704                None => receive.await?,
4705            };
4706
4707            if !status.is_success() {
4708                let body = String::from_utf8_lossy(&bytes).to_string();
4709                if let Some(protocol) = protocol_failure(status, &body) {
4710                    return Err(Error::Protocol(protocol));
4711                }
4712                let error = Error::Http { status, body };
4713                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
4714                    &error,
4715                    path,
4716                    request_body.as_ref(),
4717                )
4718                .is_some();
4719                if self
4720                    .wait_for_storage_admission(
4721                        &error,
4722                        protocol,
4723                        Some(path),
4724                        poll_request_id.as_deref(),
4725                        request_body.as_ref(),
4726                        &mut storage_retries,
4727                    )
4728                    .await
4729                {
4730                    continue;
4731                }
4732                return Err(error);
4733            }
4734
4735            if bytes.is_empty() {
4736                return Ok(serde_json::from_value(Value::Null)?);
4737            }
4738
4739            return Ok(serde_json::from_slice(&bytes)?);
4740        }
4741    }
4742
4743    async fn wait_for_storage_admission(
4744        &self,
4745        error: &Error,
4746        protocol: RequestProtocol,
4747        path: Option<&str>,
4748        poll_request_id: Option<&str>,
4749        request_body: Option<&Value>,
4750        retries: &mut usize,
4751    ) -> bool {
4752        let Some(admission) = self
4753            .worker_storage_admission
4754            .as_ref()
4755            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4756        else {
4757            return false;
4758        };
4759        let completion_deferred = path.and_then(|path| {
4760            worker_deferred_workflow_completion_retry_after(error, path, request_body)
4761        });
4762        let Some(advertised_delay) = completion_deferred
4763            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
4764            .or_else(|| {
4765                path.and_then(|path| {
4766                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4767                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4768                })
4769            })
4770        else {
4771            return false;
4772        };
4773        *retries = retries.saturating_add(1);
4774        let delay = worker_retry_delay(admission.policy, *retries)
4775            .max(advertised_delay)
4776            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4777        let delay = if completion_deferred.is_some() {
4778            delay.max(advertised_delay)
4779        } else {
4780            delay
4781        };
4782        let wait_deadline = tokio::time::Instant::now() + delay;
4783        loop {
4784            if admission.stop.load(Ordering::SeqCst) {
4785                return false;
4786            }
4787            let now = tokio::time::Instant::now();
4788            if admission
4789                .workflow_completion_retry_deadline
4790                .is_some_and(|deadline| now >= deadline)
4791            {
4792                return false;
4793            }
4794            let remaining = wait_deadline.saturating_duration_since(now);
4795            if remaining.is_zero() {
4796                return true;
4797            }
4798            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4799        }
4800    }
4801
4802    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4803        &self,
4804        path: &str,
4805        protocol: RequestProtocol,
4806        body: &B,
4807        timeout: Duration,
4808        max_retries: usize,
4809    ) -> Result<T> {
4810        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
4811            .await
4812    }
4813
4814    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
4815        &self,
4816        path: &str,
4817        protocol: RequestProtocol,
4818        body: &B,
4819        timeout: Duration,
4820        max_retries: usize,
4821    ) -> Result<T> {
4822        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
4823            .await
4824    }
4825
4826    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
4827        &self,
4828        path: &str,
4829        protocol: RequestProtocol,
4830        body: &B,
4831        timeout: Duration,
4832        max_retries: usize,
4833        resolve: bool,
4834    ) -> Result<T> {
4835        let mut retries = 0;
4836
4837        loop {
4838            let response = if resolve {
4839                self.request_json_with_timeout(
4840                    reqwest::Method::POST,
4841                    path,
4842                    protocol,
4843                    Some(body),
4844                    timeout,
4845                )
4846                .await
4847            } else {
4848                self.request_json_unresolved_with_timeout(
4849                    reqwest::Method::POST,
4850                    path,
4851                    protocol,
4852                    Some(body),
4853                    timeout,
4854                )
4855                .await
4856            };
4857
4858            match response {
4859                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4860                response => return worker_poll_response(response),
4861            }
4862        }
4863    }
4864
4865    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4866        match protocol {
4867            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4868                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4869                    return Ok(Some(token));
4870                }
4871                if self.control_token.is_some() {
4872                    return Err(Error::MissingRoleCredentials {
4873                        role: "worker",
4874                        opposite_role: "control",
4875                    });
4876                }
4877                Ok(None)
4878            }
4879            RequestProtocol::ControlPlane => {
4880                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4881                    return Ok(Some(token));
4882                }
4883                if self.worker_token.is_some() {
4884                    return Err(Error::MissingRoleCredentials {
4885                        role: "control",
4886                        opposite_role: "worker",
4887                    });
4888                }
4889                Ok(None)
4890            }
4891        }
4892    }
4893}
4894
4895fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4896    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4897    let reason = body
4898        .get("reason")
4899        .and_then(Value::as_str)
4900        .unwrap_or("query_rejected")
4901        .to_string();
4902    let message = body
4903        .get("message")
4904        .or_else(|| body.get("error"))
4905        .and_then(Value::as_str)
4906        .unwrap_or("workflow query was rejected")
4907        .to_string();
4908
4909    QueryFailure {
4910        status: status.as_u16(),
4911        reason,
4912        message,
4913        body,
4914    }
4915}
4916
4917fn workflow_command_result(
4918    command: WorkflowCommandKind,
4919    data: Value,
4920    workflow_id: &str,
4921    run_id: Option<&str>,
4922) -> WorkflowCommandResult {
4923    WorkflowCommandResult {
4924        command,
4925        workflow_id: data
4926            .get("workflow_id")
4927            .and_then(Value::as_str)
4928            .unwrap_or(workflow_id)
4929            .to_string(),
4930        run_id: data
4931            .get("run_id")
4932            .and_then(Value::as_str)
4933            .or(run_id)
4934            .map(str::to_string),
4935        outcome: data
4936            .get("outcome")
4937            .and_then(Value::as_str)
4938            .map(str::to_string),
4939        reason: data
4940            .get("reason")
4941            .and_then(Value::as_str)
4942            .map(str::to_string),
4943        command_status: data
4944            .get("command_status")
4945            .and_then(Value::as_str)
4946            .map(str::to_string),
4947        raw: data,
4948    }
4949}
4950
4951fn workflow_command_rejection(
4952    command: WorkflowCommandKind,
4953    status: reqwest::StatusCode,
4954    raw_body: String,
4955    workflow_id: &str,
4956    run_id: Option<&str>,
4957) -> WorkflowCommandRejection {
4958    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4959    WorkflowCommandRejection {
4960        command,
4961        status: status.as_u16(),
4962        reason: body
4963            .get("reason")
4964            .and_then(Value::as_str)
4965            .unwrap_or("workflow_command_rejected")
4966            .to_string(),
4967        message: body
4968            .get("message")
4969            .or_else(|| body.get("error"))
4970            .and_then(Value::as_str)
4971            .unwrap_or("workflow lifecycle command was rejected")
4972            .to_string(),
4973        workflow_id: body
4974            .get("workflow_id")
4975            .and_then(Value::as_str)
4976            .unwrap_or(workflow_id)
4977            .to_string(),
4978        run_id: body
4979            .get("run_id")
4980            .and_then(Value::as_str)
4981            .or(run_id)
4982            .map(str::to_string),
4983        target_scope: body
4984            .get("target_scope")
4985            .and_then(Value::as_str)
4986            .map(str::to_string),
4987        body,
4988    }
4989}
4990
4991fn query_task_response(response: Result<Value>) -> Result<Value> {
4992    match response {
4993        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4994        response => response,
4995    }
4996}
4997
4998fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4999    match response {
5000        Err(Error::Http { status, body })
5001            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
5002        {
5003            Ok(serde_json::from_str(&body)?)
5004        }
5005        response => response,
5006    }
5007}
5008
5009fn worker_poll_body_is_stop(body: &str) -> bool {
5010    serde_json::from_str::<Value>(body)
5011        .ok()
5012        .is_some_and(|body| {
5013            worker_poll_is_stop(
5014                body.get("poll_status").and_then(Value::as_str),
5015                body.get("reason").and_then(Value::as_str),
5016            )
5017        })
5018}
5019
5020fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
5021    matches!(poll_status, Some("draining" | "stopped"))
5022        || matches!(reason, Some("worker_draining" | "worker_stopped"))
5023}
5024
5025fn query_task_rejection_is_final(error: &Error) -> bool {
5026    matches!(
5027        error,
5028        Error::QueryFailed(failure)
5029            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
5030    )
5031}
5032
5033fn activity_task_response<T>(
5034    response: Result<T>,
5035    operation: &str,
5036    task_id: &str,
5037    activity_attempt_id: &str,
5038) -> Result<T> {
5039    match response {
5040        Err(Error::Http { status, body }) => {
5041            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
5042            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
5043                operation: operation.to_string(),
5044                status: status.as_u16(),
5045                reason: body
5046                    .get("reason")
5047                    .and_then(Value::as_str)
5048                    .unwrap_or("activity_task_rejected")
5049                    .to_string(),
5050                task_id: body
5051                    .get("task_id")
5052                    .and_then(Value::as_str)
5053                    .unwrap_or(task_id)
5054                    .to_string(),
5055                activity_attempt_id: body
5056                    .get("activity_attempt_id")
5057                    .and_then(Value::as_str)
5058                    .unwrap_or(activity_attempt_id)
5059                    .to_string(),
5060                cancel_requested: body
5061                    .get("cancel_requested")
5062                    .and_then(Value::as_bool)
5063                    .unwrap_or(false),
5064                can_continue: body.get("can_continue").and_then(Value::as_bool),
5065                run_closed_reason: body
5066                    .get("run_closed_reason")
5067                    .and_then(Value::as_str)
5068                    .map(str::to_string),
5069                body,
5070            }))
5071        }
5072        response => response,
5073    }
5074}
5075
5076fn activity_task_rejection_is_final(error: &Error) -> bool {
5077    matches!(
5078        error,
5079        Error::ActivityTaskRejected(rejection)
5080            if matches!(
5081                rejection.reason.as_str(),
5082                "run_cancelled"
5083                    | "run_terminated"
5084                    | "attempt_closed"
5085                    | "stale_attempt"
5086                    | "activity_cancelled"
5087                    | "task_cancelled"
5088                    | "run_closed"
5089                    | "activity_not_running"
5090                    | "attempt_not_found"
5091            )
5092    )
5093}
5094
5095fn workflow_task_completion_is_terminal_timeout(
5096    error: &Error,
5097    task_id: &str,
5098    workflow_task_attempt: u64,
5099    run_id: Option<&str>,
5100) -> bool {
5101    let Error::Http { status, body } = error else {
5102        return false;
5103    };
5104    if *status != reqwest::StatusCode::CONFLICT {
5105        return false;
5106    }
5107
5108    let Some(run_id) = run_id else {
5109        return false;
5110    };
5111    let Ok(body) = serde_json::from_str::<Value>(body) else {
5112        return false;
5113    };
5114
5115    body.get("recorded").and_then(Value::as_bool) == Some(false)
5116        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5117        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5118        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5119        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5120        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5121}
5122
5123fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5124    let body: Value = serde_json::from_str(raw_body).ok()?;
5125    let reason = body.get("reason")?.as_str()?;
5126    if !matches!(
5127        reason,
5128        "missing_protocol_version"
5129            | "unsupported_protocol_version"
5130            | "missing_control_plane_version"
5131            | "unsupported_control_plane_version"
5132    ) {
5133        return None;
5134    }
5135
5136    Some(ProtocolFailure {
5137        status: status.as_u16(),
5138        reason: reason.to_string(),
5139        message: body
5140            .get("message")
5141            .or_else(|| body.get("error"))
5142            .and_then(Value::as_str)
5143            .unwrap_or("protocol version rejected")
5144            .to_string(),
5145        supported_version: body
5146            .get("supported_version")
5147            .and_then(Value::as_str)
5148            .map(str::to_string),
5149        requested_version: body
5150            .get("requested_version")
5151            .and_then(Value::as_str)
5152            .map(str::to_string),
5153        body,
5154    })
5155}
5156
5157fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5158    timeout
5159        .as_secs()
5160        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5161        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5162}
5163
5164fn worker_operation_is_retryable(error: &Error) -> bool {
5165    if worker_poll_capacity_retry_after(error).is_some()
5166        || worker_storage_admission_body(error).is_some()
5167        || worker_backend_unavailable_body(error).is_some()
5168        || worker_operation_is_explicitly_non_retryable(error)
5169    {
5170        return false;
5171    }
5172
5173    match error {
5174        Error::Transport(error) => {
5175            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5176        }
5177        Error::Http { status, .. } => {
5178            matches!(
5179                *status,
5180                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5181            ) || status.is_server_error()
5182        }
5183        _ => false,
5184    }
5185}
5186
5187fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5188    let body: Value = match error {
5189        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5190        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5191        _ => return None,
5192    };
5193    matches!(
5194        body.get("reason").and_then(Value::as_str),
5195        Some("storage_pressure" | "storage_admission_unavailable")
5196    )
5197    .then_some(body)
5198}
5199
5200fn worker_storage_admission_retry_after(
5201    error: &Error,
5202    poll_request_id: Option<&str>,
5203) -> Option<Duration> {
5204    let Error::Http { status, .. } = error else {
5205        return None;
5206    };
5207    let body = worker_storage_admission_body(error)?;
5208    let delay = body.get("retry_after_seconds")?.as_u64()?;
5209    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5210        || delay == 0
5211        || body.get("retryable") != Some(&Value::Bool(true))
5212        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5213        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5214        || body
5215            .get("request_admitted")
5216            .is_some_and(|admitted| admitted != &Value::Bool(false))
5217    {
5218        return None;
5219    }
5220    match poll_request_id {
5221        Some(id) => {
5222            if id.is_empty()
5223                || body.get("task") != Some(&Value::Null)
5224                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5225                || body.get("poll_status") != body.get("reason")
5226                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5227                || body.get("claim_admitted") != Some(&Value::Bool(false))
5228            {
5229                return None;
5230            }
5231        }
5232        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5233        None => {}
5234    }
5235    Some(Duration::from_secs(delay))
5236}
5237
5238fn worker_backend_unavailable_retry_after(
5239    error: &Error,
5240    path: &str,
5241    poll_request_id: Option<&str>,
5242) -> Option<Duration> {
5243    let operation = match path {
5244        "/worker/register" => "register_worker",
5245        "/worker/heartbeat" => "heartbeat_worker",
5246        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5247        "/worker/activity-tasks/poll" => "poll_activity_task",
5248        "/worker/query-tasks/poll" => "poll_query_task",
5249        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5250        _ => return None,
5251    };
5252    let body = worker_backend_unavailable_body(error)?;
5253    let delay = body.get("retry_after_seconds")?.as_u64()?;
5254    if delay == 0
5255        || body.get("operation")?.as_str()? != operation
5256        || body.get("outcome")?.as_str()? != "unknown"
5257        || body.get("retryable") != Some(&Value::Bool(true))
5258        || body.get("worker_id")?.as_str()?.is_empty()
5259    {
5260        return None;
5261    }
5262    if let Some(id) = poll_request_id {
5263        if id.is_empty()
5264            || body.get("task") != Some(&Value::Null)
5265            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5266            || body.get("poll_request_id")?.as_str()? != id
5267            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5268        {
5269            return None;
5270        }
5271    } else if path.ends_with("/poll") {
5272        return None;
5273    }
5274    Some(Duration::from_secs(delay))
5275}
5276
5277fn worker_fenced_completion_retry_after(
5278    error: &Error,
5279    path: &str,
5280    request_body: Option<&Value>,
5281) -> Option<Duration> {
5282    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5283        .strip_prefix("/worker/workflow-tasks/")
5284        .and_then(|tail| tail.strip_suffix("/complete"))
5285    {
5286        ("complete_workflow_task", task_id, "workflow_task_attempt")
5287    } else if let Some(task_id) = path
5288        .strip_prefix("/worker/activity-tasks/")
5289        .and_then(|tail| tail.strip_suffix("/complete"))
5290    {
5291        ("complete_activity_task", task_id, "activity_attempt_id")
5292    } else {
5293        return None;
5294    };
5295    if task_id.is_empty() || task_id.contains('/') {
5296        return None;
5297    }
5298
5299    let request = request_body?.as_object()?;
5300    let lease_owner = request.get("lease_owner")?.as_str()?;
5301    if lease_owner.is_empty() {
5302        return None;
5303    }
5304    let attempt = request.get(attempt_field)?;
5305    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5306        || (attempt_field == "activity_attempt_id"
5307            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5308    {
5309        return None;
5310    }
5311
5312    let body = worker_backend_unavailable_body(error)?;
5313    let delay = body.get("retry_after_seconds")?.as_u64()?;
5314    if delay == 0
5315        || body.get("operation")?.as_str()? != operation
5316        || body.get("outcome")?.as_str()? != "unknown"
5317        || body.get("retryable") != Some(&Value::Bool(true))
5318        || body.get("worker_id")?.as_str()? != lease_owner
5319        || body.get("task_queue") != Some(&Value::Null)
5320        || body.get("task_id")?.as_str()? != task_id
5321        || body.get("lease_owner")?.as_str()? != lease_owner
5322        || body.get(attempt_field) != Some(attempt)
5323    {
5324        return None;
5325    }
5326
5327    Some(Duration::from_secs(delay))
5328}
5329
5330fn worker_deferred_workflow_completion_retry_after(
5331    error: &Error,
5332    path: &str,
5333    request_body: Option<&Value>,
5334) -> Option<Duration> {
5335    let task_id = path
5336        .strip_prefix("/worker/workflow-tasks/")?
5337        .strip_suffix("/complete")?;
5338    if task_id.is_empty() || task_id.contains('/') {
5339        return None;
5340    }
5341    let request = request_body?.as_object()?;
5342    let owner = request.get("lease_owner")?.as_str()?;
5343    let attempt = request.get("workflow_task_attempt")?;
5344    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
5345        return None;
5346    }
5347    let Error::Http { status, body } = error else {
5348        return None;
5349    };
5350    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5351        return None;
5352    }
5353    let body: Value = serde_json::from_str(body).ok()?;
5354    let delay = body.get("retry_after_seconds")?.as_u64()?;
5355    if !(1..=5).contains(&delay)
5356        || body.get("reason")?.as_str()? != "backend_lock_pressure"
5357        || body.get("operation")?.as_str()? != "complete_workflow_task"
5358        || body.get("outcome")?.as_str()? != "deferred"
5359        || body.get("recorded") != Some(&Value::Bool(false))
5360        || body.get("retryable") != Some(&Value::Bool(true))
5361        || body.get("task_id")?.as_str()? != task_id
5362        || body.get("lease_owner")?.as_str()? != owner
5363        || body.get("workflow_task_attempt") != Some(attempt)
5364        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
5365    {
5366        return None;
5367    }
5368    Some(Duration::from_secs(delay))
5369}
5370
5371fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5372    let Error::Http { status, body } = error else {
5373        return None;
5374    };
5375    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5376        return None;
5377    }
5378    let body: Value = serde_json::from_str(body).ok()?;
5379    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5380}
5381
5382fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5383    let Error::Http { body, .. } = error else {
5384        return false;
5385    };
5386
5387    serde_json::from_str::<Value>(body)
5388        .ok()
5389        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5390        == Some(false)
5391}
5392
5393fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5394    let Error::Http { status, body } = error else {
5395        return None;
5396    };
5397    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5398        return None;
5399    }
5400
5401    let body = serde_json::from_str::<Value>(body).ok()?;
5402    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5403        == Some("long_poll_capacity_exhausted")
5404        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5405    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5406        return None;
5407    }
5408
5409    Some(Duration::from_secs(
5410        body.get("retry_after_seconds")
5411            .and_then(Value::as_u64)
5412            .unwrap_or_default(),
5413    ))
5414}
5415
5416fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5417    let exponent = retry.saturating_sub(1).min(31) as u32;
5418    policy
5419        .initial_backoff
5420        .saturating_mul(1_u32 << exponent)
5421        .min(policy.max_backoff)
5422}
5423
5424#[derive(Debug)]
5425pub struct ClientBuilder {
5426    base_url: String,
5427    token: Option<String>,
5428    control_token: Option<String>,
5429    worker_token: Option<String>,
5430    namespace: String,
5431    timeout: Duration,
5432    max_external_payload_bytes: usize,
5433    worker_protocol_version: WorkerProtocolVersion,
5434}
5435
5436impl ClientBuilder {
5437    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5438    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5439        self.worker_protocol_version = version;
5440        self
5441    }
5442
5443    pub fn token(mut self, token: Option<String>) -> Self {
5444        self.token = token;
5445        self
5446    }
5447
5448    pub fn control_token(mut self, token: Option<String>) -> Self {
5449        self.control_token = token;
5450        self
5451    }
5452
5453    pub fn worker_token(mut self, token: Option<String>) -> Self {
5454        self.worker_token = token;
5455        self
5456    }
5457
5458    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5459        self.namespace = namespace.into();
5460        self
5461    }
5462
5463    pub fn timeout(mut self, timeout: Duration) -> Self {
5464        self.timeout = timeout;
5465        self
5466    }
5467
5468    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5469    /// References are fetched only from this client's authenticated runtime.
5470    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5471        self.max_external_payload_bytes = bytes;
5472        self
5473    }
5474
5475    pub fn build(self) -> Result<Client> {
5476        let base_url = self.base_url.trim_end_matches('/').to_string();
5477        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5478            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5479            .unwrap_or_else(|_| base_url.ends_with("/api"));
5480
5481        if has_sdk_api_suffix {
5482            return Err(Error::InvalidBaseUrl);
5483        }
5484
5485        Ok(Client {
5486            http: reqwest::Client::builder()
5487                .timeout(self.timeout)
5488                .redirect(reqwest::redirect::Policy::none())
5489                .build()?,
5490            hydration_timeout: self.timeout,
5491            base_url,
5492            token: self.token,
5493            control_token: self.control_token,
5494            worker_token: self.worker_token,
5495            namespace: self.namespace,
5496            max_external_payload_bytes: self.max_external_payload_bytes,
5497            worker_storage_admission: None,
5498            cooperative_worker_protocol: false,
5499            worker_protocol_version: self.worker_protocol_version,
5500            local_activities_enabled: false,
5501            worker_sessions_enabled: false,
5502            max_concurrent_worker_sessions: 10,
5503            worker_build_id: None,
5504            sticky_cache: None,
5505            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5506        })
5507    }
5508}
5509
5510#[derive(Clone, Debug)]
5511pub struct WorkflowHandle {
5512    client: Client,
5513    pub workflow_id: String,
5514    pub run_id: Option<String>,
5515    pub workflow_type: String,
5516}
5517
5518impl WorkflowHandle {
5519    /// Describe whichever run is current for this stable workflow instance.
5520    pub async fn describe(&self) -> Result<WorkflowDescription> {
5521        self.client.describe_workflow(&self.workflow_id).await
5522    }
5523
5524    /// Describe the run identity originally selected by this handle.
5525    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5526        let run_id = self.run_id.as_deref().ok_or_else(|| {
5527            Error::Codec("run_id is required for selected-run description".to_string())
5528        })?;
5529        self.client
5530            .describe_workflow_run(&self.workflow_id, run_id)
5531            .await
5532    }
5533
5534    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5535        self.client
5536            .signal_workflow(&self.workflow_id, signal_name, input)
5537            .await
5538    }
5539
5540    pub async fn append_message<T: Serialize>(
5541        &self,
5542        stream_name: &str,
5543        message_id: &str,
5544        input: T,
5545    ) -> Result<Value> {
5546        self.client
5547            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5548            .await
5549    }
5550
5551    /// Signal only if this handle's selected run is still current.
5552    pub async fn signal_selected_run<T: Serialize>(
5553        &self,
5554        signal_name: &str,
5555        input: T,
5556    ) -> Result<Value> {
5557        let run_id = self.run_id.as_deref().ok_or_else(|| {
5558            Error::Codec("run_id is required for selected-run signaling".to_string())
5559        })?;
5560        self.client
5561            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5562            .await
5563    }
5564
5565    /// Close whichever run is current as cancelled, without workflow cleanup.
5566    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5567        self.client
5568            .cancel_workflow(&self.workflow_id, options)
5569            .await
5570    }
5571
5572    /// Request cancellation only if this handle's selected run is still current.
5573    pub async fn cancel_selected_run(
5574        &self,
5575        options: WorkflowCommandOptions,
5576    ) -> Result<WorkflowCommandResult> {
5577        let run_id = self.run_id.as_deref().ok_or_else(|| {
5578            Error::Codec("run_id is required for selected-run cancellation".to_string())
5579        })?;
5580        self.client
5581            .cancel_workflow_run(&self.workflow_id, run_id, options)
5582            .await
5583    }
5584
5585    /// Forcefully terminate whichever run is current.
5586    pub async fn terminate(
5587        &self,
5588        options: WorkflowCommandOptions,
5589    ) -> Result<WorkflowCommandResult> {
5590        self.client
5591            .terminate_workflow(&self.workflow_id, options)
5592            .await
5593    }
5594
5595    /// Terminate only if this handle's selected run is still current.
5596    pub async fn terminate_selected_run(
5597        &self,
5598        options: WorkflowCommandOptions,
5599    ) -> Result<WorkflowCommandResult> {
5600        let run_id = self.run_id.as_deref().ok_or_else(|| {
5601            Error::Codec("run_id is required for selected-run termination".to_string())
5602        })?;
5603        self.client
5604            .terminate_workflow_run(&self.workflow_id, run_id, options)
5605            .await
5606    }
5607
5608    /// Continue this handle's failed run without repeating completed activities.
5609    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5610        let run_id = self
5611            .run_id
5612            .as_deref()
5613            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5614        self.client
5615            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5616            .await
5617    }
5618
5619    /// Execute a named, read-only query against this workflow.
5620    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5621        self.client
5622            .query_workflow(&self.workflow_id, query_name, input)
5623            .await
5624    }
5625
5626    pub async fn query_avro_value<T: Serialize>(
5627        &self,
5628        query_name: &str,
5629        input: T,
5630    ) -> Result<AvroValue> {
5631        self.client
5632            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5633            .await
5634    }
5635
5636    pub async fn update<T: Serialize>(
5637        &self,
5638        update_name: &str,
5639        input: T,
5640        request_id: Option<&str>,
5641    ) -> Result<Value> {
5642        self.client
5643            .update_workflow(&self.workflow_id, update_name, input, request_id)
5644            .await
5645    }
5646
5647    pub async fn update_avro_value<T: Serialize>(
5648        &self,
5649        update_name: &str,
5650        input: T,
5651        request_id: Option<&str>,
5652    ) -> Result<AvroValue> {
5653        self.client
5654            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5655            .await
5656    }
5657
5658    /// Query only if this handle's selected run is still current.
5659    pub async fn query_selected_run<T: Serialize>(
5660        &self,
5661        query_name: &str,
5662        input: T,
5663    ) -> Result<Value> {
5664        let run_id = self
5665            .run_id
5666            .as_deref()
5667            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5668        self.client
5669            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5670            .await
5671    }
5672
5673    /// Await the final terminal outcome of the current continue-as-new chain.
5674    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5675        self.result_target(options, None).await
5676    }
5677
5678    /// Await the final result without projecting Avro bytes through JSON.
5679    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5680        self.result_avro_value_target(options, None).await
5681    }
5682
5683    /// Await the final result and decode it into a Serde application type.
5684    pub async fn result_typed<T: DeserializeOwned>(
5685        &self,
5686        options: WorkflowResultOptions,
5687    ) -> Result<T> {
5688        let result = self.result_avro_value(options).await?;
5689        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5690    }
5691
5692    /// Await only the run identity originally selected by this handle.
5693    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5694        let run_id = self.run_id.as_deref().ok_or_else(|| {
5695            Error::Codec("run_id is required for selected-run result".to_string())
5696        })?;
5697        self.result_target(options, Some(run_id)).await
5698    }
5699
5700    /// Await the selected run's result on the lossless Avro Value surface.
5701    pub async fn result_selected_run_avro_value(
5702        &self,
5703        options: WorkflowResultOptions,
5704    ) -> Result<AvroValue> {
5705        let run_id = self.run_id.as_deref().ok_or_else(|| {
5706            Error::Codec("run_id is required for selected-run result".to_string())
5707        })?;
5708        self.result_avro_value_target(options, Some(run_id)).await
5709    }
5710
5711    /// Await the selected run and decode its result into a Serde type.
5712    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5713        &self,
5714        options: WorkflowResultOptions,
5715    ) -> Result<T> {
5716        let result = self.result_selected_run_avro_value(options).await?;
5717        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5718    }
5719
5720    async fn result_avro_value_target(
5721        &self,
5722        options: WorkflowResultOptions,
5723        selected_run_id: Option<&str>,
5724    ) -> Result<AvroValue> {
5725        let started = Instant::now();
5726
5727        loop {
5728            let description = match selected_run_id {
5729                Some(run_id) => {
5730                    self.client
5731                        .describe_workflow_run(&self.workflow_id, run_id)
5732                        .await?
5733                }
5734                None => self.describe().await?,
5735            };
5736            if description.is_completed() {
5737                return description.output_avro_value.ok_or_else(|| {
5738                    Error::Codec(
5739                        "missing_payload_envelope: typed workflow result requires output_envelope"
5740                            .to_string(),
5741                    )
5742                });
5743            }
5744            if description.is_terminal() {
5745                let outcome =
5746                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5747                return Err(match outcome.kind {
5748                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5749                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5750                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5751                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5752                });
5753            }
5754            if started.elapsed() >= options.timeout {
5755                return Err(Error::Timeout);
5756            }
5757            tokio::time::sleep(options.poll_interval).await;
5758        }
5759    }
5760
5761    async fn result_target(
5762        &self,
5763        options: WorkflowResultOptions,
5764        selected_run_id: Option<&str>,
5765    ) -> Result<Value> {
5766        let started = Instant::now();
5767
5768        loop {
5769            let description = match selected_run_id {
5770                Some(run_id) => {
5771                    self.client
5772                        .describe_workflow_run(&self.workflow_id, run_id)
5773                        .await?
5774                }
5775                None => self.describe().await?,
5776            };
5777            if description.is_completed() {
5778                return Ok(description.output.unwrap_or(Value::Null));
5779            }
5780
5781            if description.is_terminal() {
5782                let outcome =
5783                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5784                return Err(match outcome.kind {
5785                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5786                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5787                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5788                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5789                });
5790            }
5791
5792            if started.elapsed() >= options.timeout {
5793                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5794                    kind: WorkflowTerminalKind::TimedOut,
5795                    workflow_id: description
5796                        .workflow_id
5797                        .clone()
5798                        .unwrap_or_else(|| self.workflow_id.clone()),
5799                    run_id: description
5800                        .run_id
5801                        .clone()
5802                        .or_else(|| selected_run_id.map(str::to_string)),
5803                    reason: "result_wait_timeout".to_string(),
5804                    failure_category: Some("client_timeout".to_string()),
5805                    failure_id: None,
5806                    exception_type: None,
5807                    exception_class: None,
5808                    non_retryable: None,
5809                    message: Some(format!(
5810                        "workflow result was not terminal within {:?}",
5811                        options.timeout
5812                    )),
5813                    exception: None,
5814                    raw: description.raw_value(),
5815                }));
5816            }
5817
5818            tokio::time::sleep(options.poll_interval).await;
5819        }
5820    }
5821}
5822
5823#[derive(Clone, Copy, Debug)]
5824pub struct WorkflowResultOptions {
5825    pub poll_interval: Duration,
5826    pub timeout: Duration,
5827}
5828
5829impl Default for WorkflowResultOptions {
5830    fn default() -> Self {
5831        Self {
5832            poll_interval: Duration::from_millis(500),
5833            timeout: Duration::from_secs(30),
5834        }
5835    }
5836}
5837
5838#[derive(Clone, Debug, Deserialize)]
5839pub struct WorkflowDescription {
5840    pub workflow_id: Option<String>,
5841    pub run_id: Option<String>,
5842    pub workflow_type: Option<String>,
5843    pub status: Option<String>,
5844    #[serde(default)]
5845    pub closed_reason: Option<String>,
5846    #[serde(default)]
5847    pub error: Option<String>,
5848    #[serde(default)]
5849    pub failure: Option<Value>,
5850    #[serde(default)]
5851    pub exception: Option<Value>,
5852    #[serde(default)]
5853    pub failures: Vec<Value>,
5854    #[serde(default)]
5855    pub output: Option<Value>,
5856    #[serde(default)]
5857    pub output_envelope: Option<Value>,
5858    #[serde(skip)]
5859    pub output_avro_value: Option<AvroValue>,
5860    #[serde(flatten)]
5861    pub raw: HashMap<String, Value>,
5862}
5863
5864/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5865#[derive(Clone, Debug, Deserialize)]
5866pub struct WorkflowStreamDescription {
5867    pub stream_name: String,
5868    pub status: String,
5869    pub last_offset: i64,
5870    pub total_items: u64,
5871    pub pending_items: u64,
5872    #[serde(default)]
5873    pub opened_at: Option<String>,
5874    #[serde(default)]
5875    pub last_appended_at: Option<String>,
5876    #[serde(default)]
5877    pub closed_at: Option<String>,
5878    #[serde(default)]
5879    pub error_reason: Option<String>,
5880    #[serde(default)]
5881    pub retention_seconds: Option<u64>,
5882    #[serde(flatten)]
5883    pub raw: HashMap<String, Value>,
5884}
5885
5886impl WorkflowStreamDescription {
5887    pub fn is_terminal(&self) -> bool {
5888        matches!(self.status.as_str(), "closed" | "errored")
5889    }
5890}
5891
5892/// One item for direct or replay-safe append.
5893#[derive(Clone, Debug, Default)]
5894pub struct WorkflowStreamAppendItem {
5895    pub payload_envelope: Option<Value>,
5896    pub payload_reference: Option<String>,
5897    pub item_type: Option<String>,
5898    pub content_type: Option<String>,
5899    pub idempotency_key: Option<String>,
5900}
5901
5902impl WorkflowStreamAppendItem {
5903    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5904    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5905        let value = AvroValue::from_serialize(&payload)?;
5906        Ok(Self {
5907            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5908            ..Self::default()
5909        })
5910    }
5911
5912    /// Preserve an external payload URI as an opaque service-contract reference.
5913    pub fn from_reference(reference: impl Into<String>) -> Self {
5914        Self {
5915            payload_reference: Some(reference.into()),
5916            ..Self::default()
5917        }
5918    }
5919
5920    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5921        self.item_type = Some(item_type.into());
5922        self
5923    }
5924
5925    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5926        self.content_type = Some(content_type.into());
5927        self
5928    }
5929
5930    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5931        self.idempotency_key = Some(idempotency_key.into());
5932        self
5933    }
5934
5935    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5936        let mut item = serde_json::Map::new();
5937        if let Some(payload) = &self.payload_envelope {
5938            item.insert("payload".to_string(), payload.clone());
5939            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5940        }
5941        if let Some(reference) = &self.payload_reference {
5942            item.insert("payload_reference".to_string(), json!(reference));
5943        }
5944        if let Some(item_type) = &self.item_type {
5945            item.insert("item_type".to_string(), json!(item_type));
5946        }
5947        if let Some(content_type) = &self.content_type {
5948            item.insert("content_type".to_string(), json!(content_type));
5949        }
5950        if let Some(key) = derived_idempotency_key
5951            .as_ref()
5952            .or(self.idempotency_key.as_ref())
5953        {
5954            item.insert("idempotency_key".to_string(), json!(key));
5955        }
5956        Value::Object(item)
5957    }
5958}
5959
5960/// One durable item at its stable zero-based offset.
5961#[derive(Clone, Debug)]
5962pub struct WorkflowStreamItem {
5963    pub offset: u64,
5964    pub payload: Option<Value>,
5965    pub payload_envelope: Option<Value>,
5966    pub payload_reference: Option<String>,
5967    pub payload_codec: Option<String>,
5968    pub idempotency_key: Option<String>,
5969    pub item_type: Option<String>,
5970    pub content_type: Option<String>,
5971    pub origin: Option<String>,
5972    pub origin_reference: Option<String>,
5973    pub emitted_at: Option<String>,
5974    pub raw: Value,
5975}
5976
5977/// One bounded at-least-once subscription page.
5978#[derive(Clone, Debug)]
5979pub struct WorkflowStreamPage {
5980    pub stream: WorkflowStreamDescription,
5981    pub items: Vec<WorkflowStreamItem>,
5982    pub next_offset: u64,
5983    pub terminal: bool,
5984}
5985
5986/// Durable acceptance and deduplication outcome for an append request.
5987#[derive(Clone, Debug)]
5988pub struct WorkflowStreamAppendResult {
5989    pub stream: WorkflowStreamDescription,
5990    pub accepted_offsets: Vec<u64>,
5991    pub accepted: u64,
5992    pub deduped: u64,
5993}
5994
5995#[derive(Deserialize)]
5996struct WorkflowStreamListResponse {
5997    #[serde(default)]
5998    streams: Vec<WorkflowStreamDescription>,
5999}
6000
6001#[derive(Deserialize)]
6002struct WorkflowStreamDescriptionResponse {
6003    stream: WorkflowStreamDescription,
6004}
6005
6006#[derive(Deserialize)]
6007struct WorkflowStreamPageResponse {
6008    stream: WorkflowStreamDescription,
6009    #[serde(default)]
6010    items: Vec<Value>,
6011    next_offset: u64,
6012    terminal: bool,
6013}
6014
6015#[derive(Deserialize)]
6016struct WorkflowStreamAppendResponse {
6017    stream: WorkflowStreamDescription,
6018    #[serde(default)]
6019    accepted_offsets: Vec<u64>,
6020    accepted: u64,
6021    deduped: u64,
6022}
6023
6024impl WorkflowDescription {
6025    pub fn is_completed(&self) -> bool {
6026        matches!(self.status.as_deref(), Some("completed" | "Completed"))
6027    }
6028
6029    pub fn is_terminal(&self) -> bool {
6030        matches!(
6031            self.status.as_deref(),
6032            Some(
6033                "completed"
6034                    | "Completed"
6035                    | "failed"
6036                    | "Failed"
6037                    | "cancelled"
6038                    | "Cancelled"
6039                    | "terminated"
6040                    | "Terminated"
6041                    | "timed_out"
6042                    | "TimedOut",
6043            )
6044        )
6045    }
6046
6047    fn decode_payloads(&mut self) -> Result<()> {
6048        if let Some(envelope) = &self.output_envelope {
6049            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
6050            self.output = Some(value.clone().into_json()?);
6051            self.output_avro_value = Some(value);
6052        }
6053
6054        Ok(())
6055    }
6056
6057    fn raw_value(&self) -> Value {
6058        let mut data = self.raw.clone();
6059        data.insert(
6060            "workflow_id".to_string(),
6061            self.workflow_id
6062                .clone()
6063                .map(Value::String)
6064                .unwrap_or(Value::Null),
6065        );
6066        data.insert(
6067            "run_id".to_string(),
6068            self.run_id
6069                .clone()
6070                .map(Value::String)
6071                .unwrap_or(Value::Null),
6072        );
6073        data.insert(
6074            "workflow_type".to_string(),
6075            self.workflow_type
6076                .clone()
6077                .map(Value::String)
6078                .unwrap_or(Value::Null),
6079        );
6080        data.insert(
6081            "status".to_string(),
6082            self.status
6083                .clone()
6084                .map(Value::String)
6085                .unwrap_or(Value::Null),
6086        );
6087        data.insert(
6088            "closed_reason".to_string(),
6089            self.closed_reason
6090                .clone()
6091                .map(Value::String)
6092                .unwrap_or(Value::Null),
6093        );
6094        if let Some(failure) = &self.failure {
6095            data.insert("failure".to_string(), failure.clone());
6096        }
6097        if let Some(exception) = &self.exception {
6098            data.insert("exception".to_string(), exception.clone());
6099        }
6100        Value::Object(data.into_iter().collect())
6101    }
6102}
6103
6104fn workflow_terminal_outcome(
6105    description: &WorkflowDescription,
6106    workflow_id: &str,
6107    run_id: Option<&str>,
6108) -> WorkflowTerminalOutcome {
6109    let terminal_kind = description
6110        .closed_reason
6111        .as_deref()
6112        .or(description.status.as_deref())
6113        .unwrap_or("failed")
6114        .to_ascii_lowercase();
6115    let kind = match terminal_kind.as_str() {
6116        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6117        "terminated" => WorkflowTerminalKind::Terminated,
6118        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6119        _ => WorkflowTerminalKind::Failed,
6120    };
6121    let default_reason = match kind {
6122        WorkflowTerminalKind::Failed => "workflow_failed",
6123        WorkflowTerminalKind::Cancelled => "cancelled",
6124        WorkflowTerminalKind::Terminated => "terminated",
6125        WorkflowTerminalKind::TimedOut => "timed_out",
6126    };
6127    let failure = description
6128        .failure
6129        .as_ref()
6130        .filter(|value| value.is_object());
6131    let nested_failure = failure
6132        .and_then(|value| value.get("failures"))
6133        .and_then(Value::as_array)
6134        .and_then(|failures| failures.last())
6135        .or_else(|| description.failures.last());
6136    let exception = description
6137        .exception
6138        .clone()
6139        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6140        .or_else(|| {
6141            nested_failure
6142                .and_then(|value| value.get("exception_payload"))
6143                .cloned()
6144        });
6145    let string_field = |name: &str| {
6146        failure
6147            .and_then(|value| value.get(name))
6148            .and_then(Value::as_str)
6149            .or_else(|| {
6150                nested_failure
6151                    .and_then(|value| value.get(name))
6152                    .and_then(Value::as_str)
6153            })
6154            .map(str::to_string)
6155    };
6156    let exception_field = |name: &str| {
6157        exception
6158            .as_ref()
6159            .and_then(|value| value.get(name))
6160            .and_then(Value::as_str)
6161            .map(str::to_string)
6162    };
6163    let message = description
6164        .error
6165        .clone()
6166        .or_else(|| string_field("message"))
6167        .or_else(|| exception_field("message"));
6168    let reason = description
6169        .raw
6170        .get("reason")
6171        .and_then(Value::as_str)
6172        .map(str::to_string)
6173        .or_else(|| {
6174            failure
6175                .and_then(|value| value.get("reason"))
6176                .and_then(Value::as_str)
6177                .map(str::to_string)
6178        })
6179        .or_else(|| description.closed_reason.clone())
6180        .unwrap_or_else(|| default_reason.to_string());
6181    let failure_id = string_field("failure_id").or_else(|| {
6182        nested_failure
6183            .and_then(|value| value.get("id"))
6184            .and_then(Value::as_str)
6185            .map(str::to_string)
6186    });
6187
6188    WorkflowTerminalOutcome {
6189        kind,
6190        workflow_id: description
6191            .workflow_id
6192            .clone()
6193            .unwrap_or_else(|| workflow_id.to_string()),
6194        run_id: description
6195            .run_id
6196            .clone()
6197            .or_else(|| run_id.map(str::to_string)),
6198        reason,
6199        failure_category: string_field("failure_category")
6200            .or_else(|| Some(default_reason.to_string())),
6201        failure_id,
6202        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6203        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6204        non_retryable: failure
6205            .and_then(|value| value.get("non_retryable"))
6206            .and_then(Value::as_bool)
6207            .or_else(|| {
6208                nested_failure
6209                    .and_then(|value| value.get("non_retryable"))
6210                    .and_then(Value::as_bool)
6211            }),
6212        message,
6213        exception,
6214        raw: description.raw_value(),
6215    }
6216}
6217
6218#[derive(Clone, Debug, Deserialize)]
6219pub struct RegisterWorkerResponse {
6220    pub worker_id: String,
6221    pub registered: bool,
6222    #[serde(default)]
6223    pub heartbeat_interval_seconds: Option<u64>,
6224    #[serde(default)]
6225    pub protocol_version: Option<String>,
6226    #[serde(default)]
6227    pub server_capabilities: Option<Value>,
6228}
6229
6230/// Result of gracefully removing a worker-plane registration.
6231#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6232pub struct WorkerDeregistrationEnvelope {
6233    pub worker_id: String,
6234    pub outcome: String,
6235    pub recovered_workflow_task_count: u64,
6236}
6237
6238#[derive(Clone, Debug, Deserialize)]
6239pub struct PollWorkflowTaskResponse {
6240    #[serde(default)]
6241    pub task: Option<WorkflowTask>,
6242    #[serde(default)]
6243    pub poll_status: Option<String>,
6244    #[serde(default)]
6245    pub reason: Option<String>,
6246    #[serde(default)]
6247    pub protocol_version: Option<String>,
6248    #[serde(default)]
6249    pub server_capabilities: Option<Value>,
6250}
6251
6252impl PollWorkflowTaskResponse {
6253    /// Classify this response without parsing server display text.
6254    pub fn outcome(&self) -> WorkerPollOutcome {
6255        worker_poll_outcome(
6256            self.task.is_some(),
6257            self.poll_status.as_deref(),
6258            self.reason.as_deref(),
6259        )
6260    }
6261}
6262
6263fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6264    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6265        return false;
6266    };
6267    let supported = capabilities
6268        .get("workflow_memo_updates")
6269        .and_then(Value::as_object)
6270        .and_then(|memo| memo.get("supported"))
6271        .and_then(Value::as_bool)
6272        == Some(true);
6273    let command_advertised = capabilities
6274        .get("supported_workflow_task_commands")
6275        .and_then(Value::as_array)
6276        .is_some_and(|commands| {
6277            commands
6278                .iter()
6279                .any(|command| command.as_str() == Some("upsert_memo"))
6280        });
6281    supported && command_advertised
6282}
6283
6284fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6285    commands
6286        .iter()
6287        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6288}
6289
6290#[derive(Clone, Debug, Deserialize)]
6291pub struct PollActivityTaskResponse {
6292    #[serde(default)]
6293    pub task: Option<ActivityTask>,
6294    #[serde(default)]
6295    pub poll_status: Option<String>,
6296    #[serde(default)]
6297    pub reason: Option<String>,
6298}
6299
6300impl PollActivityTaskResponse {
6301    /// Classify this response without parsing server display text.
6302    pub fn outcome(&self) -> WorkerPollOutcome {
6303        worker_poll_outcome(
6304            self.task.is_some(),
6305            self.poll_status.as_deref(),
6306            self.reason.as_deref(),
6307        )
6308    }
6309}
6310
6311#[derive(Clone, Debug, Deserialize)]
6312pub struct PollQueryTaskResponse {
6313    #[serde(default)]
6314    pub task: Option<QueryTask>,
6315    #[serde(default)]
6316    pub poll_status: Option<String>,
6317    #[serde(default)]
6318    pub reason: Option<String>,
6319}
6320
6321impl PollQueryTaskResponse {
6322    /// Classify this response without parsing server display text.
6323    pub fn outcome(&self) -> WorkerPollOutcome {
6324        worker_poll_outcome(
6325            self.task.is_some(),
6326            self.poll_status.as_deref(),
6327            self.reason.as_deref(),
6328        )
6329    }
6330}
6331
6332/// Stable classification for worker poll responses.
6333#[derive(Clone, Debug, PartialEq, Eq)]
6334pub enum WorkerPollOutcome {
6335    /// A task was leased and is available on the response.
6336    Task,
6337    /// No task was leased, but the worker should continue polling.
6338    Idle {
6339        poll_status: Option<String>,
6340        reason: Option<String>,
6341    },
6342    /// The server asked this worker to stop claiming new work.
6343    Stop {
6344        poll_status: Option<String>,
6345        reason: Option<String>,
6346    },
6347}
6348
6349impl WorkerPollOutcome {
6350    pub fn should_stop(&self) -> bool {
6351        matches!(self, Self::Stop { .. })
6352    }
6353}
6354
6355fn worker_poll_outcome(
6356    has_task: bool,
6357    poll_status: Option<&str>,
6358    reason: Option<&str>,
6359) -> WorkerPollOutcome {
6360    if worker_poll_is_stop(poll_status, reason) {
6361        return WorkerPollOutcome::Stop {
6362            poll_status: poll_status.map(str::to_string),
6363            reason: reason.map(str::to_string),
6364        };
6365    }
6366
6367    if has_task {
6368        WorkerPollOutcome::Task
6369    } else {
6370        WorkerPollOutcome::Idle {
6371            poll_status: poll_status.map(str::to_string),
6372            reason: reason.map(str::to_string),
6373        }
6374    }
6375}
6376
6377/// An ephemeral server-routed query task.
6378#[derive(Clone, Debug, Deserialize)]
6379pub struct QueryTask {
6380    pub query_task_id: String,
6381    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6382    #[serde(default)]
6383    pub observability_context: Option<Value>,
6384    #[serde(default)]
6385    pub dispatch_observability_context: Option<Value>,
6386    #[serde(default)]
6387    pub observability_links: Option<Value>,
6388    #[serde(default = "default_workflow_task_attempt")]
6389    pub query_task_attempt: u64,
6390    #[serde(default)]
6391    pub lease_owner: Option<String>,
6392    #[serde(default)]
6393    pub workflow_id: Option<String>,
6394    #[serde(default)]
6395    pub run_id: Option<String>,
6396    pub workflow_type: String,
6397    pub query_name: String,
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 workflow_arguments: Option<Value>,
6405    #[serde(default)]
6406    pub query_arguments: Option<Value>,
6407    #[serde(default)]
6408    pub history_events: Vec<HistoryEvent>,
6409    #[serde(default)]
6410    pub history_export: Option<Value>,
6411    #[serde(default)]
6412    pub run_status: Option<String>,
6413}
6414
6415#[derive(Clone, Debug, Deserialize)]
6416pub struct WorkflowTask {
6417    pub task_id: String,
6418    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6419    #[serde(default)]
6420    pub observability_context: Option<Value>,
6421    #[serde(default)]
6422    pub dispatch_observability_context: Option<Value>,
6423    #[serde(default)]
6424    pub observability_links: Option<Value>,
6425    #[serde(default)]
6426    pub workflow_command_id: Option<String>,
6427    #[serde(default)]
6428    pub workflow_id: Option<String>,
6429    #[serde(default)]
6430    pub run_id: Option<String>,
6431    pub workflow_type: String,
6432    #[serde(default)]
6433    pub cancel_requested: bool,
6434    #[serde(
6435        default = "missing_task_payload_codec",
6436        deserialize_with = "deserialize_task_payload_codec"
6437    )]
6438    pub payload_codec: String,
6439    #[serde(default)]
6440    pub arguments: Option<Value>,
6441    #[serde(default)]
6442    pub history_events: Vec<HistoryEvent>,
6443    #[serde(default)]
6444    pub total_history_events: Option<u64>,
6445    #[serde(default)]
6446    pub history_size_bytes: Option<u64>,
6447    #[serde(default)]
6448    pub continue_as_new_recommended: Option<bool>,
6449    #[serde(default)]
6450    pub history_budget_pressure: Option<String>,
6451    #[serde(default)]
6452    pub next_history_page_token: Option<String>,
6453    #[serde(default = "default_workflow_task_attempt")]
6454    pub workflow_task_attempt: u64,
6455    #[serde(default)]
6456    pub workflow_signal_id: Option<String>,
6457    #[serde(default)]
6458    pub signal_name: Option<String>,
6459    #[serde(default)]
6460    pub signal_arguments: Option<Value>,
6461    #[serde(default)]
6462    pub workflow_update_id: Option<String>,
6463    #[serde(default)]
6464    pub update_name: Option<String>,
6465    #[serde(default)]
6466    pub lease_owner: Option<String>,
6467}
6468
6469impl WorkflowTask {
6470    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6471        self.history_events.extend(page.history_events);
6472
6473        if page.total_history_events.is_some() {
6474            self.total_history_events = page.total_history_events;
6475        }
6476
6477        self.next_history_page_token = page
6478            .next_history_page_token
6479            .filter(|token| !token.is_empty());
6480    }
6481}
6482
6483#[derive(Clone, Debug, Deserialize)]
6484struct WorkflowTaskHistoryPage {
6485    #[serde(default)]
6486    history_events: Vec<HistoryEvent>,
6487    #[serde(default)]
6488    total_history_events: Option<u64>,
6489    #[serde(default)]
6490    next_history_page_token: Option<String>,
6491}
6492
6493#[derive(Clone, Debug, Deserialize)]
6494pub struct ActivityTask {
6495    pub task_id: String,
6496    #[serde(default)]
6497    pub workflow_id: Option<String>,
6498    #[serde(default)]
6499    pub run_id: Option<String>,
6500    #[serde(default)]
6501    pub activity_execution_id: Option<String>,
6502    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6503    #[serde(default)]
6504    pub observability_context: Option<Value>,
6505    #[serde(default)]
6506    pub dispatch_observability_context: Option<Value>,
6507    #[serde(default)]
6508    pub observability_links: Option<Value>,
6509    #[serde(default)]
6510    pub activity_attempt_id: Option<String>,
6511    #[serde(default)]
6512    pub attempt_id: Option<String>,
6513    pub activity_type: String,
6514    #[serde(
6515        default = "missing_task_payload_codec",
6516        deserialize_with = "deserialize_task_payload_codec"
6517    )]
6518    pub payload_codec: String,
6519    #[serde(default)]
6520    pub arguments: Option<Value>,
6521    #[serde(default = "default_attempt_number")]
6522    pub attempt_number: u64,
6523    #[serde(default)]
6524    pub lease_owner: Option<String>,
6525}
6526
6527#[derive(Clone, Debug, Serialize, Deserialize)]
6528pub struct HistoryEvent {
6529    #[serde(alias = "type")]
6530    pub event_type: String,
6531    #[serde(default)]
6532    pub payload: Value,
6533    #[serde(flatten)]
6534    pub raw: HashMap<String, Value>,
6535}
6536
6537/// One decoded signal in the committed workflow-history snapshot.
6538#[derive(Clone, Debug, PartialEq)]
6539pub struct QuerySignal {
6540    pub id: Option<String>,
6541    pub name: String,
6542    pub arguments: Vec<Value>,
6543    avro_arguments: Vec<AvroValue>,
6544    pub workflow_sequence: Option<u64>,
6545}
6546
6547impl QuerySignal {
6548    /// Lossless fixed Avro Value arguments for this committed signal.
6549    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6550        &self.avro_arguments
6551    }
6552}
6553
6554/// Immutable state supplied to a registered query handler.
6555///
6556/// This context intentionally exposes no activity, signal-wait, or command
6557/// APIs. Query handlers inspect committed history and return a value; query
6558/// completion does not append an event or advance deterministic execution.
6559#[derive(Clone, Debug)]
6560pub struct QueryContext {
6561    pub workflow_id: Option<String>,
6562    pub run_id: Option<String>,
6563    pub workflow_type: String,
6564    pub run_status: Option<String>,
6565    workflow_input: Value,
6566    workflow_input_avro_value: AvroValue,
6567    history_events: Arc<Vec<HistoryEvent>>,
6568    signal_events: Arc<Vec<QuerySignal>>,
6569}
6570
6571impl QueryContext {
6572    /// The normalized argument list used to start the workflow.
6573    pub fn workflow_input(&self) -> &Value {
6574        &self.workflow_input
6575    }
6576
6577    /// The lossless fixed Avro Value argument list used to start the workflow.
6578    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6579        &self.workflow_input_avro_value
6580    }
6581
6582    /// The immutable committed history used for this query snapshot.
6583    pub fn history_events(&self) -> &[HistoryEvent] {
6584        self.history_events.as_slice()
6585    }
6586
6587    /// All decoded signals in committed workflow order.
6588    pub fn signal_events(&self) -> &[QuerySignal] {
6589        self.signal_events.as_slice()
6590    }
6591
6592    /// Decoded argument lists for each committed signal with `signal_name`.
6593    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6594        self.signal_events
6595            .iter()
6596            .filter(|signal| signal.name == signal_name)
6597            .map(|signal| signal.arguments.clone())
6598            .collect()
6599    }
6600
6601    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6602    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6603        self.signal_events
6604            .iter()
6605            .filter(|signal| signal.name == signal_name)
6606            .map(|signal| signal.avro_arguments.clone())
6607            .collect()
6608    }
6609}
6610
6611#[derive(Clone, Debug, Deserialize)]
6612pub struct ActivityHeartbeatResponse {
6613    #[serde(default)]
6614    pub cancel_requested: bool,
6615    #[serde(default)]
6616    pub heartbeat_recorded: bool,
6617    #[serde(default)]
6618    pub can_continue: Option<bool>,
6619    #[serde(default)]
6620    pub reason: Option<String>,
6621    #[serde(default)]
6622    pub run_closed_reason: Option<String>,
6623    #[serde(default)]
6624    pub run_closed_at: Option<String>,
6625    #[serde(default)]
6626    pub lease_expires_at: Option<String>,
6627    #[serde(default)]
6628    pub last_heartbeat_at: Option<String>,
6629}
6630
6631impl ActivityHeartbeatResponse {
6632    /// Whether the activity should stop instead of attempting completion.
6633    pub fn should_stop(&self) -> bool {
6634        self.cancel_requested || self.can_continue == Some(false)
6635    }
6636}
6637
6638fn missing_task_payload_codec() -> String {
6639    MISSING_TASK_PAYLOAD_CODEC.to_string()
6640}
6641
6642fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6643where
6644    D: Deserializer<'de>,
6645{
6646    Ok(match Value::deserialize(deserializer)? {
6647        Value::String(codec) => codec,
6648        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6649        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6650    })
6651}
6652
6653fn default_workflow_task_attempt() -> u64 {
6654    1
6655}
6656
6657fn default_attempt_number() -> u64 {
6658    1
6659}
6660
6661type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6662type WorkflowHandler =
6663    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<WorkflowFuture> + Send + Sync>;
6664type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6665type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6666type ReplayedWorkflowHandler =
6667    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<ReplayedWorkflowInvocation> + Send + Sync>;
6668type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6669type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6670type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6671type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6672type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6673type ReplayedQueryHandler = Arc<
6674    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6675        + Send
6676        + Sync,
6677>;
6678type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6679
6680struct ReplayedWorkflowInvocation {
6681    future: WorkflowFuture,
6682    snapshot: WorkflowStateSnapshot,
6683}
6684
6685#[derive(Clone)]
6686struct RegisteredWorkflow {
6687    execute: WorkflowHandler,
6688    replay: Option<ReplayedWorkflowHandler>,
6689    state_type: Option<TypeId>,
6690    definition_fingerprint: Option<String>,
6691}
6692
6693fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
6694    names
6695        .iter()
6696        .map(|name| {
6697            json!({
6698                "name": name,
6699                "parameters": [{
6700                    "name": "args",
6701                    "position": 0,
6702                    "required": false,
6703                    "variadic": true,
6704                    "type": null,
6705                    "allows_null": true,
6706                    "default_available": false,
6707                    "default": null,
6708                }],
6709            })
6710        })
6711        .collect()
6712}
6713
6714#[derive(Debug)]
6715struct WorkflowTaskDecision {
6716    commands: Vec<Value>,
6717    message_stream_cursors: Vec<Value>,
6718    message_stream_waits: Vec<Value>,
6719    cancellation_delivery: Option<CancellationDelivery>,
6720    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6721    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6722}
6723
6724enum PreparedWorkflowTask {
6725    Decision(WorkflowTaskDecision),
6726    Execution {
6727        task: WorkflowTask,
6728        context: WorkflowContext,
6729        future: WorkflowFuture,
6730    },
6731}
6732
6733impl WorkflowTaskDecision {
6734    fn without_message_streams(commands: Vec<Value>) -> Self {
6735        Self {
6736            commands,
6737            message_stream_cursors: Vec::new(),
6738            message_stream_waits: Vec::new(),
6739            cancellation_delivery: None,
6740            cancellation_scope_opening: None,
6741            cancellation_scope_delivery: None,
6742        }
6743    }
6744}
6745
6746#[derive(Clone)]
6747enum RegisteredQuery {
6748    Snapshot(QueryHandler),
6749    Replayed {
6750        state_type: TypeId,
6751        handler: ReplayedQueryHandler,
6752    },
6753}
6754
6755#[derive(Clone, Debug)]
6756pub struct WorkerHeartbeatObservation {
6757    pub worker_id: String,
6758    pub task_queue: String,
6759    pub acknowledged_at_unix_millis: u64,
6760    pub acknowledgement: Value,
6761}
6762
6763/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6764///
6765/// Expected empty long polls and explicit Server capacity backpressure are
6766/// normal worker states. Capacity backpressure honors the advertised retry
6767/// delay without consuming this retry budget. Other transport failures,
6768/// retryable HTTP 408/429 responses, and server errors are retried with capped
6769/// exponential backoff. Authentication, protocol, codec, and handler failures
6770/// are never retried by the worker.
6771/// Explicit storage admission pauses also preserve the already-serialized worker
6772/// request without consuming this budget or rerunning its handler. The delay is
6773/// capped by `max_backoff`, except an explicit completion deferral must honor
6774/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
6775/// completion retries remain bounded by the original cleanup deadline.
6776/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6777/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6778/// and `max_retries = 0` disables ordinary retries in either mode.
6779#[derive(Clone, Copy, Debug)]
6780pub struct WorkerRetryPolicy {
6781    /// Number of retries after the initial request fails.
6782    pub max_retries: usize,
6783    /// Delay before the first retry.
6784    pub initial_backoff: Duration,
6785    /// Maximum delay between retries.
6786    pub max_backoff: Duration,
6787}
6788
6789impl Default for WorkerRetryPolicy {
6790    fn default() -> Self {
6791        Self {
6792            max_retries: 5,
6793            initial_backoff: Duration::from_millis(100),
6794            max_backoff: Duration::from_secs(5),
6795        }
6796    }
6797}
6798
6799#[derive(Clone, Debug)]
6800struct WorkerStorageAdmission {
6801    policy: WorkerRetryPolicy,
6802    stop: Arc<AtomicBool>,
6803    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
6804}
6805
6806struct StopWorkerOnDrop(Arc<AtomicBool>);
6807
6808impl Drop for StopWorkerOnDrop {
6809    fn drop(&mut self) {
6810        self.0.store(true, Ordering::SeqCst);
6811    }
6812}
6813
6814async fn wait_for_worker_stop(stop: &AtomicBool) {
6815    while !stop.load(Ordering::SeqCst) {
6816        tokio::time::sleep(Duration::from_millis(100)).await;
6817    }
6818}
6819
6820#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6821enum ManagedPollOutcome {
6822    Idle,
6823    Handled,
6824    Stop,
6825}
6826
6827#[derive(Clone)]
6828pub struct Worker {
6829    client: Client,
6830    worker_id: String,
6831    task_queue: String,
6832    workflows: HashMap<String, RegisteredWorkflow>,
6833    activities: HashMap<String, ActivityHandler>,
6834    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6835    signals: HashMap<String, Vec<String>>,
6836    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6837    registration_definitions:
6838        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
6839    registration_error: Option<DuplicateRegistrationError>,
6840    max_concurrent_workflow_tasks: usize,
6841    max_concurrent_activity_tasks: usize,
6842    poll_timeout: Duration,
6843    heartbeat_interval: Duration,
6844    retry_policy: WorkerRetryPolicy,
6845    recover_transient_outages: bool,
6846    run_stop: Option<Arc<AtomicBool>>,
6847    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6848    cooperative_cancellation_enabled: bool,
6849    nexus_cooperative_cancellation_enabled: bool,
6850    allow_cancellation_scope_authoring: bool,
6851    allow_cancellation_scope_delivery: bool,
6852    cooperative_registration_confirmed: Arc<AtomicBool>,
6853    nexus_registration_confirmed: Arc<AtomicBool>,
6854    local_registration_confirmed: Arc<AtomicBool>,
6855    session_registration_confirmed: Arc<AtomicBool>,
6856    sticky_registration_confirmed: Arc<AtomicBool>,
6857    require_query_task_authority: bool,
6858    query_authority_confirmed: Arc<AtomicBool>,
6859    resource_capabilities: Vec<String>,
6860    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6861}
6862
6863impl Worker {
6864    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6865        Self {
6866            client,
6867            worker_id: default_worker_id(),
6868            task_queue: task_queue.into(),
6869            workflows: HashMap::new(),
6870            activities: HashMap::new(),
6871            queries: HashMap::new(),
6872            signals: HashMap::new(),
6873            updates: HashMap::new(),
6874            registration_definitions: HashMap::new(),
6875            registration_error: None,
6876            max_concurrent_workflow_tasks: 10,
6877            max_concurrent_activity_tasks: 10,
6878            poll_timeout: Duration::from_secs(30),
6879            heartbeat_interval: Duration::from_secs(60),
6880            retry_policy: WorkerRetryPolicy::default(),
6881            recover_transient_outages: false,
6882            run_stop: None,
6883            heartbeat_observer: None,
6884            cooperative_cancellation_enabled: false,
6885            nexus_cooperative_cancellation_enabled: false,
6886            allow_cancellation_scope_authoring: false,
6887            allow_cancellation_scope_delivery: false,
6888            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6889            nexus_registration_confirmed: Arc::new(AtomicBool::new(false)),
6890            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6891            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6892            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
6893            require_query_task_authority: false,
6894            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
6895            resource_capabilities: Vec::new(),
6896            sessions: Arc::new(Mutex::new(HashMap::new())),
6897        }
6898    }
6899
6900    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6901        self.worker_id = worker_id.into();
6902        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6903        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
6904        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6905        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6906        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
6907        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
6908        self.client.reset_sticky_cache();
6909        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6910        self
6911    }
6912
6913    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6914        self.poll_timeout = timeout;
6915        self
6916    }
6917
6918    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6919        self.heartbeat_interval = interval;
6920        self
6921    }
6922
6923    /// Require original query timing and non-renewing runtime observation.
6924    ///
6925    /// Registration refuses before creating a Worker unless protocol 1.20 and
6926    /// the runtime's `query_task_authority` capability are available. By default,
6927    /// older Servers retain their weaker, disclosed local-timing behavior.
6928    pub fn require_query_task_authority(mut self, required: bool) -> Self {
6929        self.require_query_task_authority = required;
6930        self
6931    }
6932
6933    /// Explicitly enable inline local activities in this workflow worker.
6934    ///
6935    /// The worker advertises the capability to Server only when enabled.
6936    /// These callbacks must yield to Tokio and have idempotent side effects.
6937    /// Cooperative prepared local supervision is a separate capability.
6938    pub fn local_activities(mut self, enabled: bool) -> Self {
6939        self.client.local_activities_enabled = enabled;
6940        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6941        self
6942    }
6943
6944    /// Opt in to separate cooperative workflow cancellation requests.
6945    ///
6946    /// Registration requires the Server to acknowledge this exact worker,
6947    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6948    /// processing uses canonical delivery and activity ownership fences.
6949    /// Existing terminal cancel and terminate operations remain terminal.
6950    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
6951    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6952    /// and [`Worker::run_until`] register automatically.
6953    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6954        self.cooperative_cancellation_enabled = enabled;
6955        self.client.cooperative_worker_protocol = enabled;
6956        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6957        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
6958        if !enabled {
6959            self.nexus_cooperative_cancellation_enabled = false;
6960        }
6961        self
6962    }
6963
6964    /// Opt in to cooperative Nexus completion waits on an installed workflow binding.
6965    ///
6966    /// This also enables ordinary cooperative cancellation. Registration checks
6967    /// protocol 1.20 and Server's installed `workflow_run` bridge before advertising.
6968    pub fn nexus_cooperative_cancellation(self, enabled: bool) -> Self {
6969        let mut worker = if enabled {
6970            self.cooperative_cancellation(true)
6971        } else {
6972            self
6973        };
6974        worker.nexus_cooperative_cancellation_enabled = enabled;
6975        worker.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
6976        worker
6977    }
6978
6979    /// Enable candidate scope authoring without advertising scoped execution.
6980    #[doc(hidden)]
6981    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6982        self.allow_cancellation_scope_authoring = enabled;
6983        self
6984    }
6985
6986    /// Enable the candidate scoped call consumer with canonical authoring.
6987    #[doc(hidden)]
6988    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6989        self.allow_cancellation_scope_delivery = enabled;
6990        self
6991    }
6992
6993    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6994    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6995        self.retry_policy = policy;
6996        self
6997    }
6998
6999    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
7000    ///
7001    /// Retries preserve the poll request identity and use capped exponential
7002    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
7003    /// An in-flight poll is allowed to finish so leased work is not discarded.
7004    /// Authentication, protocol, codec, handler and task settlement failures
7005    /// remain errors. Registration and deregistration are not retried here.
7006    ///
7007    /// The default is disabled, preserving the bounded retry contract.
7008    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
7009    /// even when this option is enabled.
7010    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
7011        self.recover_transient_outages = enabled;
7012        self
7013    }
7014
7015    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
7016    where
7017        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
7018    {
7019        self.heartbeat_observer = Some(Arc::new(observer));
7020        self
7021    }
7022
7023    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
7024        self.max_concurrent_workflow_tasks = count.max(1);
7025        self
7026    }
7027
7028    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
7029        self.max_concurrent_activity_tasks = count.max(1);
7030        self
7031    }
7032
7033    /// Validate local handler admission without making a Server request.
7034    ///
7035    /// Registration methods retain their existing signatures. A duplicate keeps
7036    /// the original handler and makes this Worker invalid, including its clones.
7037    /// `register`, `run`, `run_until` and `run_once` enforce this check before
7038    /// any network request. Build a new Worker to correct an invalid configuration.
7039    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
7040        match &self.registration_error {
7041            Some(error) => Err(error.clone()),
7042            None => Ok(()),
7043        }
7044    }
7045
7046    #[track_caller]
7047    fn admit_registration<F>(
7048        &mut self,
7049        handler_kind: RegistrationKind,
7050        workflow_type: Option<&str>,
7051        handler_name: &str,
7052        method: &'static str,
7053    ) -> bool {
7054        let location = std::panic::Location::caller();
7055        let definition = HandlerRegistration {
7056            method,
7057            handler_type: type_name::<F>(),
7058            file: location.file(),
7059            line: location.line(),
7060            column: location.column(),
7061        };
7062        let key = (
7063            handler_kind,
7064            workflow_type.map(str::to_owned),
7065            handler_name.to_owned(),
7066        );
7067        if let Some(first_definition) = self.registration_definitions.get(&key) {
7068            if self.registration_error.is_none() {
7069                self.registration_error = Some(DuplicateRegistrationError {
7070                    handler_kind,
7071                    workflow_type: key.1.clone(),
7072                    handler_name: key.2.clone(),
7073                    first_definition: first_definition.clone(),
7074                    second_definition: definition,
7075                });
7076            }
7077            return false;
7078        }
7079        self.registration_definitions.insert(key, definition);
7080        true
7081    }
7082
7083    /// Register a workflow handler.
7084    ///
7085    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
7086    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
7087    /// while acquiring or decoding a worker task remain worker-operation
7088    /// failures and do not get converted into workflow outcomes.
7089    #[track_caller]
7090    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
7091    where
7092        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
7093        Fut: Future<Output = Result<Value>> + Send + 'static,
7094    {
7095        let workflow_type = workflow_type.into();
7096        if !self.admit_registration::<F>(
7097            RegistrationKind::Workflow,
7098            None,
7099            &workflow_type,
7100            "register_workflow",
7101        ) {
7102            return;
7103        }
7104        let handler = Arc::new(handler);
7105        self.workflows.insert(
7106            workflow_type,
7107            RegisteredWorkflow {
7108                execute: Arc::new(move |ctx, input| {
7109                    let handler = Arc::clone(&handler);
7110                    Ok(Box::pin(async move {
7111                        let result = handler(ctx, input.into_json()?).await?;
7112                        AvroValue::from_serialize(&result)
7113                    }))
7114                }),
7115                replay: None,
7116                state_type: None,
7117                definition_fingerprint: None,
7118            },
7119        );
7120    }
7121
7122    /// Register a workflow with one Serde request value and a Serde result.
7123    ///
7124    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
7125    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
7126    /// workflow-specific schema. A task must contain zero arguments for a unit
7127    /// request or exactly one argument for every other request type.
7128    ///
7129    /// See the runnable
7130    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
7131    /// for typed workflow and activity contracts with retry and timeout policy.
7132    #[track_caller]
7133    pub fn register_typed_workflow<I, O, F, Fut>(
7134        &mut self,
7135        workflow_type: impl Into<String>,
7136        handler: F,
7137    ) where
7138        I: DeserializeOwned + Send + 'static,
7139        O: Serialize + Send + 'static,
7140        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
7141        Fut: Future<Output = Result<O>> + Send + 'static,
7142    {
7143        let workflow_type = workflow_type.into();
7144        if !self.admit_registration::<F>(
7145            RegistrationKind::Workflow,
7146            None,
7147            &workflow_type,
7148            "register_typed_workflow",
7149        ) {
7150            return;
7151        }
7152        let handler_name = workflow_type.clone();
7153        let handler = Arc::new(handler);
7154        self.workflows.insert(
7155            workflow_type,
7156            RegisteredWorkflow {
7157                execute: Arc::new(move |ctx, input| {
7158                    let input = decode_workflow_entry::<I>(input, &handler_name)?;
7159                    let handler = Arc::clone(&handler);
7160                    let handler_name = handler_name.clone();
7161                    Ok(Box::pin(async move {
7162                        let result = handler(ctx, input).await?;
7163                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7164                    }))
7165                }),
7166                replay: None,
7167                state_type: None,
7168                definition_fingerprint: None,
7169            },
7170        );
7171    }
7172
7173    /// Register a workflow on the lossless fixed Avro Value surface.
7174    #[track_caller]
7175    pub fn register_workflow_avro_value<F, Fut>(
7176        &mut self,
7177        workflow_type: impl Into<String>,
7178        handler: F,
7179    ) where
7180        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
7181        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7182    {
7183        let workflow_type = workflow_type.into();
7184        if !self.admit_registration::<F>(
7185            RegistrationKind::Workflow,
7186            None,
7187            &workflow_type,
7188            "register_workflow_avro_value",
7189        ) {
7190            return;
7191        }
7192        self.workflows.insert(
7193            workflow_type,
7194            RegisteredWorkflow {
7195                execute: Arc::new(move |ctx, input| Ok(Box::pin(handler(ctx, input)))),
7196                replay: None,
7197                state_type: None,
7198                definition_fingerprint: None,
7199            },
7200        );
7201    }
7202
7203    /// Register a workflow whose typed instance state can be reconstructed for queries.
7204    ///
7205    /// `state_factory` creates a fresh instance for every normal workflow task and
7206    /// query replay. The workflow handler is the single source of truth for state
7207    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7208    /// resolve. Query replay runs this same handler over committed history and
7209    /// discards any commands it would emit.
7210    #[track_caller]
7211    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7212        &mut self,
7213        workflow_type: impl Into<String>,
7214        state_factory: Factory,
7215        handler: F,
7216    ) where
7217        S: Clone + Send + Sync + 'static,
7218        Factory: Fn() -> S + Send + Sync + 'static,
7219        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7220        Fut: Future<Output = Result<Value>> + Send + 'static,
7221    {
7222        let workflow_type = workflow_type.into();
7223        if !self.admit_registration::<F>(
7224            RegistrationKind::Workflow,
7225            None,
7226            &workflow_type,
7227            "register_replayed_workflow",
7228        ) {
7229            return;
7230        }
7231        let state_factory = Arc::new(state_factory);
7232        let handler = Arc::new(handler);
7233
7234        let execute_factory = Arc::clone(&state_factory);
7235        let execute_handler = Arc::clone(&handler);
7236        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7237            let state = WorkflowInstance::new(execute_factory());
7238            let handler = Arc::clone(&execute_handler);
7239            Ok(Box::pin(async move {
7240                let result = handler(ctx, input.into_json()?, state).await?;
7241                AvroValue::from_serialize(&result)
7242            }) as WorkflowFuture)
7243        });
7244
7245        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7246            let state = WorkflowInstance::new(state_factory());
7247            let snapshot_state = state.clone();
7248            let snapshot: WorkflowStateSnapshot =
7249                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7250            let replay_handler = Arc::clone(&handler);
7251            let future = async move {
7252                let result = replay_handler(ctx, input.into_json()?, state).await?;
7253                AvroValue::from_serialize(&result)
7254            };
7255            Ok(ReplayedWorkflowInvocation {
7256                future: Box::pin(future),
7257                snapshot,
7258            })
7259        });
7260
7261        self.workflows.insert(
7262            workflow_type,
7263            RegisteredWorkflow {
7264                execute,
7265                replay: Some(replay),
7266                state_type: Some(TypeId::of::<S>()),
7267                definition_fingerprint: None,
7268            },
7269        );
7270    }
7271
7272    /// Register a replayable workflow with one Serde request value and result.
7273    ///
7274    /// Normal task execution and instance-state query replay both decode and
7275    /// encode through the fixed Avro Value codec. The state factory and handler
7276    /// otherwise follow [`Worker::register_replayed_workflow`].
7277    #[track_caller]
7278    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7279        &mut self,
7280        workflow_type: impl Into<String>,
7281        state_factory: Factory,
7282        handler: F,
7283    ) where
7284        I: DeserializeOwned + Send + 'static,
7285        O: Serialize + Send + 'static,
7286        S: Clone + Send + Sync + 'static,
7287        Factory: Fn() -> S + Send + Sync + 'static,
7288        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7289        Fut: Future<Output = Result<O>> + Send + 'static,
7290    {
7291        let workflow_type = workflow_type.into();
7292        if !self.admit_registration::<F>(
7293            RegistrationKind::Workflow,
7294            None,
7295            &workflow_type,
7296            "register_typed_replayed_workflow",
7297        ) {
7298            return;
7299        }
7300        let state_factory = Arc::new(state_factory);
7301        let handler = Arc::new(handler);
7302
7303        let execute_name = workflow_type.clone();
7304        let execute_factory = Arc::clone(&state_factory);
7305        let execute_handler = Arc::clone(&handler);
7306        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7307            let input = decode_workflow_entry::<I>(input, &execute_name)?;
7308            let state = WorkflowInstance::new(execute_factory());
7309            let handler = Arc::clone(&execute_handler);
7310            let handler_name = execute_name.clone();
7311            Ok(Box::pin(async move {
7312                let result = handler(ctx, input, state).await?;
7313                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7314            }) as WorkflowFuture)
7315        });
7316
7317        let replay_name = workflow_type.clone();
7318        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7319            let input = decode_workflow_entry::<I>(input, &replay_name)?;
7320            let state = WorkflowInstance::new(state_factory());
7321            let snapshot_state = state.clone();
7322            let snapshot: WorkflowStateSnapshot =
7323                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7324            let handler = Arc::clone(&handler);
7325            let handler_name = replay_name.clone();
7326            let future = async move {
7327                let result = handler(ctx, input, state).await?;
7328                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7329            };
7330            Ok(ReplayedWorkflowInvocation {
7331                future: Box::pin(future),
7332                snapshot,
7333            })
7334        });
7335
7336        self.workflows.insert(
7337            workflow_type,
7338            RegisteredWorkflow {
7339                execute,
7340                replay: Some(replay),
7341                state_type: Some(TypeId::of::<S>()),
7342                definition_fingerprint: None,
7343            },
7344        );
7345    }
7346
7347    /// Declare the signal names consumed by a registered workflow.
7348    ///
7349    /// Call this after registering the workflow and before starting the worker.
7350    /// Names read through `wait_signal` or `signals` need a declaration for
7351    /// Server command admission. Arguments remain arbitrary positional values,
7352    /// including lossless Avro values. This replaces the previous declaration;
7353    /// an empty slice declares no signals. Names are sorted and deduplicated.
7354    /// Existing runs retain the declarations captured when they started.
7355    pub fn declare_workflow_signals(
7356        &mut self,
7357        workflow_type: &str,
7358        signal_names: &[&str],
7359    ) -> Result<()> {
7360        if !self.workflows.contains_key(workflow_type) {
7361            return Err(Error::Codec(format!(
7362                "workflow type {workflow_type:?} is not registered"
7363            )));
7364        }
7365        if signal_names
7366            .iter()
7367            .any(|name| name.is_empty() || *name != name.trim())
7368        {
7369            return Err(Error::Codec(
7370                "signal names must be non-empty and have no surrounding whitespace".into(),
7371            ));
7372        }
7373        let mut names = signal_names
7374            .iter()
7375            .map(|name| (*name).to_string())
7376            .collect::<Vec<_>>();
7377        names.sort();
7378        names.dedup();
7379        self.signals.insert(workflow_type.to_string(), names);
7380        Ok(())
7381    }
7382
7383    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7384    ///
7385    /// Supply `include_str!` values for the workflow body and every helper whose
7386    /// behavior can affect replay. Register the workflow once, then set its
7387    /// identity before starting the worker. Duplicate registrations are invalid. The server
7388    /// rejects reusing a worker ID when its prior fingerprint disappears.
7389    /// Workflows without source identity remain runnable but cannot be safely redriven.
7390    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7391    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7392    pub fn set_workflow_definition_sources(
7393        &mut self,
7394        workflow_type: &str,
7395        sources: &[&str],
7396    ) -> Result<()> {
7397        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7398            return Err(Error::Codec(
7399                "workflow definition sources must be non-empty".to_string(),
7400            ));
7401        }
7402        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7403            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7404        })?;
7405        let mut hasher = Sha256::new();
7406        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7407        hasher.update((workflow_type.len() as u64).to_be_bytes());
7408        hasher.update(workflow_type.as_bytes());
7409        for source in sources {
7410            hasher.update((source.len() as u64).to_be_bytes());
7411            hasher.update(source.as_bytes());
7412        }
7413        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7414        Ok(())
7415    }
7416
7417    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7418    #[track_caller]
7419    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7420        &mut self,
7421        workflow_type: impl Into<String>,
7422        state_factory: Factory,
7423        handler: F,
7424    ) where
7425        S: Clone + Send + Sync + 'static,
7426        Factory: Fn() -> S + Send + Sync + 'static,
7427        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7428        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7429    {
7430        let workflow_type = workflow_type.into();
7431        if !self.admit_registration::<F>(
7432            RegistrationKind::Workflow,
7433            None,
7434            &workflow_type,
7435            "register_replayed_workflow_avro_value",
7436        ) {
7437            return;
7438        }
7439        let state_factory = Arc::new(state_factory);
7440        let handler = Arc::new(handler);
7441
7442        let execute_factory = Arc::clone(&state_factory);
7443        let execute_handler = Arc::clone(&handler);
7444        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7445            let state = WorkflowInstance::new(execute_factory());
7446            Ok(Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture)
7447        });
7448
7449        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7450            let state = WorkflowInstance::new(state_factory());
7451            let snapshot_state = state.clone();
7452            let snapshot: WorkflowStateSnapshot =
7453                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7454            Ok(ReplayedWorkflowInvocation {
7455                future: Box::pin(handler(ctx, input, state)),
7456                snapshot,
7457            })
7458        });
7459
7460        self.workflows.insert(
7461            workflow_type,
7462            RegisteredWorkflow {
7463                execute,
7464                replay: Some(replay),
7465                state_type: Some(TypeId::of::<S>()),
7466                definition_fingerprint: None,
7467            },
7468        );
7469    }
7470
7471    #[track_caller]
7472    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7473    where
7474        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7475        Fut: Future<Output = Result<Value>> + Send + 'static,
7476    {
7477        let activity_type = activity_type.into();
7478        if !self.admit_registration::<F>(
7479            RegistrationKind::Activity,
7480            None,
7481            &activity_type,
7482            "register_activity",
7483        ) {
7484            return;
7485        }
7486        let handler = Arc::new(handler);
7487        self.activities.insert(
7488            activity_type,
7489            Arc::new(move |ctx, args| {
7490                let handler = Arc::clone(&handler);
7491                Box::pin(async move {
7492                    let result = handler(ctx, args.into_json()?).await?;
7493                    AvroValue::from_serialize(&result)
7494                })
7495            }),
7496        );
7497    }
7498
7499    /// Register an activity with one Serde request value and a Serde result.
7500    ///
7501    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7502    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7503    /// with the activity name and Rust type.
7504    #[track_caller]
7505    pub fn register_typed_activity<I, O, F, Fut>(
7506        &mut self,
7507        activity_type: impl Into<String>,
7508        handler: F,
7509    ) where
7510        I: DeserializeOwned + Send + 'static,
7511        O: Serialize + Send + 'static,
7512        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
7513        Fut: Future<Output = Result<O>> + Send + 'static,
7514    {
7515        let activity_type = activity_type.into();
7516        if !self.admit_registration::<F>(
7517            RegistrationKind::Activity,
7518            None,
7519            &activity_type,
7520            "register_typed_activity",
7521        ) {
7522            return;
7523        }
7524        let handler_name = activity_type.clone();
7525        let handler = Arc::new(handler);
7526        self.activities.insert(
7527            activity_type,
7528            Arc::new(move |ctx, input| {
7529                let handler = Arc::clone(&handler);
7530                let handler_name = handler_name.clone();
7531                Box::pin(async move {
7532                    let input =
7533                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
7534                    let result = handler(ctx, input).await?;
7535                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
7536                })
7537            }),
7538        );
7539    }
7540
7541    /// Register an activity on the lossless fixed Avro Value surface.
7542    #[track_caller]
7543    pub fn register_activity_avro_value<F, Fut>(
7544        &mut self,
7545        activity_type: impl Into<String>,
7546        handler: F,
7547    ) where
7548        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
7549        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7550    {
7551        let activity_type = activity_type.into();
7552        if !self.admit_registration::<F>(
7553            RegistrationKind::Activity,
7554            None,
7555            &activity_type,
7556            "register_activity_avro_value",
7557        ) {
7558            return;
7559        }
7560        self.activities.insert(
7561            activity_type,
7562            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7563        );
7564    }
7565
7566    /// Register a named, read-only query handler for a workflow type.
7567    ///
7568    /// The workflow type must also be registered with [`Worker::register_workflow`]
7569    /// before the worker runs. The handler receives only an immutable committed
7570    /// state snapshot and normalized query arguments.
7571    #[track_caller]
7572    pub fn register_query<F, Fut>(
7573        &mut self,
7574        workflow_type: impl Into<String>,
7575        query_name: impl Into<String>,
7576        handler: F,
7577    ) where
7578        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7579        Fut: Future<Output = Result<Value>> + Send + 'static,
7580    {
7581        let workflow_type = workflow_type.into();
7582        let query_name = query_name.into();
7583        if !self.admit_registration::<F>(
7584            RegistrationKind::Query,
7585            Some(&workflow_type),
7586            &query_name,
7587            "register_query",
7588        ) {
7589            return;
7590        }
7591        let handler = Arc::new(handler);
7592        self.queries.entry(workflow_type).or_default().insert(
7593            query_name,
7594            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
7595                let handler = Arc::clone(&handler);
7596                Box::pin(async move {
7597                    let result = handler(ctx, args.into_json()?).await?;
7598                    AvroValue::from_serialize(&result)
7599                })
7600            })),
7601        );
7602    }
7603
7604    /// Register a query handler on the lossless fixed Avro Value surface.
7605    #[track_caller]
7606    pub fn register_query_avro_value<F, Fut>(
7607        &mut self,
7608        workflow_type: impl Into<String>,
7609        query_name: impl Into<String>,
7610        handler: F,
7611    ) where
7612        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7613        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7614    {
7615        let workflow_type = workflow_type.into();
7616        let query_name = query_name.into();
7617        if !self.admit_registration::<F>(
7618            RegistrationKind::Query,
7619            Some(&workflow_type),
7620            &query_name,
7621            "register_query_avro_value",
7622        ) {
7623            return;
7624        }
7625        self.queries.entry(workflow_type).or_default().insert(
7626            query_name,
7627            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
7628        );
7629    }
7630
7631    /// Register a named query against deterministically replayed instance state.
7632    ///
7633    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
7634    /// same state type `S`. The handler receives an immutable, detached state
7635    /// clone, so successful and failed queries cannot affect workflow execution
7636    /// or the state reconstructed by a later query.
7637    #[track_caller]
7638    pub fn register_replayed_query<S, F, Fut>(
7639        &mut self,
7640        workflow_type: impl Into<String>,
7641        query_name: impl Into<String>,
7642        handler: F,
7643    ) where
7644        S: Clone + Send + Sync + 'static,
7645        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
7646        Fut: Future<Output = Result<Value>> + Send + 'static,
7647    {
7648        let workflow_type = workflow_type.into();
7649        let query_name = query_name.into();
7650        if !self.admit_registration::<F>(
7651            RegistrationKind::Query,
7652            Some(&workflow_type),
7653            &query_name,
7654            "register_replayed_query",
7655        ) {
7656            return;
7657        }
7658        let handler = Arc::new(handler);
7659        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7660            let state = state.downcast::<S>().map_err(|_| {
7661                "registered query state type does not match the replayed workflow state".to_string()
7662            })?;
7663            let handler = Arc::clone(&handler);
7664            Ok(Box::pin(async move {
7665                let result = handler(ctx, state, args.into_json()?).await?;
7666                AvroValue::from_serialize(&result)
7667            }))
7668        });
7669
7670        self.queries.entry(workflow_type).or_default().insert(
7671            query_name,
7672            RegisteredQuery::Replayed {
7673                state_type: TypeId::of::<S>(),
7674                handler: erased_handler,
7675            },
7676        );
7677    }
7678
7679    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7680    #[track_caller]
7681    pub fn register_replayed_query_avro_value<S, F, Fut>(
7682        &mut self,
7683        workflow_type: impl Into<String>,
7684        query_name: impl Into<String>,
7685        handler: F,
7686    ) where
7687        S: Clone + Send + Sync + 'static,
7688        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7689        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7690    {
7691        let workflow_type = workflow_type.into();
7692        let query_name = query_name.into();
7693        if !self.admit_registration::<F>(
7694            RegistrationKind::Query,
7695            Some(&workflow_type),
7696            &query_name,
7697            "register_replayed_query_avro_value",
7698        ) {
7699            return;
7700        }
7701        let handler = Arc::new(handler);
7702        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7703            let state = state.downcast::<S>().map_err(|_| {
7704                "registered query state type does not match the replayed workflow state".to_string()
7705            })?;
7706            Ok(Box::pin(handler(ctx, state, args)))
7707        });
7708
7709        self.queries.entry(workflow_type).or_default().insert(
7710            query_name,
7711            RegisteredQuery::Replayed {
7712                state_type: TypeId::of::<S>(),
7713                handler: erased_handler,
7714            },
7715        );
7716    }
7717
7718    /// Register a synchronous workflow update handler.
7719    #[track_caller]
7720    pub fn register_update<F, Fut>(
7721        &mut self,
7722        workflow_type: impl Into<String>,
7723        update_name: impl Into<String>,
7724        handler: F,
7725    ) where
7726        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7727        Fut: Future<Output = Result<Value>> + Send + 'static,
7728    {
7729        let workflow_type = workflow_type.into();
7730        let update_name = update_name.into();
7731        if !self.admit_registration::<F>(
7732            RegistrationKind::Update,
7733            Some(&workflow_type),
7734            &update_name,
7735            "register_update",
7736        ) {
7737            return;
7738        }
7739        let handler = Arc::new(handler);
7740        self.updates.entry(workflow_type).or_default().insert(
7741            update_name,
7742            Arc::new(move |ctx, args| {
7743                let handler = Arc::clone(&handler);
7744                Box::pin(async move {
7745                    let result = handler(ctx, args.into_json()?).await?;
7746                    AvroValue::from_serialize(&result)
7747                })
7748            }),
7749        );
7750    }
7751
7752    /// Register an update handler on the lossless fixed Avro Value surface.
7753    #[track_caller]
7754    pub fn register_update_avro_value<F, Fut>(
7755        &mut self,
7756        workflow_type: impl Into<String>,
7757        update_name: impl Into<String>,
7758        handler: F,
7759    ) where
7760        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7761        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7762    {
7763        let workflow_type = workflow_type.into();
7764        let update_name = update_name.into();
7765        if !self.admit_registration::<F>(
7766            RegistrationKind::Update,
7767            Some(&workflow_type),
7768            &update_name,
7769            "register_update_avro_value",
7770        ) {
7771            return;
7772        }
7773        self.updates.entry(workflow_type).or_default().insert(
7774            update_name,
7775            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7776        );
7777    }
7778
7779    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7780        self.validate_registration()?;
7781        self.nexus_registration_confirmed
7782            .store(false, Ordering::SeqCst);
7783        self.query_authority_confirmed
7784            .store(false, Ordering::SeqCst);
7785        if self.nexus_cooperative_cancellation_enabled {
7786            let info: Value = self
7787                .client
7788                .request_json(
7789                    reqwest::Method::GET,
7790                    "/cluster/info",
7791                    RequestProtocol::Worker("1.20"),
7792                    Option::<&Value>::None,
7793                )
7794                .await?;
7795            if !nexus::installed_cooperation(&info["worker_protocol"]["server_capabilities"]) {
7796                return Err(Error::CooperativeCancellationUnavailable(
7797                    "nexus_cooperative_cancellation_not_supported: Server must advertise the installed workflow_run bridge".into(),
7798                ));
7799            }
7800        }
7801        if self.require_query_task_authority {
7802            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
7803                return Err(Error::WorkerLoop(
7804                    "query authority requires worker protocol 1.20".into(),
7805                ));
7806            }
7807            // Discovery uses the Worker credential, including worker-only Clients.
7808            let discovery: Value = self
7809                .client
7810                .request_json_unresolved_with_timeout::<Value, Value>(
7811                    reqwest::Method::GET,
7812                    "/cluster/info",
7813                    RequestProtocol::Worker("1.20"),
7814                    None,
7815                    Duration::from_secs(5),
7816                )
7817                .await?;
7818            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
7819                return Err(Error::WorkerLoop(
7820                    "runtime does not advertise query_task_authority".into(),
7821                ));
7822            }
7823        }
7824        self.sticky_registration_confirmed
7825            .store(false, Ordering::SeqCst);
7826        self.session_registration_confirmed
7827            .store(false, Ordering::SeqCst);
7828        for capability in &self.resource_capabilities {
7829            worker_session::validate_resource_capability(capability)?;
7830        }
7831        self.local_registration_confirmed
7832            .store(false, Ordering::SeqCst);
7833        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7834            return Err(Error::CooperativeCancellationUnavailable(
7835                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7836            ));
7837        }
7838        let mut command_contracts = serde_json::Map::new();
7839        for workflow_type in self.workflows.keys() {
7840            let mut queries = self
7841                .queries
7842                .get(workflow_type)
7843                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7844                .unwrap_or_default();
7845            queries.sort();
7846            let mut updates = self
7847                .updates
7848                .get(workflow_type)
7849                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7850                .unwrap_or_default();
7851            updates.sort();
7852            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
7853            command_contracts.insert(
7854                workflow_type.clone(),
7855                json!({
7856                    "queries": queries,
7857                    "query_contracts": argument_vector_contracts(&queries),
7858                    "signals": signals,
7859                    "signal_contracts": argument_vector_contracts(&signals),
7860                    "updates": updates,
7861                    "update_contracts": argument_vector_contracts(&updates),
7862                    "update_validators": [],
7863                }),
7864            );
7865        }
7866
7867        self.cooperative_registration_confirmed
7868            .store(false, Ordering::SeqCst);
7869        let response = self
7870            .client
7871            .register_worker_with_definition_fingerprints(
7872                &self.worker_id,
7873                &self.task_queue,
7874                self.workflows.keys().cloned().collect(),
7875                self.activities.keys().cloned().collect(),
7876                self.max_concurrent_workflow_tasks,
7877                self.max_concurrent_activity_tasks,
7878                [
7879                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7880                    Some("workflow_entry_arguments_validation".to_string()),
7881                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7882                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7883                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7884                    self.client
7885                        .local_activities_enabled
7886                        .then(|| "local_activities".to_string()),
7887                    self.client
7888                        .worker_sessions_enabled
7889                        .then(|| "worker_sessions".to_string()),
7890                    self.client
7891                        .sticky_cache
7892                        .is_some()
7893                        .then(|| "sticky_execution".to_string()),
7894                    self.cooperative_cancellation_enabled
7895                        .then(|| "cooperative_cancellation".to_string()),
7896                    self.nexus_cooperative_cancellation_enabled
7897                        .then(|| "nexus_cooperative_cancellation".to_string()),
7898                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7899                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7900                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7901                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7902                ]
7903                .into_iter()
7904                .flatten()
7905                .chain(self.resource_capabilities.iter().cloned())
7906                .collect(),
7907                Value::Object(command_contracts),
7908                Some(
7909                    self.workflows
7910                        .iter()
7911                        .filter_map(|(workflow_type, workflow)| {
7912                            workflow
7913                                .definition_fingerprint
7914                                .as_ref()
7915                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7916                        })
7917                        .collect(),
7918                ),
7919            )
7920            .await?;
7921        if self.cooperative_cancellation_enabled && response.registered {
7922            self.cooperative_registration_confirmed
7923                .store(true, Ordering::SeqCst);
7924        }
7925        if self.nexus_cooperative_cancellation_enabled && response.registered {
7926            self.nexus_registration_confirmed
7927                .store(true, Ordering::SeqCst);
7928        }
7929        if self.client.local_activities_enabled && response.registered {
7930            self.local_registration_confirmed
7931                .store(true, Ordering::SeqCst);
7932        }
7933        if self.client.worker_sessions_enabled && response.registered {
7934            self.session_registration_confirmed
7935                .store(true, Ordering::SeqCst);
7936        }
7937        if self.client.sticky_cache.is_some() && response.registered {
7938            self.sticky_registration_confirmed
7939                .store(true, Ordering::SeqCst);
7940        }
7941        self.query_authority_confirmed.store(
7942            response.registered
7943                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
7944                && response
7945                    .server_capabilities
7946                    .as_ref()
7947                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
7948            Ordering::SeqCst,
7949        );
7950        Ok(response)
7951    }
7952
7953    /// Run until shutdown or a terminal worker error occurs.
7954    ///
7955    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7956    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7957    /// authentication, protocol, and other non-retryable failures are returned.
7958    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7959    /// poll and heartbeat outages beyond the ordinary retry budget.
7960    pub async fn run(&self) -> Result<()> {
7961        self.run_until(std::future::pending::<()>()).await
7962    }
7963
7964    /// Run until `shutdown` resolves or a terminal worker error occurs.
7965    ///
7966    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7967    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7968    where
7969        F: Future<Output = ()>,
7970    {
7971        let _clear_cache_on_drop =
7972            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
7973        let stop = Arc::new(AtomicBool::new(false));
7974        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7975        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7976        worker.run_stop = Some(Arc::clone(&stop));
7977        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7978        tokio::pin!(run);
7979        tokio::pin!(shutdown);
7980        tokio::select! {
7981            result = &mut run => result,
7982            _ = &mut shutdown => {
7983                stop.store(true, Ordering::SeqCst);
7984                run.await
7985            }
7986        }
7987    }
7988
7989    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7990        let mut worker = self.clone();
7991        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7992            policy: self.retry_policy,
7993            stop,
7994            workflow_completion_retry_deadline: None,
7995        });
7996        worker
7997    }
7998
7999    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
8000        let registration = self.register().await?;
8001        if !registration.registered {
8002            return Err(Error::WorkerLoop(format!(
8003                "worker registration for {:?} was not accepted",
8004                self.worker_id
8005            )));
8006        }
8007        let registered_worker_id = registration.worker_id.clone();
8008        let primary = self.run_registered_until(stop, registration).await;
8009        let primary = match (primary, self.close_worker_sessions().await) {
8010            (Ok(()), result) => result,
8011            (Err(error), Ok(())) => Err(error),
8012            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
8013                primary: Box::new(primary),
8014                deregistration: Box::new(close),
8015            }),
8016        };
8017        self.session_registration_confirmed
8018            .store(false, Ordering::SeqCst);
8019        self.cooperative_registration_confirmed
8020            .store(false, Ordering::SeqCst);
8021        self.local_registration_confirmed
8022            .store(false, Ordering::SeqCst);
8023        let deregistration = self
8024            .client
8025            .deregister_worker_registration(&registered_worker_id)
8026            .await;
8027        self.sticky_registration_confirmed
8028            .store(false, Ordering::SeqCst);
8029        self.client.clear_sticky_cache()?;
8030
8031        match (primary, deregistration) {
8032            (Ok(()), Ok(_)) => Ok(()),
8033            (Ok(()), Err(deregistration)) => Err(deregistration),
8034            (Err(primary), Ok(_)) => Err(primary),
8035            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
8036                primary: Box::new(primary),
8037                deregistration: Box::new(deregistration),
8038            }),
8039        }
8040    }
8041
8042    async fn run_registered_until(
8043        &self,
8044        stop: Arc<AtomicBool>,
8045        registration: RegisterWorkerResponse,
8046    ) -> Result<()> {
8047        if self.require_query_task_authority
8048            && !self.query_authority_confirmed.load(Ordering::SeqCst)
8049        {
8050            return Err(Error::WorkerLoop(
8051                "registration did not confirm query_task_authority".into(),
8052            ));
8053        }
8054        let heartbeat_interval = Duration::from_secs(
8055            registration
8056                .heartbeat_interval_seconds
8057                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
8058        );
8059        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
8060        // from the completion of the preceding attempt, including its bounded
8061        // retries. A fixed-epoch interval can leave an already-due tick queued
8062        // while an acknowledgement is slow, producing a catch-up heartbeat as
8063        // soon as that request completes.
8064        let heartbeat = tokio::time::sleep(Duration::ZERO);
8065        tokio::pin!(heartbeat);
8066        // Poll responses may already have leased server-side work by the time
8067        // they become ready, so each poller owns its responses through
8068        // completion or failure instead of racing raw polls in this select.
8069        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
8070            let worker = self.clone();
8071            let stop = Arc::clone(&stop);
8072            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
8073        });
8074        let mut activity_poller = (!self.activities.is_empty()).then(|| {
8075            let worker = self.clone();
8076            let stop = Arc::clone(&stop);
8077            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
8078        });
8079        let mut query_poller = (!self.queries.is_empty()).then(|| {
8080            let worker = self.clone();
8081            let stop = Arc::clone(&stop);
8082            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
8083        });
8084
8085        loop {
8086            tokio::select! {
8087                _ = wait_for_worker_stop(&stop) => {
8088                    stop.store(true, Ordering::SeqCst);
8089                    break;
8090                }
8091                _ = &mut heartbeat => {
8092                    let result = self.retry_worker_operation(|| {
8093                        self.client.heartbeat_worker_with_sessions(
8094                            &self.worker_id,
8095                            self.max_concurrent_workflow_tasks,
8096                            self.max_concurrent_activity_tasks,
8097                            self.client.worker_sessions_enabled.then(|| self.session_available()),
8098                        )
8099                    }).await;
8100                    heartbeat
8101                        .as_mut()
8102                        .reset(tokio::time::Instant::now() + heartbeat_interval);
8103                    match result {
8104                        Ok(Some(acknowledgement)) => {
8105                            if let Some(observer) = &self.heartbeat_observer {
8106                                observer(&WorkerHeartbeatObservation {
8107                                    worker_id: self.worker_id.clone(),
8108                                    task_queue: self.task_queue.clone(),
8109                                    acknowledged_at_unix_millis: SystemTime::now()
8110                                        .duration_since(UNIX_EPOCH)
8111                                        .unwrap_or_default()
8112                                        .as_millis()
8113                                        .min(u64::MAX as u128)
8114                                        as u64,
8115                                    acknowledgement,
8116                                });
8117                            }
8118                        }
8119                        Ok(None) => break,
8120                        Err(error) => {
8121                            stop.store(true, Ordering::SeqCst);
8122                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
8123                            return Err(error);
8124                        }
8125                    }
8126                }
8127                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
8128                    workflow_poller = None;
8129                    let stopped_by_server = stop.load(Ordering::SeqCst);
8130                    stop.store(true, Ordering::SeqCst);
8131                    let poller_result = optional_poller_result("workflow", result);
8132                    let join_result =
8133                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8134                    poller_result?;
8135                    join_result?;
8136                    if stopped_by_server {
8137                        return Ok(());
8138                    }
8139                    return Err(Error::WorkerLoop(
8140                        "workflow poller stopped unexpectedly".to_string(),
8141                    ));
8142                }
8143                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
8144                    activity_poller = None;
8145                    let stopped_by_server = stop.load(Ordering::SeqCst);
8146                    stop.store(true, Ordering::SeqCst);
8147                    let poller_result = optional_poller_result("activity", result);
8148                    let join_result =
8149                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8150                    poller_result?;
8151                    join_result?;
8152                    if stopped_by_server {
8153                        return Ok(());
8154                    }
8155                    return Err(Error::WorkerLoop(
8156                        "activity poller stopped unexpectedly".to_string(),
8157                    ));
8158                }
8159                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
8160                    query_poller = None;
8161                    let stopped_by_server = stop.load(Ordering::SeqCst);
8162                    stop.store(true, Ordering::SeqCst);
8163                    let poller_result = optional_poller_result("query", result);
8164                    let join_result =
8165                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8166                    poller_result?;
8167                    join_result?;
8168                    if stopped_by_server {
8169                        return Ok(());
8170                    }
8171                    return Err(Error::WorkerLoop(
8172                        "query poller stopped unexpectedly".to_string(),
8173                    ));
8174                }
8175            }
8176        }
8177
8178        join_pollers(
8179            workflow_poller.take(),
8180            activity_poller.take(),
8181            query_poller.take(),
8182        )
8183        .await
8184    }
8185
8186    /// Poll and settle at most one task from each enabled task family.
8187    ///
8188    /// A workflow may reach its server-enforced run deadline while this worker
8189    /// holds a task. When the completion endpoint authoritatively rejects that
8190    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
8191    /// terminal `run_status=failed`, the workflow tick is considered settled:
8192    /// the late command was not recorded and cannot replace the terminal run.
8193    /// Every other completion rejection remains an error. This worker-level
8194    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
8195    /// only bounds how long a client waits for a result.
8196    ///
8197    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
8198    /// the original [`Error::Http`] status and response body.
8199    pub async fn run_once(&self) -> Result<usize> {
8200        self.validate_registration()?;
8201        if self.client.worker_sessions_enabled {
8202            self.require_session_registration()?;
8203        }
8204        if self.cooperative_cancellation_enabled
8205            && !self
8206                .cooperative_registration_confirmed
8207                .load(Ordering::SeqCst)
8208        {
8209            return Err(Error::CooperativeCancellationUnavailable(
8210                "register this cooperative worker before polling tasks".into(),
8211            ));
8212        }
8213        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
8214        let mut handled = 0;
8215        match worker.poll_workflow_once().await? {
8216            ManagedPollOutcome::Handled => handled += 1,
8217            ManagedPollOutcome::Stop => return Ok(handled),
8218            ManagedPollOutcome::Idle => {}
8219        }
8220        match worker.poll_activity_once().await? {
8221            ManagedPollOutcome::Handled => handled += 1,
8222            ManagedPollOutcome::Stop => return Ok(handled),
8223            ManagedPollOutcome::Idle => {}
8224        }
8225        if !self.queries.is_empty() {
8226            match worker.poll_query_once().await? {
8227                ManagedPollOutcome::Handled => handled += 1,
8228                ManagedPollOutcome::Stop => return Ok(handled),
8229                ManagedPollOutcome::Idle => {}
8230            }
8231        }
8232        Ok(handled)
8233    }
8234
8235    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
8236        if self.client.sticky_cache.is_some()
8237            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
8238        {
8239            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
8240        }
8241        if self.client.local_activities_enabled
8242            && !self.local_registration_confirmed.load(Ordering::SeqCst)
8243        {
8244            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
8245        }
8246        if self.cooperative_cancellation_enabled {
8247            return self.poll_cooperative_workflow_once().await;
8248        }
8249        let poll_request_id = unique_request_id("rust-workflow-poll");
8250        let response = self
8251            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
8252            .await;
8253        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
8254            return Ok(ManagedPollOutcome::Idle);
8255        };
8256        if response.outcome().should_stop() {
8257            return Ok(ManagedPollOutcome::Stop);
8258        }
8259        let memo_updates_supported =
8260            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
8261        let Some(task) = response.task else {
8262            return Ok(ManagedPollOutcome::Idle);
8263        };
8264
8265        let task_id = task.task_id.clone();
8266        let attempt = task.workflow_task_attempt;
8267        let run_id = task.run_id.clone();
8268        let lease_owner = task
8269            .lease_owner
8270            .clone()
8271            .unwrap_or_else(|| self.worker_id.clone());
8272
8273        let decision = match self.execute_workflow_with_local_activities(task).await {
8274            Ok(Some(decision)) => Ok(decision),
8275            Ok(None) => return Ok(ManagedPollOutcome::Handled),
8276            Err(error) => Err(error),
8277        };
8278        self.settle_workflow_task_decision(
8279            &task_id,
8280            &lease_owner,
8281            attempt,
8282            run_id.as_deref(),
8283            decision,
8284            memo_updates_supported,
8285            snapshot,
8286        )
8287        .await
8288    }
8289
8290    #[allow(clippy::too_many_arguments)]
8291    async fn settle_workflow_task_decision(
8292        &self,
8293        task_id: &str,
8294        lease_owner: &str,
8295        attempt: u64,
8296        run_id: Option<&str>,
8297        decision: Result<WorkflowTaskDecision>,
8298        memo_updates_supported: bool,
8299        snapshot: Option<sticky_worker::StickySnapshot>,
8300    ) -> Result<ManagedPollOutcome> {
8301        match decision {
8302            Ok(decision)
8303                if decision.cancellation_delivery.is_some()
8304                    || decision.cancellation_scope_delivery.is_some()
8305                    || decision.cancellation_scope_opening.is_some() =>
8306            {
8307                return Err(Error::CooperativeCancellationUnavailable(
8308                    "worker cancellation delivery has not been negotiated".into(),
8309                ));
8310            }
8311            Ok(decision)
8312                if commands_use_workflow_memo_updates(&decision.commands)
8313                    && !memo_updates_supported =>
8314            {
8315                self.client
8316                    .fail_workflow_task(
8317                        task_id,
8318                        lease_owner,
8319                        attempt,
8320                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8321                    )
8322                    .await?;
8323            }
8324            Ok(decision) if decision.commands.is_empty() => {
8325                // A replay can consume a recorded pending durable command
8326                // without producing a new command. The standalone protocol
8327                // acknowledges that state through the typed waiting outcome;
8328                // an empty completion is rejected by servers that require at
8329                // least one executable command.
8330                self.client
8331                    .fail_workflow_task_with_type(
8332                        task_id,
8333                        lease_owner,
8334                        attempt,
8335                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8336                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8337                    )
8338                    .await?;
8339            }
8340            Ok(decision) => {
8341                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8342                let completion = self
8343                    .client
8344                    .complete_workflow_task_with_message_streams(
8345                        task_id,
8346                        lease_owner,
8347                        attempt,
8348                        decision.commands,
8349                        decision.message_stream_cursors,
8350                        decision.message_stream_waits,
8351                        sticky_claim,
8352                    )
8353                    .await;
8354                if let Err(error) = completion {
8355                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8356                    if !workflow_task_completion_is_terminal_timeout(
8357                        &error, task_id, attempt, run_id,
8358                    ) {
8359                        return Err(error);
8360                    }
8361                }
8362            }
8363            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8364            Err(error) => {
8365                self.discard_sticky_snapshot(snapshot.as_ref())?;
8366                if matches!(
8367                    error,
8368                    Error::HandlerType {
8369                        handler_kind: HandlerKind::Workflow,
8370                        value_kind: HandlerValueKind::Input,
8371                        ..
8372                    }
8373                ) {
8374                    self.client
8375                        .fail_workflow_task_with_failure(
8376                            task_id,
8377                            lease_owner,
8378                            attempt,
8379                            json!({
8380                                "message": error.to_string(),
8381                                "type": "WorkflowEntryArgumentsMismatch",
8382                                "reason": "workflow_entry_arguments_mismatch",
8383                            }),
8384                        )
8385                        .await?;
8386                } else {
8387                    self.client
8388                        .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8389                        .await?;
8390                }
8391            }
8392        }
8393
8394        Ok(ManagedPollOutcome::Handled)
8395    }
8396
8397    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8398        while !stop.load(Ordering::SeqCst) {
8399            match self.poll_workflow_once().await {
8400                Ok(ManagedPollOutcome::Stop) => {
8401                    stop.store(true, Ordering::SeqCst);
8402                    break;
8403                }
8404                Err(error) => {
8405                    stop.store(true, Ordering::SeqCst);
8406                    return Err(error);
8407                }
8408                _ => {}
8409            }
8410        }
8411
8412        Ok(())
8413    }
8414
8415    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
8416        if self.client.worker_sessions_enabled {
8417            self.require_session_registration()?;
8418        }
8419        if self.cooperative_cancellation_enabled {
8420            return self.poll_cooperative_activity_once().await;
8421        }
8422        let poll_request_id = unique_request_id("rust-activity-poll");
8423        let response = self
8424            .retry_worker_operation(|| {
8425                self.client.poll_activity_task_response_with_request_id(
8426                    &self.worker_id,
8427                    &self.task_queue,
8428                    self.poll_timeout,
8429                    &poll_request_id,
8430                    0,
8431                )
8432            })
8433            .await;
8434        let response = match response {
8435            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8436            response => response,
8437        };
8438        let Some(response) = self.settle_worker_poll_response(response).await? else {
8439            return Ok(ManagedPollOutcome::Idle);
8440        };
8441        if response.outcome().should_stop() {
8442            return Ok(ManagedPollOutcome::Stop);
8443        }
8444        let Some(task) = response.task else {
8445            return Ok(ManagedPollOutcome::Idle);
8446        };
8447
8448        let session = self.track_session_task(task.worker_session.as_ref())?;
8449        let hydration_claim = task.hydration_claim;
8450        let task = task.task;
8451
8452        let task_id = task.task_id.clone();
8453        let attempt_id = task
8454            .activity_attempt_id
8455            .clone()
8456            .or(task.attempt_id.clone())
8457            .unwrap_or_default();
8458        let lease_owner = task
8459            .lease_owner
8460            .clone()
8461            .unwrap_or_else(|| self.worker_id.clone());
8462        let codec = task.payload_codec.clone();
8463        let result = self
8464            .execute_session_activity_task(task, session, hydration_claim.as_ref())
8465            .await;
8466        match result {
8467            Err(Error::ActivityExecutionAbandoned(_)) => {}
8468            Err(error) if activity_hydration::stopped(&error) => {}
8469            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
8470            Ok(value) => {
8471                let completion = self
8472                    .client
8473                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
8474                    .await;
8475                if let Err(error) = completion {
8476                    if !activity_task_rejection_is_final(&error) {
8477                        return Err(error);
8478                    }
8479                }
8480            }
8481            Err(error) => {
8482                let failure = self
8483                    .client
8484                    .fail_activity_task(
8485                        &task_id,
8486                        &attempt_id,
8487                        &lease_owner,
8488                        error.to_string(),
8489                        false,
8490                    )
8491                    .await;
8492                if let Err(error) = failure {
8493                    if !activity_task_rejection_is_final(&error) {
8494                        return Err(error);
8495                    }
8496                }
8497            }
8498        }
8499
8500        Ok(ManagedPollOutcome::Handled)
8501    }
8502
8503    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8504        // Each lane retains its leased response through callback settlement.
8505        // A bounded independent activity must not occupy the cleanup lane too.
8506        // Preserve the existing serial loop unless cooperation is enabled.
8507        let lane_count = if self.cooperative_cancellation_enabled {
8508            self.max_concurrent_activity_tasks
8509        } else {
8510            1
8511        };
8512        let mut lanes = FuturesUnordered::new();
8513        for _ in 0..lane_count {
8514            let worker = self.clone();
8515            let stop = Arc::clone(&stop);
8516            lanes.push(async move {
8517                while !stop.load(Ordering::SeqCst) {
8518                    match worker.poll_activity_once().await {
8519                        Ok(ManagedPollOutcome::Stop) => {
8520                            stop.store(true, Ordering::SeqCst);
8521                            break;
8522                        }
8523                        Err(error) => {
8524                            stop.store(true, Ordering::SeqCst);
8525                            return Err(error);
8526                        }
8527                        _ => {}
8528                    }
8529                }
8530                Ok(())
8531            });
8532        }
8533        // Join every lane before deregistration, including after one fails.
8534        let mut first_error = None;
8535        while let Some(result) = lanes.next().await {
8536            if let Err(error) = result {
8537                first_error.get_or_insert(error);
8538            }
8539        }
8540        first_error.map_or(Ok(()), Err)
8541    }
8542
8543    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
8544        let poll_request_id = unique_request_id("rust-query-poll");
8545        let response = self
8546            .retry_worker_operation(|| {
8547                let body = json!({"worker_id":self.worker_id,"task_queue":self.task_queue,
8548                    "poll_request_id":poll_request_id,
8549                    "timeout_seconds":long_poll_timeout_seconds(self.poll_timeout)});
8550                async move {
8551                    self.client
8552                        .poll_request_json_unresolved::<Value, Value>(
8553                            "/worker/query-tasks/poll",
8554                            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
8555                            &body,
8556                            self.poll_timeout + Duration::from_secs(5),
8557                            0,
8558                        )
8559                        .await
8560                }
8561            })
8562            .await;
8563        let Some(mut wire) = self.settle_worker_poll_response(response).await? else {
8564            return Ok(ManagedPollOutcome::Idle);
8565        };
8566        let authority = if wire.get("task").is_some_and(|task| !task.is_null()) {
8567            match query_authority::Authority::capture(&wire["task"], self) {
8568                Ok(authority) => authority,
8569                Err(_) => return Ok(ManagedPollOutcome::Handled),
8570            }
8571        } else {
8572            None
8573        };
8574        let loading = self.client.resolve_runtime_payloads(
8575            &mut wire,
8576            "/worker/query-tasks/poll",
8577            RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
8578        );
8579        match query_authority::Authority::protect(authority.as_ref(), self, loading).await {
8580            Err(_) => return Ok(ManagedPollOutcome::Handled),
8581            Ok(result) => result?,
8582        }
8583        let response: PollQueryTaskResponse = serde_json::from_value(wire)?;
8584        if response.outcome().should_stop() {
8585            return Ok(ManagedPollOutcome::Stop);
8586        }
8587        let Some(task) = response.task else {
8588            return Ok(ManagedPollOutcome::Idle);
8589        };
8590
8591        let query_task_id = task.query_task_id.clone();
8592        let attempt = task.query_task_attempt;
8593        let lease_owner = task
8594            .lease_owner
8595            .clone()
8596            .unwrap_or_else(|| self.worker_id.clone());
8597        let codec = task.payload_codec.clone();
8598
8599        let execution = query_authority::Authority::protect(
8600            authority.as_ref(),
8601            self,
8602            self.execute_query_task_with_authority(task, authority.as_ref()),
8603        )
8604        .await;
8605        let execution = match execution {
8606            Err(_) => return Ok(ManagedPollOutcome::Handled),
8607            Ok(Err(failure)) if failure.reason == "query_authority_lost" => {
8608                return Ok(ManagedPollOutcome::Handled)
8609            }
8610            Ok(result) => result,
8611        };
8612        match execution {
8613            Ok(value) => {
8614                let result_envelope = match encode_typed_envelope(&value, &codec) {
8615                    Ok(result_envelope) => result_envelope,
8616                    Err(error) => {
8617                        let failure = query_authority::Authority::protect(
8618                            authority.as_ref(),
8619                            self,
8620                            self.client.fail_query_task(
8621                                &query_task_id,
8622                                &lease_owner,
8623                                attempt,
8624                                error.to_string(),
8625                                "query_result_encode_failed",
8626                                "QueryResultEncodeFailed",
8627                            ),
8628                        )
8629                        .await;
8630                        let Ok(failure) = failure else {
8631                            return Ok(ManagedPollOutcome::Handled);
8632                        };
8633                        if let Err(error) = failure {
8634                            if !query_task_rejection_is_final(&error) {
8635                                return Err(error);
8636                            }
8637                        }
8638                        return Ok(ManagedPollOutcome::Handled);
8639                    }
8640                };
8641
8642                let completion = query_authority::Authority::protect(
8643                    authority.as_ref(),
8644                    self,
8645                    self.client.complete_query_task_with_envelope(
8646                        &query_task_id,
8647                        &lease_owner,
8648                        attempt,
8649                        value.clone().into_json()?,
8650                        result_envelope,
8651                    ),
8652                )
8653                .await;
8654                let Ok(completion) = completion else {
8655                    return Ok(ManagedPollOutcome::Handled);
8656                };
8657                if let Err(error) = completion {
8658                    if !query_task_rejection_is_final(&error) {
8659                        return Err(error);
8660                    }
8661                }
8662            }
8663            Err(failure) => {
8664                let result = query_authority::Authority::protect(
8665                    authority.as_ref(),
8666                    self,
8667                    self.client.fail_query_task(
8668                        &query_task_id,
8669                        &lease_owner,
8670                        attempt,
8671                        failure.message,
8672                        failure.reason,
8673                        failure.failure_type,
8674                    ),
8675                )
8676                .await;
8677                let Ok(result) = result else {
8678                    return Ok(ManagedPollOutcome::Handled);
8679                };
8680                if let Err(error) = result {
8681                    if !query_task_rejection_is_final(&error) {
8682                        return Err(error);
8683                    }
8684                }
8685            }
8686        }
8687
8688        Ok(ManagedPollOutcome::Handled)
8689    }
8690
8691    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8692        while !stop.load(Ordering::SeqCst) {
8693            match self.poll_query_once().await {
8694                Ok(ManagedPollOutcome::Stop) => {
8695                    stop.store(true, Ordering::SeqCst);
8696                    break;
8697                }
8698                Err(error) => {
8699                    stop.store(true, Ordering::SeqCst);
8700                    return Err(error);
8701                }
8702                _ => {}
8703            }
8704        }
8705
8706        Ok(())
8707    }
8708
8709    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
8710    where
8711        F: FnMut() -> Fut,
8712        Fut: Future<Output = Result<T>>,
8713    {
8714        let mut retries = 0;
8715
8716        loop {
8717            if self
8718                .run_stop
8719                .as_ref()
8720                .is_some_and(|stop| stop.load(Ordering::SeqCst))
8721            {
8722                return Ok(None);
8723            }
8724            match operation().await {
8725                Err(error)
8726                    if (workflow_hydration::stopped(&error)
8727                        || activity_hydration::stopped(&error))
8728                        && self
8729                            .run_stop
8730                            .as_ref()
8731                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
8732                {
8733                    return Ok(None);
8734                }
8735                Err(error)
8736                    if worker_operation_is_retryable(&error)
8737                        && (retries < self.retry_policy.max_retries
8738                            || (self.recover_transient_outages
8739                                && self.run_stop.is_some()
8740                                && self.retry_policy.max_retries > 0)) =>
8741                {
8742                    retries = retries.saturating_add(1);
8743                    let delay = worker_retry_delay(self.retry_policy, retries)
8744                        .max(Duration::from_millis(1));
8745                    if let Some(stop) = &self.run_stop {
8746                        tokio::select! {
8747                            _ = tokio::time::sleep(delay) => {}
8748                            _ = wait_for_worker_stop(stop) => return Ok(None),
8749                        }
8750                    } else {
8751                        tokio::time::sleep(delay).await;
8752                    }
8753                }
8754                result => return result.map(Some),
8755            }
8756        }
8757    }
8758
8759    async fn settle_worker_poll_response<T>(
8760        &self,
8761        response: Result<Option<T>>,
8762    ) -> Result<Option<T>> {
8763        match response {
8764            Ok(response) => Ok(response),
8765            Err(error) => {
8766                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
8767                    return Err(error);
8768                };
8769                let minimum_delay = self
8770                    .retry_policy
8771                    .initial_backoff
8772                    .max(Duration::from_millis(1));
8773                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
8774                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
8775                Ok(None)
8776            }
8777        }
8778    }
8779
8780    #[cfg(test)]
8781    async fn execute_query_task(
8782        &self,
8783        task: QueryTask,
8784    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8785        self.execute_query_task_with_authority(task, None).await
8786    }
8787
8788    async fn execute_query_task_with_authority(
8789        &self,
8790        mut task: QueryTask,
8791        authority: Option<&query_authority::Authority>,
8792    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8793        validate_query_task_payloads(&task).map_err(|error| {
8794            QueryTaskExecutionFailure::new(
8795                "query_payload_decode_failed",
8796                error.to_string(),
8797                "QueryPayloadDecodeFailed",
8798            )
8799        })?;
8800
8801        if !self.workflows.contains_key(&task.workflow_type) {
8802            return Err(QueryTaskExecutionFailure::new(
8803                "query_workflow_type_not_registered",
8804                format!("no workflow registered for type {:?}", task.workflow_type),
8805                "WorkflowTypeNotRegistered",
8806            ));
8807        }
8808
8809        let Some(handlers) = self.queries.get(&task.workflow_type) else {
8810            return Err(QueryTaskExecutionFailure::new(
8811                "query_handler_unavailable",
8812                format!(
8813                    "query handlers are unavailable for workflow type {:?}",
8814                    task.workflow_type
8815                ),
8816                "QueryHandlerUnavailable",
8817            ));
8818        };
8819        let Some(query) = handlers.get(&task.query_name) else {
8820            return Err(QueryTaskExecutionFailure::new(
8821                "rejected_unknown_query",
8822                format!("unknown query {:?}", task.query_name),
8823                "QueryFailed",
8824            ));
8825        };
8826
8827        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
8828            .map_err(|error| {
8829            QueryTaskExecutionFailure::new(
8830                "query_payload_decode_failed",
8831                format!("cannot decode query arguments: {error}"),
8832                "QueryPayloadDecodeFailed",
8833            )
8834        })?;
8835        let workflow_input_typed =
8836            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
8837                .map_err(|error| {
8838                    QueryTaskExecutionFailure::new(
8839                        "query_workflow_state_unavailable",
8840                        format!("cannot decode workflow start input: {error}"),
8841                        "QueryWorkflowStateUnavailable",
8842                    )
8843                })?;
8844        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
8845            QueryTaskExecutionFailure::new(
8846                "query_workflow_state_unavailable",
8847                format!("cannot project workflow start input: {error}"),
8848                "QueryWorkflowStateUnavailable",
8849            )
8850        })?;
8851        hydrate_query_history_from_export(&mut task).map_err(|error| {
8852            QueryTaskExecutionFailure::new(
8853                "query_workflow_state_unavailable",
8854                format!("cannot restore query history snapshot: {error}"),
8855                "QueryWorkflowStateUnavailable",
8856            )
8857        })?;
8858        enrich_query_history_from_export(&mut task).map_err(|error| {
8859            QueryTaskExecutionFailure::new(
8860                "query_workflow_state_unavailable",
8861                format!("cannot restore compact query history payloads: {error}"),
8862                "QueryWorkflowStateUnavailable",
8863            )
8864        })?;
8865        let signal_events = query_signal_events(&task).map_err(|error| {
8866            QueryTaskExecutionFailure::new(
8867                "query_workflow_state_unavailable",
8868                format!("cannot decode committed workflow signals: {error}"),
8869                "QueryWorkflowStateUnavailable",
8870            )
8871        })?;
8872        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8873        let context = QueryContext {
8874            workflow_id: task.workflow_id,
8875            run_id: task.run_id,
8876            workflow_type: task.workflow_type.clone(),
8877            run_status: task.run_status,
8878            workflow_input,
8879            workflow_input_avro_value: workflow_input_typed.clone(),
8880            history_events: Arc::clone(&history_events),
8881            signal_events: Arc::new(signal_events),
8882        };
8883
8884        let future = match query {
8885            RegisteredQuery::Snapshot(handler) => {
8886                query_authority::before_handler(authority, &self.client).await?;
8887                handler(context, args)
8888            }
8889            RegisteredQuery::Replayed {
8890                state_type,
8891                handler,
8892            } => {
8893                let workflow = self
8894                    .workflows
8895                    .get(&task.workflow_type)
8896                    .expect("workflow registration was checked above");
8897                if workflow.state_type != Some(*state_type) {
8898                    return Err(QueryTaskExecutionFailure::new(
8899                        "query_workflow_state_unavailable",
8900                        "replayed query state type does not match its workflow registration",
8901                        "QueryWorkflowStateUnavailable",
8902                    ));
8903                }
8904                let replay = workflow.replay.as_ref().ok_or_else(|| {
8905                    QueryTaskExecutionFailure::new(
8906                        "query_workflow_state_unavailable",
8907                        format!(
8908                            "workflow type {:?} is not registered for instance-state replay",
8909                            task.workflow_type
8910                        ),
8911                        "QueryWorkflowStateUnavailable",
8912                    )
8913                })?;
8914                let workflow_state = Arc::new(Mutex::new(
8915                    WorkflowState::new_with_identity(
8916                        history_events.as_ref().clone(),
8917                        context.workflow_id.clone(),
8918                        context.run_id.clone(),
8919                        self.task_queue.clone(),
8920                        task.payload_codec,
8921                        None,
8922                    )
8923                    .map_err(|error| {
8924                        QueryTaskExecutionFailure::new(
8925                            "query_workflow_state_unavailable",
8926                            format!("workflow replay failed before query: {error}"),
8927                            "QueryWorkflowStateUnavailable",
8928                        )
8929                    })?,
8930                ));
8931                let workflow_context = WorkflowContext {
8932                    state: workflow_state,
8933                    cancellation_scope_id: "root".into(),
8934                };
8935                query_authority::before_handler(authority, &self.client).await?;
8936                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone())
8937                    .map_err(|error| {
8938                        QueryTaskExecutionFailure::new(
8939                            "query_workflow_state_unavailable",
8940                            error.to_string(),
8941                            "QueryWorkflowStateUnavailable",
8942                        )
8943                    })?;
8944                let outcome = {
8945                    let mut cx = TaskContext::from_waker(noop_waker_ref());
8946                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8947                        .map_err(|error| {
8948                            QueryTaskExecutionFailure::new(
8949                                "query_workflow_state_unavailable",
8950                                error.to_string(),
8951                                "QueryWorkflowStateUnavailable",
8952                            )
8953                        })?;
8954                    invocation.future.as_mut().poll(&mut cx)
8955                };
8956                match outcome {
8957                    Poll::Ready(Ok(_)) => {
8958                        workflow_context
8959                            .ensure_history_consumed()
8960                            .map_err(|error| {
8961                                QueryTaskExecutionFailure::new(
8962                                    "query_workflow_state_unavailable",
8963                                    format!("workflow replay failed before query: {error}"),
8964                                    "QueryWorkflowStateUnavailable",
8965                                )
8966                            })?;
8967                    }
8968                    Poll::Ready(Err(error)) => {
8969                        return Err(QueryTaskExecutionFailure::new(
8970                            "query_workflow_state_unavailable",
8971                            format!("workflow replay failed before query: {error}"),
8972                            "QueryWorkflowStateUnavailable",
8973                        ));
8974                    }
8975                    Poll::Pending => {
8976                        let commands = workflow_context.take_commands().map_err(|error| {
8977                            QueryTaskExecutionFailure::new(
8978                                "query_workflow_state_unavailable",
8979                                format!("workflow replay failed before query: {error}"),
8980                                "QueryWorkflowStateUnavailable",
8981                            )
8982                        })?;
8983                        if commands.is_empty()
8984                            && !workflow_context
8985                                .matched_recorded_pending()
8986                                .map_err(|error| {
8987                                    QueryTaskExecutionFailure::new(
8988                                        "query_workflow_state_unavailable",
8989                                        format!("workflow replay failed before query: {error}"),
8990                                        "QueryWorkflowStateUnavailable",
8991                                    )
8992                                })?
8993                        {
8994                            return Err(QueryTaskExecutionFailure::new(
8995                                "query_workflow_state_unavailable",
8996                                "workflow replay yielded without a durable command",
8997                                "QueryWorkflowStateUnavailable",
8998                            ));
8999                        }
9000                    }
9001                }
9002                let state = (invocation.snapshot)().map_err(|error| {
9003                    QueryTaskExecutionFailure::new(
9004                        "query_workflow_state_unavailable",
9005                        format!("cannot snapshot replayed workflow state: {error}"),
9006                        "QueryWorkflowStateUnavailable",
9007                    )
9008                })?;
9009                query_authority::before_handler(authority, &self.client).await?;
9010                handler(context, state, args).map_err(|message| {
9011                    QueryTaskExecutionFailure::new(
9012                        "query_workflow_state_unavailable",
9013                        message,
9014                        "QueryWorkflowStateUnavailable",
9015                    )
9016                })?
9017            }
9018        };
9019
9020        future.await.map_err(|error| {
9021            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
9022        })
9023    }
9024
9025    #[cfg(test)]
9026    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
9027        Ok(self.execute_workflow_task_decision(task)?.commands)
9028    }
9029
9030    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
9031        self.execute_workflow_task_decision_with_cancellation(task, None)
9032    }
9033
9034    fn execute_workflow_task_decision_with_cancellation(
9035        &self,
9036        task: WorkflowTask,
9037        observation: Option<&CancellationRequest>,
9038    ) -> Result<WorkflowTaskDecision> {
9039        match self.prepare_workflow_task_execution(task, observation)? {
9040            PreparedWorkflowTask::Decision(decision) => Ok(decision),
9041            PreparedWorkflowTask::Execution {
9042                task,
9043                context,
9044                mut future,
9045            } => {
9046                let outcome = Self::poll_workflow_future(&context, &mut future)?;
9047                self.finish_workflow_task_execution(&task, &context, outcome)
9048            }
9049        }
9050    }
9051
9052    fn prepare_workflow_task_execution(
9053        &self,
9054        task: WorkflowTask,
9055        observation: Option<&CancellationRequest>,
9056    ) -> Result<PreparedWorkflowTask> {
9057        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
9058            && !self.cooperative_cancellation_enabled
9059        {
9060            return Err(Error::CancellationScopeExecutionUnavailable);
9061        }
9062        validate_workflow_task_payloads(&task)?;
9063        cooperative_cancellation::assert_cancellation_scope_replay_supported(
9064            &task.history_events,
9065            self.allow_cancellation_scope_authoring,
9066            self.allow_cancellation_scope_delivery,
9067        )?;
9068        let cancellation_history = if let Some(observation) = observation {
9069            observation.validate_observation()?;
9070            cooperative_cancellation::cancellation_claim(&task)?;
9071            let canonical = CancellationHistory::from_events(
9072                &task.history_events,
9073                task.run_id.as_deref().unwrap_or_default(),
9074                Some(observation),
9075            )?;
9076            if canonical.request_index >= task.history_events.len() {
9077                return Err(Error::InvalidCooperativeCancellation(
9078                    "workflow replay requires the observed canonical request".into(),
9079                ));
9080            }
9081            Some(canonical)
9082        } else {
9083            None
9084        };
9085        if let Some(update_id) = task
9086            .workflow_update_id
9087            .as_deref()
9088            .filter(|update_id| !update_id.is_empty())
9089        {
9090            if self.allow_cancellation_scope_delivery {
9091                return Err(Error::CancellationScopeExecutionUnavailable);
9092            }
9093            CancellationHistory::from_events(
9094                &task.history_events,
9095                task.run_id.as_deref().unwrap_or_default(),
9096                None,
9097            )?;
9098            return self
9099                .execute_update_task(&task, update_id)
9100                .map(WorkflowTaskDecision::without_message_streams)
9101                .map(PreparedWorkflowTask::Decision);
9102        }
9103
9104        let workflow = self
9105            .workflows
9106            .get(&task.workflow_type)
9107            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
9108        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9109        let resume_signal = decode_resume_signal(&task)?;
9110        let history_budget = WorkflowHistoryBudget {
9111            event_count: task
9112                .total_history_events
9113                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
9114            size_bytes: task.history_size_bytes,
9115            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
9116            pressure: task.history_budget_pressure.clone(),
9117        };
9118        let workflow_command_identity = task
9119            .workflow_command_id
9120            .clone()
9121            .filter(|identity| !identity.is_empty())
9122            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
9123            .unwrap_or_default();
9124        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
9125            task.history_events.clone(),
9126            task.workflow_id.clone(),
9127            task.run_id.clone(),
9128            self.task_queue.clone(),
9129            task.payload_codec.clone(),
9130            resume_signal,
9131            self.allow_cancellation_scope_authoring,
9132            self.allow_cancellation_scope_delivery,
9133        )?;
9134        workflow_state.history_budget = history_budget;
9135        workflow_state.workflow_command_identity = workflow_command_identity;
9136        if let Some(canonical) = cancellation_history {
9137            workflow_state.cancellation_history = canonical;
9138            workflow_state.cancellation_delivery_enabled = true;
9139        }
9140        if workflow_state.cancellation_history.request.is_none() {
9141            workflow_state.cancel_requested = task.cancel_requested;
9142        }
9143        let state = Arc::new(Mutex::new(workflow_state));
9144        let ctx = WorkflowContext {
9145            state,
9146            cancellation_scope_id: "root".into(),
9147        };
9148        let future = (workflow.execute)(ctx.clone(), input)?;
9149        Ok(PreparedWorkflowTask::Execution {
9150            task,
9151            context: ctx,
9152            future,
9153        })
9154    }
9155
9156    fn poll_workflow_future(
9157        ctx: &WorkflowContext,
9158        future: &mut WorkflowFuture,
9159    ) -> Result<Poll<Result<AvroValue>>> {
9160        let mut cx = TaskContext::from_waker(noop_waker_ref());
9161        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
9162        Ok(future.as_mut().poll(&mut cx))
9163    }
9164
9165    fn finish_workflow_task_execution(
9166        &self,
9167        task: &WorkflowTask,
9168        ctx: &WorkflowContext,
9169        outcome: Poll<Result<AvroValue>>,
9170    ) -> Result<WorkflowTaskDecision> {
9171        if !ctx
9172            .state
9173            .lock()
9174            .map_err(|_| Error::WorkflowStatePoisoned)?
9175            .local_activity_requests
9176            .is_empty()
9177        {
9178            return Err(Error::CooperativeCancellationUnavailable(
9179                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
9180            ));
9181        }
9182        let awaiting_canonical_boundary = {
9183            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9184            state.cancellation_delivery_intent.is_some()
9185                || state.cancellation_scope_opening.is_some()
9186                || state
9187                    .scope_delivery
9188                    .as_ref()
9189                    .is_some_and(|replay| replay.intent.is_some())
9190        };
9191        if awaiting_canonical_boundary {
9192            // A private delivery intent never becomes an application error.
9193            // Even a custom future which ignores a pending durable call cannot
9194            // publish terminal commands before canonical delivery and replay.
9195            if let Poll::Ready(Err(error)) = outcome {
9196                if workflow_task_integrity_error(&error) {
9197                    return Err(error);
9198                }
9199            }
9200            return self.message_stream_decision(&ctx, ctx.take_commands()?);
9201        }
9202
9203        match outcome {
9204            Poll::Ready(Ok(result)) => {
9205                ctx.ensure_history_consumed()?;
9206                let result = encode_typed_envelope(&result, &task.payload_codec)?;
9207                let mut commands = ctx.take_commands()?;
9208                commands.push(json!({
9209                    "type": "complete_workflow",
9210                    "result": result
9211                }));
9212                self.message_stream_decision(&ctx, commands)
9213            }
9214            Poll::Ready(Err(error)) => {
9215                if let Error::ContinueAsNew(request) = error {
9216                    let mut commands = ctx.take_commands()?;
9217                    if let Some(command) = ctx.continue_as_new_command(request)? {
9218                        commands.push(command);
9219                    }
9220                    ctx.ensure_history_consumed()?;
9221                    return self.message_stream_decision(&ctx, commands);
9222                }
9223                if workflow_task_integrity_error(&error) {
9224                    // Replay and protocol failures describe the workflow-task
9225                    // decision itself. Preserve their specific failure reason
9226                    // instead of replacing it with the derivative fact that
9227                    // recorded commands remain unconsumed.
9228                    return Err(error);
9229                }
9230                // A handler error must not hide a committed durable command that
9231                // upgraded workflow code no longer consumes.
9232                ctx.ensure_history_consumed()?;
9233                let mut commands = ctx.take_commands()?;
9234                commands.push(workflow_failure_command(
9235                    &error,
9236                    recorded_activity_failure_boundary(&ctx, &error),
9237                ));
9238                self.message_stream_decision(&ctx, commands)
9239            }
9240            Poll::Pending => {
9241                let commands = ctx.take_commands()?;
9242                if commands.is_empty() && !ctx.matched_recorded_pending()? {
9243                    Err(Error::WorkflowYieldedWithoutCommand)
9244                } else {
9245                    self.message_stream_decision(&ctx, commands)
9246                }
9247            }
9248        }
9249    }
9250
9251    fn message_stream_decision(
9252        &self,
9253        ctx: &WorkflowContext,
9254        commands: Vec<Value>,
9255    ) -> Result<WorkflowTaskDecision> {
9256        if !self.cooperative_cancellation_enabled
9257            && commands.iter().any(|command| {
9258                command["type"] == "schedule_activity"
9259                    && command.get("cancellation_policy").is_some()
9260            })
9261        {
9262            return Err(Error::CooperativeCancellationUnavailable(format!(
9263                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9264                self.worker_id,
9265            )));
9266        }
9267        if !self.cooperative_cancellation_enabled
9268            && commands.iter().any(|command| {
9269                command["type"] == "start_child_workflow"
9270                    && (command["parent_close_policy"] == "request_cancellation"
9271                        || matches!(
9272                            command["cancellation_policy"].as_str(),
9273                            Some("try_cancel" | "wait_cancellation_completed")
9274                        ))
9275            })
9276        {
9277            return Err(Error::CooperativeCancellationUnavailable(format!(
9278                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9279                self.worker_id,
9280            )));
9281        }
9282        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
9283        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9284        let scope_delivery = state
9285            .scope_delivery
9286            .as_ref()
9287            .and_then(|replay| replay.intent.clone());
9288        if scope_delivery
9289            .as_ref()
9290            .is_some_and(|intent| commands.len() != intent.command_count)
9291        {
9292            return Err(invalid_recorded_history(
9293                "cancellation_scope_pending_call_escaped",
9294                scope_delivery.as_ref().unwrap().boundary.sequence,
9295                "commands preceding the pending scoped call",
9296                "commands after suspension",
9297                "workflow cannot publish beyond an uncommitted scope delivery",
9298            ));
9299        }
9300        if let Some(opening) = &state.cancellation_scope_opening {
9301            if commands.len() != opening.command_count {
9302                return Err(invalid_recorded_history(
9303                    "cancellation_scope_pending_call_escaped",
9304                    opening.sequence,
9305                    "commands before original scope opening",
9306                    "commands after suspended opening",
9307                    "workflow cannot publish beyond an uncommitted scope opening",
9308                ));
9309            }
9310        }
9311        if state.cancellation_delivery_intent.is_some()
9312            && commands.len() != state.cancellation_delivery_command_count
9313        {
9314            return Err(invalid_recorded_history(
9315                "cooperative_cancellation_pending_call_escaped",
9316                state
9317                    .cancellation_delivery_intent
9318                    .as_ref()
9319                    .expect("pending delivery")
9320                    .sequence,
9321                "only commands preceding the pending cancellation call",
9322                "commands authored after a suspended call",
9323                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
9324            ));
9325        }
9326        Ok(WorkflowTaskDecision {
9327            commands,
9328            message_stream_cursors,
9329            message_stream_waits,
9330            cancellation_delivery: state.cancellation_delivery_intent.clone(),
9331            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
9332            cancellation_scope_delivery: scope_delivery,
9333        })
9334    }
9335
9336    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
9337        if !self.workflows.contains_key(&task.workflow_type) {
9338            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
9339        }
9340
9341        let accepted = task.history_events.iter().rev().find_map(|event| {
9342            (event.event_type == "UpdateAccepted"
9343                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
9344            .then_some(&event.payload)
9345        });
9346        let update_name = accepted
9347            .and_then(|payload| payload.get("update_name"))
9348            .and_then(Value::as_str)
9349            .or(task.update_name.as_deref())
9350            .unwrap_or_default();
9351        let Some(handler) = self
9352            .updates
9353            .get(&task.workflow_type)
9354            .and_then(|handlers| handlers.get(update_name))
9355        else {
9356            return Ok(vec![json!({
9357                "type": "fail_update",
9358                "update_id": update_id,
9359                "message": format!(
9360                    "no update handler is registered for {}.{update_name}",
9361                    task.workflow_type
9362                ),
9363                "exception_type": "UnknownUpdate",
9364                "non_retryable": true,
9365            })]);
9366        };
9367        let arguments = accepted
9368            .and_then(|payload| payload.get("arguments"))
9369            .or(task.arguments.as_ref());
9370        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9371        let workflow_input_avro_value =
9372            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9373        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9374        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9375        let context = QueryContext {
9376            workflow_id: task.workflow_id.clone(),
9377            run_id: task.run_id.clone(),
9378            workflow_type: task.workflow_type.clone(),
9379            run_status: Some("running".to_string()),
9380            workflow_input,
9381            workflow_input_avro_value,
9382            history_events: Arc::new(task.history_events.clone()),
9383            signal_events: Arc::new(signal_events),
9384        };
9385        let mut future = handler(context, arguments);
9386        let mut cx = TaskContext::from_waker(noop_waker_ref());
9387
9388        match future.as_mut().poll(&mut cx) {
9389            Poll::Ready(Ok(result)) => Ok(vec![json!({
9390                "type": "complete_update",
9391                "update_id": update_id,
9392                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9393            })]),
9394            Poll::Ready(Err(error)) => Ok(vec![json!({
9395                "type": "fail_update",
9396                "update_id": update_id,
9397                "message": error.to_string(),
9398                "exception_type": "UpdateFailed",
9399                "non_retryable": true,
9400            })]),
9401            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9402        }
9403    }
9404
9405    #[cfg(test)]
9406    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9407        self.execute_session_activity_task(task, None, None).await
9408    }
9409
9410    async fn execute_session_activity_task(
9411        &self,
9412        task: ActivityTask,
9413        worker_session: Option<WorkerSession>,
9414        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9415    ) -> Result<AvroValue> {
9416        validate_activity_task_payloads(&task)?;
9417        if worker_session.is_some() {
9418            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
9419                || task
9420                    .activity_attempt_id
9421                    .as_deref()
9422                    .or(task.attempt_id.as_deref())
9423                    .is_none_or(str::is_empty)
9424                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
9425            {
9426                return Err(Error::ActivityExecutionAbandoned(
9427                    "session activity requires this worker's exact immutable claim".into(),
9428                ));
9429            }
9430        }
9431
9432        let handler = self
9433            .activities
9434            .get(&task.activity_type)
9435            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
9436        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9437        let attempt_id = task
9438            .activity_attempt_id
9439            .clone()
9440            .or(task.attempt_id.clone())
9441            .unwrap_or_default();
9442        let lease_owner = task
9443            .lease_owner
9444            .clone()
9445            .unwrap_or_else(|| self.worker_id.clone());
9446        let session = worker_session.clone();
9447        let ctx = ActivityContext {
9448            client: self.client.clone(),
9449            task_id: task.task_id,
9450            activity_attempt_id: attempt_id,
9451            lease_owner,
9452            activity_type: task.activity_type,
9453            attempt_number: task.attempt_number,
9454            task_queue: self.task_queue.clone(),
9455            worker_id: self.worker_id.clone(),
9456            claim_guard: None,
9457            local_heartbeats: None,
9458            worker_session,
9459        };
9460
9461        if let Some(claim) = hydration_claim {
9462            claim.confirm(&self.client).await?;
9463        }
9464        let callback = handler(ctx, args);
9465        if let Some(session) = session {
9466            tokio::select! {
9467                biased;
9468                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
9469                result = callback => if session.active() { result } else {
9470                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
9471                },
9472            }
9473        } else {
9474            callback.await
9475        }
9476    }
9477}
9478
9479fn poller_result(
9480    kind: &str,
9481    result: std::result::Result<Result<()>, tokio::task::JoinError>,
9482) -> Result<()> {
9483    match result {
9484        Ok(result) => result,
9485        Err(error) => Err(Error::WorkerLoop(format!(
9486            "{kind} poller join error: {error}"
9487        ))),
9488    }
9489}
9490
9491fn optional_poller_result(
9492    kind: &str,
9493    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
9494) -> Result<()> {
9495    match result {
9496        Some(result) => poller_result(kind, result),
9497        None => Ok(()),
9498    }
9499}
9500
9501async fn join_pollers(
9502    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9503    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9504    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9505) -> Result<()> {
9506    let mut first_error = None;
9507
9508    if let Some(handle) = workflow_poller {
9509        if let Err(error) = poller_result("workflow", handle.await) {
9510            first_error.get_or_insert(error);
9511        }
9512    }
9513
9514    if let Some(handle) = activity_poller {
9515        if let Err(error) = poller_result("activity", handle.await) {
9516            first_error.get_or_insert(error);
9517        }
9518    }
9519
9520    if let Some(handle) = query_poller {
9521        if let Err(error) = poller_result("query", handle.await) {
9522            first_error.get_or_insert(error);
9523        }
9524    }
9525
9526    if let Some(error) = first_error {
9527        Err(error)
9528    } else {
9529        Ok(())
9530    }
9531}
9532
9533fn default_worker_id() -> String {
9534    let millis = SystemTime::now()
9535        .duration_since(UNIX_EPOCH)
9536        .unwrap_or_default()
9537        .as_millis();
9538    format!("rust-worker-{}-{millis}", std::process::id())
9539}
9540
9541fn percent_encode_path_segment(segment: &str) -> String {
9542    const HEX: &[u8; 16] = b"0123456789ABCDEF";
9543    let mut encoded = String::with_capacity(segment.len());
9544
9545    for byte in segment.bytes() {
9546        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
9547            encoded.push(char::from(byte));
9548        } else {
9549            encoded.push('%');
9550            encoded.push(char::from(HEX[(byte >> 4) as usize]));
9551            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
9552        }
9553    }
9554
9555    encoded
9556}
9557
9558fn unique_request_id(prefix: &str) -> String {
9559    let nanos = SystemTime::now()
9560        .duration_since(UNIX_EPOCH)
9561        .unwrap_or_default()
9562        .as_nanos();
9563    format!("{prefix}-{}-{nanos}", std::process::id())
9564}
9565
9566#[derive(Debug)]
9567struct QueryTaskExecutionFailure {
9568    reason: String,
9569    message: String,
9570    failure_type: String,
9571}
9572
9573impl QueryTaskExecutionFailure {
9574    fn new(
9575        reason: impl Into<String>,
9576        message: impl Into<String>,
9577        failure_type: impl Into<String>,
9578    ) -> Self {
9579        Self {
9580            reason: reason.into(),
9581            message: message.into(),
9582            failure_type: failure_type.into(),
9583        }
9584    }
9585}
9586
9587/// Typed local state owned by one deterministic workflow invocation.
9588///
9589/// Use [`WorkflowInstance::update`] for the same state transitions during
9590/// ordinary execution and replay. A replayed query receives a detached
9591/// immutable `Arc<S>` rather than this mutation-capable handle.
9592#[derive(Clone, Debug)]
9593pub struct WorkflowInstance<S> {
9594    state: Arc<Mutex<S>>,
9595}
9596
9597impl<S> WorkflowInstance<S> {
9598    fn new(state: S) -> Self {
9599        Self {
9600            state: Arc::new(Mutex::new(state)),
9601        }
9602    }
9603
9604    /// Read the current workflow-instance state without changing it.
9605    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
9606        let state = self
9607            .state
9608            .lock()
9609            .map_err(|_| Error::WorkflowStatePoisoned)?;
9610        Ok(reader(&state))
9611    }
9612
9613    /// Apply one deterministic workflow-instance state transition.
9614    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
9615        let mut state = self
9616            .state
9617            .lock()
9618            .map_err(|_| Error::WorkflowStatePoisoned)?;
9619        Ok(transition(&mut state))
9620    }
9621}
9622
9623impl<S: Clone> WorkflowInstance<S> {
9624    fn snapshot(&self) -> Result<S> {
9625        self.read(Clone::clone)
9626    }
9627}
9628
9629#[derive(Clone, Debug, PartialEq)]
9630pub struct MessageStreamMessage {
9631    pub stream_name: String,
9632    pub message_id: String,
9633    pub position: u64,
9634    pub arguments: Vec<AvroValue>,
9635}
9636
9637#[derive(Clone, Debug)]
9638pub struct MessageStream {
9639    ctx: WorkflowContext,
9640    name: String,
9641}
9642
9643impl MessageStream {
9644    /// Wait for one message, then return a bounded currently-available batch.
9645    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
9646        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
9647            return Err(Error::Codec(format!(
9648                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
9649            )));
9650        }
9651        loop {
9652            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
9653                return Ok(batch);
9654            }
9655
9656            self.ctx.record_message_stream_wait(&self.name)?;
9657            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
9658            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
9659            self.ctx.buffer_message_stream_delivery(arguments)?;
9660            if let Some(sequence) = replay_wait_sequence {
9661                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
9662            }
9663        }
9664    }
9665
9666    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
9667        self.receive(1)
9668            .await?
9669            .into_iter()
9670            .next()
9671            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
9672    }
9673}
9674
9675#[derive(Clone, Debug)]
9676pub struct WorkflowContext {
9677    state: Arc<Mutex<WorkflowState>>,
9678    cancellation_scope_id: String,
9679}
9680
9681fn valid_memo_key(key: &str) -> bool {
9682    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
9683
9684    !key.is_empty()
9685        && key.len() <= 64
9686        && (numeric_candidate.is_empty()
9687            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
9688        && key
9689            .bytes()
9690            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
9691}
9692
9693fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
9694    BASE64
9695        .decode(encode_avro_value(value)?.blob)
9696        .map(|bytes| bytes.len())
9697        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
9698}
9699
9700fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
9701    let AvroValue::Map(entries) = value else {
9702        return Err(Error::InvalidMemoUpdate(
9703            "entries must serialize to an Avro string-keyed map".to_string(),
9704        ));
9705    };
9706    if require_entries && entries.is_empty() {
9707        return Err(Error::InvalidMemoUpdate(
9708            "at least one entry is required".to_string(),
9709        ));
9710    }
9711    if entries.len() > MAX_MEMO_ENTRIES {
9712        return Err(Error::InvalidMemoUpdate(format!(
9713            "at most {MAX_MEMO_ENTRIES} entries are allowed"
9714        )));
9715    }
9716
9717    for (key, value) in &entries {
9718        if !valid_memo_key(&key) {
9719            return Err(Error::InvalidMemoUpdate(
9720                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
9721            ));
9722        }
9723        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
9724            return Err(Error::InvalidMemoUpdate(format!(
9725                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
9726            )));
9727        }
9728    }
9729
9730    let value = AvroValue::Map(entries);
9731    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
9732        return Err(Error::InvalidMemoUpdate(format!(
9733            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
9734        )));
9735    }
9736    Ok(value)
9737}
9738
9739fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
9740    let object = envelope.as_object().ok_or_else(|| {
9741        Error::InvalidMemoUpdate(
9742            "history field must use the public {codec, blob} payload envelope".to_string(),
9743        )
9744    })?;
9745    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
9746        return Err(Error::InvalidMemoUpdate(
9747            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
9748        ));
9749    }
9750
9751    canonical_memo_entries(
9752        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
9753        require_entries,
9754    )
9755}
9756
9757impl WorkflowContext {
9758    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
9759        let name = name.into();
9760        if name.is_empty()
9761            || name.len() > 128
9762            || !name.bytes().all(|byte| {
9763                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
9764            })
9765        {
9766            return Err(Error::Codec(
9767                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
9768                    .to_string(),
9769            ));
9770        }
9771        Ok(MessageStream {
9772            ctx: self.clone(),
9773            name,
9774        })
9775    }
9776
9777    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
9778        let mut state = self
9779            .state
9780            .lock()
9781            .map_err(|_| Error::WorkflowStatePoisoned)?;
9782        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9783        state
9784            .message_stream_waits
9785            .insert(name.to_string(), position);
9786        Ok(())
9787    }
9788
9789    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
9790        let mut state = self
9791            .state
9792            .lock()
9793            .map_err(|_| Error::WorkflowStatePoisoned)?;
9794        let cursor = state
9795            .message_stream_cursors
9796            .get(&message.stream_name)
9797            .copied()
9798            .unwrap_or(0);
9799        if message.position <= cursor {
9800            return Ok(());
9801        }
9802        let pending = state
9803            .message_stream_messages
9804            .entry(message.stream_name.clone())
9805            .or_default();
9806        if pending.iter().any(|candidate| {
9807            candidate.position == message.position || candidate.message_id == message.message_id
9808        }) {
9809            return Ok(());
9810        }
9811        pending.push(message);
9812        pending.sort_by_key(|candidate| candidate.position);
9813        Ok(())
9814    }
9815
9816    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
9817        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
9818            match delivery {
9819                MessageStreamDelivery::Message(message) => {
9820                    let stream_name = message.stream_name.clone();
9821                    self.buffer_message_stream(message)?;
9822                    return Ok(Some(stream_name));
9823                }
9824                MessageStreamDelivery::Cursor {
9825                    stream_name,
9826                    through_position,
9827                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
9828            }
9829        }
9830        Ok(None)
9831    }
9832
9833    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
9834        let state = self
9835            .state
9836            .lock()
9837            .map_err(|_| Error::WorkflowStatePoisoned)?;
9838        Ok(match state.recorded_commands.get(state.command_cursor) {
9839            Some(RecordedCommand::SignalWait {
9840                sequence,
9841                signal_name,
9842                ..
9843            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
9844            _ => None,
9845        })
9846    }
9847
9848    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
9849        let (history, payload_codec) = {
9850            let state = self
9851                .state
9852                .lock()
9853                .map_err(|_| Error::WorkflowStatePoisoned)?;
9854            (
9855                Arc::clone(&state.history_events),
9856                state.payload_codec.clone(),
9857            )
9858        };
9859
9860        let Some(opened_index) = history.iter().position(|event| {
9861            event.event_type == "SignalWaitOpened"
9862                && durable_event_sequence(event) == Some(wait_sequence)
9863                && event.payload.get("signal_name").and_then(Value::as_str)
9864                    == Some(MESSAGE_STREAM_SIGNAL)
9865        }) else {
9866            return Ok(());
9867        };
9868        let boundary_index = history
9869            .iter()
9870            .enumerate()
9871            .skip(opened_index + 1)
9872            .find_map(|(index, event)| {
9873                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
9874                    && is_authored_command_open_event(event))
9875                .then_some(index)
9876            })
9877            .unwrap_or(history.len());
9878
9879        for event in history[opened_index + 1..boundary_index]
9880            .iter()
9881            .filter(|event| {
9882                event.event_type == "SignalReceived"
9883                    && event.payload.get("signal_name").and_then(Value::as_str)
9884                        == Some(MESSAGE_STREAM_SIGNAL)
9885            })
9886        {
9887            let arguments = decode_signal_event_arguments(event, &payload_codec)?
9888                .into_iter()
9889                .map(AvroValue::into_json)
9890                .collect::<Result<Vec<_>>>()?;
9891            self.buffer_message_stream_delivery(arguments)?;
9892        }
9893        Ok(())
9894    }
9895
9896    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9897        let mut state = self
9898            .state
9899            .lock()
9900            .map_err(|_| Error::WorkflowStatePoisoned)?;
9901        let cursor = state
9902            .message_stream_cursors
9903            .entry(name.to_string())
9904            .or_default();
9905        *cursor = (*cursor).max(through_position);
9906        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9907            pending.retain(|message| message.position > through_position);
9908        }
9909        Ok(())
9910    }
9911
9912    fn take_message_stream_batch(
9913        &self,
9914        name: &str,
9915        max_items: usize,
9916    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9917        let mut state = self
9918            .state
9919            .lock()
9920            .map_err(|_| Error::WorkflowStatePoisoned)?;
9921        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9922        let pending = state
9923            .message_stream_messages
9924            .entry(name.to_string())
9925            .or_default();
9926        let count = contiguous_message_stream_count(pending, cursor, max_items);
9927        if count == 0 {
9928            return Ok(None);
9929        }
9930        let batch = pending.drain(..count).collect::<Vec<_>>();
9931        let position = batch.last().map(|message| message.position).unwrap_or(0);
9932        state
9933            .message_stream_cursors
9934            .insert(name.to_string(), position);
9935        state.message_stream_waits.remove(name);
9936        Ok(Some(batch))
9937    }
9938
9939    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9940        let state = self
9941            .state
9942            .lock()
9943            .map_err(|_| Error::WorkflowStatePoisoned)?;
9944        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9945        cursors.sort_by_key(|(name, _)| *name);
9946        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9947        waits.sort_by_key(|(name, _)| *name);
9948        Ok((
9949            cursors
9950                .into_iter()
9951                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9952                .collect(),
9953            waits
9954                .into_iter()
9955                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9956                .collect(),
9957        ))
9958    }
9959    /// Identity of the parent workflow currently being replayed.
9960    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9961        let state = self
9962            .state
9963            .lock()
9964            .map_err(|_| Error::WorkflowStatePoisoned)?;
9965        Ok(WorkflowIdentity {
9966            workflow_id: state.workflow_id.clone(),
9967            run_id: state.run_id.clone(),
9968        })
9969    }
9970
9971    /// Return the server-published history budget for this workflow task.
9972    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9973        let state = self
9974            .state
9975            .lock()
9976            .map_err(|_| Error::WorkflowStatePoisoned)?;
9977        Ok(state.history_budget.clone())
9978    }
9979
9980    /// Continue this workflow instance as a fresh run with replacement arguments.
9981    ///
9982    /// Return this value directly from the workflow handler. The worker converts
9983    /// it to the terminal protocol command only after replay has consumed every
9984    /// recorded durable command.
9985    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9986        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9987    }
9988
9989    /// Continue as new with optional workflow-type and task-queue overrides.
9990    pub fn continue_as_new_with_options<T: Serialize>(
9991        &self,
9992        options: ContinueAsNewOptions,
9993        args: T,
9994    ) -> Result<Value> {
9995        options.validate()?;
9996        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9997            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9998            options,
9999        }))
10000    }
10001
10002    pub fn activity<T: Serialize>(
10003        &self,
10004        activity_type: impl Into<String>,
10005        args: T,
10006    ) -> ActivityCall {
10007        self.activity_with_options(activity_type, ActivityOptions::new(), args)
10008    }
10009
10010    pub fn activity_on_queue<T, Q>(
10011        &self,
10012        activity_type: impl Into<String>,
10013        task_queue: Option<Q>,
10014        args: T,
10015    ) -> ActivityCall
10016    where
10017        T: Serialize,
10018        Q: Into<String>,
10019    {
10020        let mut options = ActivityOptions::new();
10021        options.task_queue = task_queue.map(Into::into);
10022        self.activity_with_options(activity_type, options, args)
10023    }
10024
10025    /// Schedule one durable activity with retry, routing, and timeout options.
10026    ///
10027    /// Options are validated before the command is emitted. Once the command is
10028    /// recorded, replay consumes the same activity lifecycle at this command
10029    /// position and never emits a duplicate schedule.
10030    ///
10031    /// ```no_run
10032    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
10033    /// # use std::time::Duration;
10034    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
10035    /// let result = ctx
10036    ///     .activity_with_options(
10037    ///         "charge-card",
10038    ///         ActivityOptions::new()
10039    ///             .task_queue("payments")
10040    ///             .retry_policy(
10041    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
10042    ///                     Duration::from_secs(1),
10043    ///                     2,
10044    ///                     Some(Duration::from_secs(30)),
10045    ///                 ),
10046    ///             )
10047    ///             .start_to_close_timeout(Duration::from_secs(60))
10048    ///             .schedule_to_close_timeout(Duration::from_secs(180))
10049    ///             .heartbeat_timeout(Duration::from_secs(15)),
10050    ///         json!([{"order_id": "order-42"}]),
10051    ///     )
10052    ///     .await;
10053    /// match result {
10054    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
10055    ///         "reason": failure.reason,
10056    ///         "timeout_kind": failure.timeout_kind,
10057    ///     })),
10058    ///     other => other,
10059    /// }
10060    /// # }
10061    /// ```
10062    pub fn activity_with_options<T: Serialize>(
10063        &self,
10064        activity_type: impl Into<String>,
10065        options: ActivityOptions,
10066        args: T,
10067    ) -> ActivityCall {
10068        ActivityCall {
10069            ctx: self.clone(),
10070            activity_type: activity_type.into(),
10071            options,
10072            worker_session: None,
10073            args: Some(AvroValue::from_serialize(&args)),
10074            scheduled: false,
10075            local: false,
10076            local_result: None,
10077            parallel_group_path: Vec::new(),
10078        }
10079    }
10080
10081    pub async fn activity_avro_value<T: Serialize>(
10082        &self,
10083        activity_type: impl Into<String>,
10084        args: T,
10085    ) -> Result<AvroValue> {
10086        let mut call = self.activity(activity_type, args);
10087        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10088    }
10089
10090    pub async fn activity_avro_value_with_options<T: Serialize>(
10091        &self,
10092        activity_type: impl Into<String>,
10093        options: ActivityOptions,
10094        args: T,
10095    ) -> Result<AvroValue> {
10096        let mut call = self.activity_with_options(activity_type, options, args);
10097        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10098    }
10099
10100    /// Schedule an activity with a Serde request and decode its Serde result.
10101    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
10102    where
10103        I: Serialize,
10104        O: DeserializeOwned,
10105    {
10106        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
10107            .await
10108    }
10109
10110    /// Schedule an activity with options and decode its result into `O`.
10111    ///
10112    /// Both directions use the fixed Avro Value codec. In particular, this
10113    /// method does not deserialize the JSON-safe inspection projection returned
10114    /// by the dynamic [`ActivityCall`] future.
10115    pub async fn activity_typed_with_options<I, O>(
10116        &self,
10117        activity_type: impl Into<String>,
10118        options: ActivityOptions,
10119        args: I,
10120    ) -> Result<O>
10121    where
10122        I: Serialize,
10123        O: DeserializeOwned,
10124    {
10125        let activity_type = activity_type.into();
10126        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
10127            handler_type_error::<I>(
10128                HandlerKind::Activity,
10129                &activity_type,
10130                HandlerValueKind::Input,
10131                error.to_string(),
10132            )
10133        });
10134        let mut call = ActivityCall {
10135            ctx: self.clone(),
10136            activity_type: activity_type.clone(),
10137            options,
10138            worker_session: None,
10139            args: Some(encoded),
10140            scheduled: false,
10141            local: false,
10142            local_result: None,
10143            parallel_group_path: Vec::new(),
10144        };
10145        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
10146        decode_handler_result(result, HandlerKind::Activity, &activity_type)
10147    }
10148
10149    /// Schedule and join a deterministic activity/child/timer group.
10150    ///
10151    /// Nested groups retain their input shape. Every durable leaf is scheduled
10152    /// before this future yields, results are assembled by declaration order,
10153    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
10154    /// declaration path, stable group metadata, and completed siblings.
10155    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10156        ParallelCall::new(self.clone(), operations)
10157    }
10158
10159    /// Alias for [`WorkflowContext::parallel`].
10160    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10161        self.parallel(operations)
10162    }
10163
10164    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
10165    pub async fn parallel_avro_value(
10166        &self,
10167        operations: Vec<ParallelOperation>,
10168    ) -> Result<Vec<ParallelAvroResult>> {
10169        let mut call = self.parallel(operations);
10170        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10171    }
10172
10173    /// Start every durable operation and resume from the one winner persisted
10174    /// by Server. Non-winning operations continue and remain addressable.
10175    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
10176        let operations = operations
10177            .into_iter()
10178            .enumerate()
10179            .map(|(index, operation)| (SelectionKey::Index(index), operation))
10180            .collect();
10181        SelectCall::new(self.clone(), operations)
10182    }
10183
10184    /// Named-key variant of [`WorkflowContext::select`].
10185    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
10186    where
10187        K: Into<SelectionKey>,
10188    {
10189        SelectCall::new(
10190            self.clone(),
10191            operations
10192                .into_iter()
10193                .map(|(key, operation)| (key.into(), operation))
10194                .collect(),
10195        )
10196    }
10197
10198    /// Create a workflow-local deterministic compensation registry.
10199    pub fn saga(&self) -> Saga {
10200        Saga::new(self.clone())
10201    }
10202
10203    /// Whether cancellation has reached this replay's authored boundary.
10204    ///
10205    /// Server's current `/cancel` route is terminal and does not set this flag.
10206    /// A canonical service request remains pending until its committed delivery
10207    /// is consumed. Request observation alone does not authorize an exception.
10208    pub fn is_cancellation_requested(&self) -> Result<bool> {
10209        let state = self
10210            .state
10211            .lock()
10212            .map_err(|_| Error::WorkflowStatePoisoned)?;
10213        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10214            return Ok(state
10215                .scope_delivery
10216                .as_ref()
10217                .unwrap()
10218                .contexts
10219                .contains_key(&self.cancellation_scope_id));
10220        }
10221        Ok(state.cancel_requested
10222            || state
10223                .scope_delivery
10224                .as_ref()
10225                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
10226    }
10227
10228    /// Raise a typed cooperative cancellation at an author-controlled point.
10229    ///
10230    /// Passing this result to [`Saga::finish`] compensates already registered
10231    /// forward steps before the cancellation remains the initiating outcome.
10232    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
10233        let mut state = self
10234            .state
10235            .lock()
10236            .map_err(|_| Error::WorkflowStatePoisoned)?;
10237        if state.cancellation_shield_depth == 0 {
10238            if let Some(replay) = &state.scope_delivery {
10239                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
10240                    let delivered = replay
10241                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
10242                        .ok_or_else(|| {
10243                            Error::InvalidCooperativeCancellation(
10244                                "scoped request lacks its consumed original delivery".into(),
10245                            )
10246                        })?;
10247                    return Err(Error::CancellationScopeRequested(
10248                        CancellationScopeRequested {
10249                            context: context
10250                                .clone()
10251                                .with_replay(Some(Arc::downgrade(&self.state))),
10252                            delivery: delivered.boundary.clone(),
10253                        },
10254                    ));
10255                }
10256            }
10257        }
10258        if state.cancel_requested && state.cancellation_shield_depth == 0 {
10259            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10260                return Ok(());
10261            }
10262            return Err(state.cancellation_error());
10263        }
10264        Ok(())
10265    }
10266
10267    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10268        SignalCall {
10269            ctx: self.clone(),
10270            signal_name: signal_name.into(),
10271            runtime_reserved_allowed: false,
10272            opened_wait: false,
10273            matched_pending: false,
10274            parallel_group_path: Vec::new(),
10275        }
10276    }
10277
10278    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10279        SignalCall {
10280            ctx: self.clone(),
10281            signal_name: signal_name.into(),
10282            runtime_reserved_allowed: true,
10283            opened_wait: false,
10284            matched_pending: false,
10285            parallel_group_path: Vec::new(),
10286        }
10287    }
10288
10289    pub async fn wait_signal_avro_value(
10290        &self,
10291        signal_name: impl Into<String>,
10292    ) -> Result<Vec<AvroValue>> {
10293        let mut call = self.wait_signal(signal_name);
10294        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10295    }
10296
10297    /// Return every committed signal argument list with the given name.
10298    ///
10299    /// This history-backed view is deterministic and is intended for
10300    /// condition predicates that must be re-evaluated after a signal while the
10301    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10302    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10303        self.signals_avro_value(signal_name)?
10304            .into_iter()
10305            .map(|arguments| {
10306                arguments
10307                    .into_iter()
10308                    .map(AvroValue::into_json)
10309                    .collect::<Result<Vec<_>>>()
10310            })
10311            .collect()
10312    }
10313
10314    /// Lossless fixed Avro Value view of committed signals with the given name.
10315    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10316        let state = self
10317            .state
10318            .lock()
10319            .map_err(|_| Error::WorkflowStatePoisoned)?;
10320        state
10321            .history_events
10322            .iter()
10323            .filter(|event| {
10324                event.event_type == "SignalReceived"
10325                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10326            })
10327            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10328            .collect()
10329    }
10330
10331    /// Return every committed update argument list with the given name.
10332    ///
10333    /// Accepted and applied records for the same update ID are de-duplicated.
10334    /// A Server task created after an update therefore replays the workflow and
10335    /// re-evaluates an open condition without application polling.
10336    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10337        self.updates_avro_value(update_name)?
10338            .into_iter()
10339            .map(|arguments| {
10340                arguments
10341                    .into_iter()
10342                    .map(AvroValue::into_json)
10343                    .collect::<Result<Vec<_>>>()
10344            })
10345            .collect()
10346    }
10347
10348    /// Lossless fixed Avro Value view of committed updates with the given name.
10349    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10350        let state = self
10351            .state
10352            .lock()
10353            .map_err(|_| Error::WorkflowStatePoisoned)?;
10354        let mut seen = Vec::new();
10355        let mut updates = Vec::new();
10356        for event in state.history_events.iter() {
10357            if !matches!(
10358                event.event_type.as_str(),
10359                "UpdateAccepted" | "UpdateApplied"
10360            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
10361                || event.payload.get("arguments").is_none()
10362            {
10363                continue;
10364            }
10365            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
10366                if seen.iter().any(|recorded| recorded == update_id) {
10367                    continue;
10368                }
10369                seen.push(update_id.to_string());
10370            }
10371            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
10372        }
10373        Ok(updates)
10374    }
10375
10376    /// Wait for a deterministic predicate to become true or for its durable
10377    /// timeout to elapse.
10378    ///
10379    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
10380    /// predicate tokens automatically change the recorded definition
10381    /// fingerprint. Direct callers must provide an equally stable identity in
10382    /// [`ConditionWaitOptions`].
10383    pub fn wait_condition<F>(
10384        &self,
10385        options: ConditionWaitOptions,
10386        predicate: F,
10387    ) -> ConditionWaitCall
10388    where
10389        F: Fn() -> Result<bool> + Send + 'static,
10390    {
10391        ConditionWaitCall {
10392            ctx: self.clone(),
10393            options,
10394            predicate: Box::new(predicate),
10395            occurrence_id: None,
10396            opened_wait: false,
10397            parallel_group_path: Vec::new(),
10398        }
10399    }
10400
10401    /// Wait for server-backed durable time without blocking the worker executor.
10402    ///
10403    /// Polling this future emits one `start_timer` command and yields. The
10404    /// server records the deadline, so neither worker nor server restarts reset
10405    /// the wait. Replay resolves the future only from a `TimerScheduled` and
10406    /// `TimerFired` pair at the same position in the shared durable-command
10407    /// stream, with matching sequence, timer identity, and delay. Sub-second
10408    /// durations round up because protocol deadlines use whole seconds.
10409    ///
10410    /// ```no_run
10411    /// # use durable_workflow::{json, Client, Worker};
10412    /// # use std::time::Duration;
10413    /// # fn configure(client: Client) {
10414    /// let mut worker = Worker::new(client, "rust-workers");
10415    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
10416    ///     ctx.sleep(Duration::from_secs(5)).await?;
10417    ///     Ok(json!({"status": "timer fired"}))
10418    /// });
10419    /// # }
10420    /// ```
10421    pub fn sleep(&self, duration: Duration) -> TimerCall {
10422        let delay_seconds = duration
10423            .as_secs()
10424            .checked_add(u64::from(duration.subsec_nanos() > 0));
10425        TimerCall {
10426            ctx: self.clone(),
10427            delay_seconds,
10428            scheduled: false,
10429            matched_pending: false,
10430            parallel_group_path: Vec::new(),
10431        }
10432    }
10433
10434    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
10435    pub fn start_timer(&self, duration: Duration) -> TimerCall {
10436        self.sleep(duration)
10437    }
10438
10439    /// Evaluate a non-deterministic callback once and durably record its typed value.
10440    ///
10441    /// On replay the callback is not invoked: the value is decoded from the
10442    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
10443    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
10444    /// small values that must remain fixed for the lifetime of a workflow run.
10445    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
10446    where
10447        T: Serialize + DeserializeOwned,
10448        F: FnOnce() -> T,
10449    {
10450        {
10451            let mut state = self
10452                .state
10453                .lock()
10454                .map_err(|_| Error::WorkflowStatePoisoned)?;
10455            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10456                return match recorded {
10457                    RecordedCommand::SideEffect { sequence, value } => {
10458                        state.command_cursor += 1;
10459                        value.deserialize().map_err(|error| {
10460                            Error::NonDeterministicReplay(ReplayFailure::new(
10461                                "side_effect_type_mismatch",
10462                                Some(sequence),
10463                                Some(std::any::type_name::<T>().to_string()),
10464                                Some(error.to_string()),
10465                                "recorded side-effect value is incompatible with the requested Rust type",
10466                            ))
10467                        })
10468                    }
10469                    other => Err(command_mismatch(&other, "side effect")),
10470                };
10471            }
10472        }
10473
10474        let value = callback();
10475        let avro_value = AvroValue::from_serialize(&value)?;
10476        let mut state = self
10477            .state
10478            .lock()
10479            .map_err(|_| Error::WorkflowStatePoisoned)?;
10480        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
10481        state.commands.push(json!({
10482            "type": "record_side_effect",
10483            "result": result,
10484        }));
10485        Ok(value)
10486    }
10487
10488    /// Record or replay a lossless fixed Avro Value side effect.
10489    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
10490    where
10491        F: FnOnce() -> AvroValue,
10492    {
10493        {
10494            let mut state = self
10495                .state
10496                .lock()
10497                .map_err(|_| Error::WorkflowStatePoisoned)?;
10498            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10499                return match recorded {
10500                    RecordedCommand::SideEffect { value, .. } => {
10501                        state.command_cursor += 1;
10502                        Ok(value)
10503                    }
10504                    other => Err(command_mismatch(&other, "side effect")),
10505                };
10506            }
10507        }
10508
10509        let value = callback();
10510        let mut state = self
10511            .state
10512            .lock()
10513            .map_err(|_| Error::WorkflowStatePoisoned)?;
10514        let result = encode_typed_envelope(&value, &state.payload_codec)?;
10515        state.commands.push(json!({
10516            "type": "record_side_effect",
10517            "result": result,
10518        }));
10519        Ok(value)
10520    }
10521
10522    /// Append output items at a deterministic workflow command boundary.
10523    ///
10524    /// Stable idempotency keys are derived from the server-provided durable
10525    /// workflow command identity, command ordinal, and item index. Replay
10526    /// consumes the recorded side effect and never emits another append.
10527    pub fn append_workflow_stream(
10528        &self,
10529        stream_name: impl Into<String>,
10530        items: &[WorkflowStreamAppendItem],
10531        max_pending_items: Option<u64>,
10532    ) -> Result<()> {
10533        if items.is_empty() {
10534            return Err(Error::Codec(
10535                "workflow_stream_items_empty: append requires at least one item".to_string(),
10536            ));
10537        }
10538        if max_pending_items == Some(0) {
10539            return Err(Error::Codec(
10540                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
10541                    .to_string(),
10542            ));
10543        }
10544        let stream_name = stream_name.into();
10545        if stream_name.is_empty() {
10546            return Err(Error::Codec(
10547                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10548            ));
10549        }
10550
10551        let mut state = self
10552            .state
10553            .lock()
10554            .map_err(|_| Error::WorkflowStatePoisoned)?;
10555        let command_ordinal = state.workflow_stream_command_counter;
10556        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10557            state.workflow_stream_command_counter += 1;
10558            return match recorded {
10559                RecordedCommand::SideEffect { .. } => {
10560                    state.command_cursor += 1;
10561                    Ok(())
10562                }
10563                other => Err(command_mismatch(&other, "workflow stream append")),
10564            };
10565        }
10566
10567        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10568        state.workflow_stream_command_counter += 1;
10569        let wire_items = items
10570            .iter()
10571            .enumerate()
10572            .map(|(item_index, item)| {
10573                item.wire_value(Some(format!(
10574                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
10575                )))
10576            })
10577            .collect::<Vec<_>>();
10578        let mut directive = json!({
10579            "operation": "append",
10580            "stream_name": stream_name,
10581            "command_identity": identity,
10582            "command_ordinal": command_ordinal,
10583            "items": wire_items,
10584        });
10585        if let Some(max_pending_items) = max_pending_items {
10586            directive["max_pending_items"] = json!(max_pending_items);
10587        }
10588        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10589        state.commands.push(json!({
10590            "type": "record_side_effect",
10591            "result": result,
10592            "workflow_stream": directive,
10593        }));
10594        Ok(())
10595    }
10596
10597    /// Close a run-scoped output stream at a deterministic command boundary.
10598    pub fn close_workflow_stream(
10599        &self,
10600        stream_name: impl Into<String>,
10601        retention_seconds: Option<u64>,
10602    ) -> Result<()> {
10603        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
10604    }
10605
10606    /// Mark a run-scoped output stream errored at a deterministic command boundary.
10607    pub fn error_workflow_stream(
10608        &self,
10609        stream_name: impl Into<String>,
10610        error_reason: impl Into<String>,
10611        retention_seconds: Option<u64>,
10612    ) -> Result<()> {
10613        let error_reason = error_reason.into();
10614        if error_reason.is_empty() {
10615            return Err(Error::Codec(
10616                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
10617            ));
10618        }
10619        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
10620    }
10621
10622    fn finish_workflow_stream(
10623        &self,
10624        stream_name: String,
10625        error_reason: Option<String>,
10626        retention_seconds: Option<u64>,
10627    ) -> Result<()> {
10628        if stream_name.is_empty() {
10629            return Err(Error::Codec(
10630                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10631            ));
10632        }
10633        if retention_seconds == Some(0) {
10634            return Err(Error::Codec(
10635                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
10636            ));
10637        }
10638        let mut state = self
10639            .state
10640            .lock()
10641            .map_err(|_| Error::WorkflowStatePoisoned)?;
10642        let command_ordinal = state.workflow_stream_command_counter;
10643        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10644            state.workflow_stream_command_counter += 1;
10645            return match recorded {
10646                RecordedCommand::SideEffect { .. } => {
10647                    state.command_cursor += 1;
10648                    Ok(())
10649                }
10650                other => Err(command_mismatch(&other, "workflow stream close")),
10651            };
10652        }
10653        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10654        state.workflow_stream_command_counter += 1;
10655        let mut directive = json!({
10656            "operation": if error_reason.is_some() { "error" } else { "close" },
10657            "stream_name": stream_name,
10658            "command_identity": identity,
10659            "command_ordinal": command_ordinal,
10660        });
10661        if let Some(error_reason) = error_reason {
10662            directive["error_reason"] = json!(error_reason);
10663        }
10664        if let Some(retention_seconds) = retention_seconds {
10665            directive["retention_seconds"] = json!(retention_seconds);
10666        }
10667        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10668        state.commands.push(json!({
10669            "type": "record_side_effect",
10670            "result": result,
10671            "workflow_stream": directive,
10672        }));
10673        Ok(())
10674    }
10675
10676    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
10677        let identity = state.workflow_command_identity.as_str();
10678        if identity.is_empty() {
10679            return Err(Error::MissingWorkflowCommandIdentity);
10680        }
10681        Ok(identity)
10682    }
10683
10684    /// Validate, emit, or replay a typed workflow search-attribute update.
10685    ///
10686    /// The command is non-blocking within a workflow decision, but its
10687    /// `SearchAttributesUpserted` event occupies the same deterministic command
10688    /// stream as activities, timers, conditions, and other durable operations.
10689    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
10690        update.validate()?;
10691        let (attributes, attribute_types) = update.into_wire_parts();
10692        let mut state = self
10693            .state
10694            .lock()
10695            .map_err(|_| Error::WorkflowStatePoisoned)?;
10696
10697        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10698            return match recorded {
10699                RecordedCommand::SearchAttributes {
10700                    sequence,
10701                    attributes: recorded_attributes,
10702                    attribute_types: recorded_attribute_types,
10703                } => {
10704                    if recorded_attributes != attributes {
10705                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10706                            "search_attribute_value_mismatch",
10707                            Some(sequence),
10708                            Some(recorded_attributes.to_string()),
10709                            Some(attributes.to_string()),
10710                            "search-attribute values differ from the recorded durable command",
10711                        )));
10712                    }
10713                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
10714                        if recorded_types != attribute_types {
10715                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10716                                "search_attribute_type_mismatch",
10717                                Some(sequence),
10718                                Some(json!(recorded_types).to_string()),
10719                                Some(json!(attribute_types).to_string()),
10720                                "search-attribute declared types differ from the recorded durable command",
10721                            )));
10722                        }
10723                    }
10724                    state.command_cursor += 1;
10725                    Ok(())
10726                }
10727                other => Err(command_mismatch(&other, "search-attribute update")),
10728            };
10729        }
10730
10731        let mut command = serde_json::Map::from_iter([
10732            ("type".to_string(), json!("upsert_search_attributes")),
10733            ("attributes".to_string(), attributes),
10734        ]);
10735        if !attribute_types.is_empty() {
10736            command.insert("attribute_types".to_string(), json!(attribute_types));
10737        }
10738        state.commands.push(Value::Object(command));
10739        Ok(())
10740    }
10741
10742    /// Record a UUIDv4 once and return the same UUID on every replay.
10743    pub fn uuid_v4(&self) -> Result<Uuid> {
10744        self.side_effect(Uuid::new_v4)
10745    }
10746
10747    /// Select the newest supported version for a change, or replay the version
10748    /// already committed for that stable change ID.
10749    ///
10750    /// An unmarked old history that reached its next durable operation, or
10751    /// already completed, selects `-1` when that version is supported. This
10752    /// leaves the original operation available and writes no additional marker.
10753    /// Consistent markers written by older workers retain their original ordered
10754    /// positions. Repeated calls consume a matching marker at the current cursor.
10755    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
10756    pub fn get_version(
10757        &self,
10758        change_id: impl Into<String>,
10759        min_supported: i32,
10760        max_supported: i32,
10761    ) -> Result<i32> {
10762        let change_id = change_id.into();
10763        if change_id.trim().is_empty() {
10764            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10765                "version_change_id_invalid",
10766                None,
10767                Some("non-empty change ID".to_string()),
10768                Some(change_id),
10769                "version markers require a stable non-empty change ID",
10770            )));
10771        }
10772        if min_supported > max_supported {
10773            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10774                "version_range_invalid",
10775                None,
10776                Some("min_supported <= max_supported".to_string()),
10777                Some(format!("{min_supported}..={max_supported}")),
10778                "version marker supported range is invalid",
10779            )));
10780        }
10781
10782        let mut state = self
10783            .state
10784            .lock()
10785            .map_err(|_| Error::WorkflowStatePoisoned)?;
10786        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
10787            if let Some(RecordedCommand::VersionMarker {
10788                sequence: alias_sequence,
10789                change_id: alias_change_id,
10790                version: alias_version,
10791            }) = state.recorded_commands.get(state.command_cursor)
10792            {
10793                if alias_change_id == &change_id {
10794                    if *alias_version != version {
10795                        return Err(invalid_recorded_history(
10796                            "version_marker_conflict",
10797                            *alias_sequence,
10798                            &format!("selected version {version} for change ID {change_id:?}"),
10799                            &format!("recorded version {alias_version}"),
10800                            "recorded marker conflicts with the decision already selected during replay",
10801                        ));
10802                    }
10803                    ensure_version_supported(
10804                        &change_id,
10805                        version,
10806                        min_supported,
10807                        max_supported,
10808                        *alias_sequence,
10809                    )?;
10810                    // Older workers could record the same decision again. Keep
10811                    // each physical boundary without skipping intervening work.
10812                    state.command_cursor += 1;
10813                    return Ok(version);
10814                }
10815            }
10816            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
10817            return Ok(version);
10818        }
10819
10820        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10821            return match recorded {
10822                RecordedCommand::VersionMarker {
10823                    sequence,
10824                    change_id: recorded_change_id,
10825                    version,
10826                    ..
10827                } => {
10828                    if recorded_change_id != change_id {
10829                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10830                            "version_change_id_mismatch",
10831                            Some(sequence),
10832                            Some(recorded_change_id),
10833                            Some(change_id),
10834                            "recorded version marker change ID differs from current workflow code",
10835                        )));
10836                    }
10837                    ensure_version_supported(
10838                        &change_id,
10839                        version,
10840                        min_supported,
10841                        max_supported,
10842                        sequence,
10843                    )?;
10844                    state.command_cursor += 1;
10845                    state.version_markers.insert(change_id, (version, sequence));
10846                    Ok(version)
10847                }
10848                other => {
10849                    let version = -1;
10850                    let sequence = other.sequence();
10851                    ensure_version_supported(
10852                        &change_id,
10853                        version,
10854                        min_supported,
10855                        max_supported,
10856                        sequence,
10857                    )?;
10858                    // The existing operation proves this patch site was reached
10859                    // before its marker existed. Keep its original cursor.
10860                    state.version_markers.insert(change_id, (version, sequence));
10861                    Ok(version)
10862                }
10863            };
10864        }
10865
10866        if state
10867            .history_events
10868            .iter()
10869            .any(|event| event.event_type == "WorkflowCompleted")
10870        {
10871            let version = -1;
10872            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
10873            state.version_markers.insert(change_id, (version, 0));
10874            return Ok(version);
10875        }
10876
10877        let version = max_supported;
10878        state.commands.push(json!({
10879            "type": "record_version_marker",
10880            "change_id": change_id,
10881            "version": version,
10882            "min_supported": min_supported,
10883            "max_supported": max_supported,
10884        }));
10885        // Sequence numbers are assigned by the server. Zero identifies a marker
10886        // selected in this uncommitted decision batch for duplicate-call checks.
10887        state.version_markers.insert(change_id, (version, 0));
10888        Ok(version)
10889    }
10890
10891    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
10892    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
10893        Ok(self.get_version(change_id, -1, 1)? == 1)
10894    }
10895
10896    /// Keep a patch marker in history after the legacy branch has been removed.
10897    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
10898        self.get_version(change_id, -1, 1).map(|_| ())
10899    }
10900
10901    /// Merge non-indexed workflow memo metadata through durable history.
10902    ///
10903    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
10904    /// public Avro payload envelope consumed by Server and Cloud runtimes.
10905    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
10906        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
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 match recorded {
10914                RecordedCommand::Memo {
10915                    sequence,
10916                    entries: recorded_entries,
10917                } => {
10918                    if recorded_entries != entries {
10919                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10920                            "memo_update_mismatch",
10921                            Some(sequence),
10922                            Some(format!("{recorded_entries:?}")),
10923                            Some(format!("{entries:?}")),
10924                            "recorded memo entries differ from the current workflow update",
10925                        )));
10926                    }
10927                    state.command_cursor += 1;
10928                    Ok(())
10929                }
10930                other => Err(command_mismatch(&other, "memo upsert")),
10931            };
10932        }
10933
10934        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
10935        state.commands.push(json!({
10936            "type": "upsert_memo",
10937            "entries": entries_envelope,
10938        }));
10939        Ok(())
10940    }
10941
10942    /// Start a named durable child on an explicit queue and await its result.
10943    ///
10944    /// The command is recorded in the parent's sequence-ordered durable command
10945    /// stream. Replay keeps a scheduled child pending without emitting another
10946    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
10947    /// values preserve the history payload codec and include both sides of the
10948    /// durable relationship; failures are returned as
10949    /// [`Error::ChildWorkflowFailed`].
10950    ///
10951    /// ```no_run
10952    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10953    /// # fn configure(client: Client) {
10954    /// let mut worker = Worker::new(client, "parent-workers");
10955    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10956    ///     let child = ctx
10957    ///         .start_child_workflow(
10958    ///             "fulfil-order",
10959    ///             ChildWorkflowOptions::new("fulfilment-workers")
10960    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10961    ///             json!([{"order_id": "order-42"}]),
10962    ///         )
10963    ///         .await?;
10964    ///     Ok(child.result)
10965    /// });
10966    /// # }
10967    /// ```
10968    pub fn start_child_workflow<T: Serialize>(
10969        &self,
10970        workflow_type: impl Into<String>,
10971        options: ChildWorkflowOptions,
10972        args: T,
10973    ) -> ChildWorkflowCall {
10974        ChildWorkflowCall {
10975            ctx: self.clone(),
10976            workflow_type: workflow_type.into(),
10977            options,
10978            args: Some(AvroValue::from_serialize(&args)),
10979            scheduled: false,
10980            matched_pending: false,
10981            parallel_group_path: Vec::new(),
10982        }
10983    }
10984
10985    pub async fn start_child_workflow_avro_value<T: Serialize>(
10986        &self,
10987        workflow_type: impl Into<String>,
10988        options: ChildWorkflowOptions,
10989        args: T,
10990    ) -> Result<ChildWorkflowAvroResult> {
10991        let mut call = self.start_child_workflow(workflow_type, options, args);
10992        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10993    }
10994
10995    fn take_commands(&self) -> Result<Vec<Value>> {
10996        let mut state = self
10997            .state
10998            .lock()
10999            .map_err(|_| Error::WorkflowStatePoisoned)?;
11000        Ok(std::mem::take(&mut state.commands))
11001    }
11002
11003    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
11004        let mut state = self
11005            .state
11006            .lock()
11007            .map_err(|_| Error::WorkflowStatePoisoned)?;
11008
11009        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11010            return Err(command_mismatch(&recorded, "continue as new"));
11011        }
11012        if state.recorded_continue_as_new_sequence.is_some() {
11013            state.continue_as_new_consumed = true;
11014            return Ok(None);
11015        }
11016
11017        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
11018        let mut command = serde_json::Map::from_iter([
11019            ("type".to_string(), json!("continue_as_new")),
11020            ("arguments".to_string(), arguments),
11021            ("queue".to_string(), json!(state.task_queue.clone())),
11022        ]);
11023        if let Some(workflow_type) = request.options.workflow_type {
11024            command.insert("workflow_type".to_string(), json!(workflow_type));
11025        }
11026        if let Some(task_queue) = request.options.task_queue {
11027            command.insert("queue".to_string(), json!(task_queue));
11028        }
11029        Ok(Some(Value::Object(command)))
11030    }
11031
11032    fn matched_recorded_pending(&self) -> Result<bool> {
11033        let state = self
11034            .state
11035            .lock()
11036            .map_err(|_| Error::WorkflowStatePoisoned)?;
11037        Ok(state.matched_recorded_pending)
11038    }
11039
11040    fn ensure_history_consumed(&self) -> Result<()> {
11041        let state = self
11042            .state
11043            .lock()
11044            .map_err(|_| Error::WorkflowStatePoisoned)?;
11045        if let Some(replay) = &state.scope_delivery {
11046            if let Some((&sequence, _)) = replay
11047                .canonical
11048                .deliveries
11049                .iter()
11050                .find(|(sequence, _)| !replay.consumed.contains(sequence))
11051            {
11052                return Err(invalid_recorded_history(
11053                    "cancellation_scope_delivery_unconsumed",
11054                    sequence,
11055                    "original scoped delivery",
11056                    "workflow completion",
11057                    "workflow completed without consuming its committed scope delivery",
11058                ));
11059            }
11060        }
11061        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
11062            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11063                "recorded_commands_unconsumed",
11064                Some(command.sequence()),
11065                Some(command.shape().to_string()),
11066                Some("workflow completion".to_string()),
11067                "workflow completed before consuming all recorded durable commands",
11068            )));
11069        }
11070        if let Some(delivery) = state
11071            .cancellation_history
11072            .delivery
11073            .as_ref()
11074            .filter(|_| !state.cancellation_consumed)
11075        {
11076            return Err(invalid_recorded_history(
11077                "cooperative_cancellation_unconsumed",
11078                delivery.sequence,
11079                "committed cancellation call",
11080                "workflow completion",
11081                "workflow completed without reaching its committed cancellation boundary",
11082            ));
11083        }
11084        if let Some(sequence) = state
11085            .recorded_continue_as_new_sequence
11086            .filter(|_| !state.continue_as_new_consumed)
11087        {
11088            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11089                "recorded_continue_as_new_unconsumed",
11090                Some(sequence),
11091                Some("continue as new".to_string()),
11092                Some("workflow completion".to_string()),
11093                "workflow completed without consuming its recorded continue-as-new transition",
11094            )));
11095        }
11096        Ok(())
11097    }
11098}
11099
11100fn contiguous_message_stream_count(
11101    pending: &[MessageStreamMessage],
11102    cursor: u64,
11103    max_items: usize,
11104) -> usize {
11105    pending
11106        .iter()
11107        .take(max_items)
11108        .enumerate()
11109        .take_while(|(offset, message)| {
11110            u64::try_from(*offset)
11111                .ok()
11112                .and_then(|offset| cursor.checked_add(offset + 1))
11113                == Some(message.position)
11114        })
11115        .count()
11116}
11117
11118fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
11119    matches!(
11120        event.event_type.as_str(),
11121        "ActivityScheduled"
11122            | "TimerScheduled"
11123            | "ChildWorkflowScheduled"
11124            | "SignalWaitOpened"
11125            | "ConditionWaitOpened"
11126            | "SearchAttributesUpserted"
11127            | "SideEffectRecorded"
11128            | "VersionMarkerRecorded"
11129            | "MemoUpserted"
11130            | "WorkflowContinuedAsNew"
11131    )
11132}
11133
11134#[derive(Debug)]
11135struct WorkflowState {
11136    workflow_id: Option<String>,
11137    run_id: Option<String>,
11138    task_queue: String,
11139    payload_codec: String,
11140    history_events: Arc<Vec<HistoryEvent>>,
11141    history_budget: WorkflowHistoryBudget,
11142    cancel_requested: bool,
11143    cancellation_history: CancellationHistory,
11144    cancellation_consumed: bool,
11145    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
11146    cancellation_shield_depth: u64,
11147    cancellation_delivery_enabled: bool,
11148    cancellation_delivery_intent: Option<CancellationDelivery>,
11149    cancellation_delivery_command_count: usize,
11150    allow_cancellation_scope_authoring: bool,
11151    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
11152    cancellation_scope_memberships: BTreeMap<u64, String>,
11153    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
11154    resume_signal: Option<ResumeSignal>,
11155    recorded_commands: Vec<RecordedCommand>,
11156    selection_markers: Vec<SelectionMarker>,
11157    selection_marker_cursor: usize,
11158    cancelled_selection_members: Vec<SelectionCancellation>,
11159    recorded_continue_as_new_sequence: Option<u64>,
11160    continue_as_new_consumed: bool,
11161    command_cursor: usize,
11162    condition_wait_occurrence_counter: u64,
11163    matched_recorded_pending: bool,
11164    version_markers: HashMap<String, (i32, u64)>,
11165    workflow_command_identity: String,
11166    workflow_stream_command_counter: u64,
11167    commands: Vec<Value>,
11168    local_activity_requests: Vec<local_activity::Request>,
11169    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
11170    message_stream_cursors: HashMap<String, u64>,
11171    message_stream_waits: HashMap<String, u64>,
11172}
11173
11174impl WorkflowState {
11175    #[cfg(test)]
11176    fn new(
11177        history: Vec<HistoryEvent>,
11178        task_queue: String,
11179        payload_codec: String,
11180        resume_signal: Option<ResumeSignal>,
11181    ) -> Result<Self> {
11182        Self::new_with_identity(
11183            history,
11184            None,
11185            None,
11186            task_queue,
11187            payload_codec,
11188            resume_signal,
11189        )
11190    }
11191
11192    fn new_with_identity(
11193        history: Vec<HistoryEvent>,
11194        workflow_id: Option<String>,
11195        run_id: Option<String>,
11196        task_queue: String,
11197        payload_codec: String,
11198        resume_signal: Option<ResumeSignal>,
11199    ) -> Result<Self> {
11200        Self::new_with_identity_and_scopes(
11201            history,
11202            workflow_id,
11203            run_id,
11204            task_queue,
11205            payload_codec,
11206            resume_signal,
11207            false,
11208        )
11209    }
11210
11211    fn new_with_identity_and_scopes(
11212        history: Vec<HistoryEvent>,
11213        workflow_id: Option<String>,
11214        run_id: Option<String>,
11215        task_queue: String,
11216        payload_codec: String,
11217        resume_signal: Option<ResumeSignal>,
11218        allow_cancellation_scope_authoring: bool,
11219    ) -> Result<Self> {
11220        Self::new_with_identity_and_scope_delivery(
11221            history,
11222            workflow_id,
11223            run_id,
11224            task_queue,
11225            payload_codec,
11226            resume_signal,
11227            allow_cancellation_scope_authoring,
11228            false,
11229        )
11230    }
11231
11232    fn new_with_identity_and_scope_delivery(
11233        history: Vec<HistoryEvent>,
11234        workflow_id: Option<String>,
11235        run_id: Option<String>,
11236        task_queue: String,
11237        payload_codec: String,
11238        resume_signal: Option<ResumeSignal>,
11239        allow_cancellation_scope_authoring: bool,
11240        allow_cancellation_scope_delivery: bool,
11241    ) -> Result<Self> {
11242        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11243            &history,
11244            allow_cancellation_scope_authoring,
11245            allow_cancellation_scope_delivery,
11246        )?;
11247        let scopes = if allow_cancellation_scope_authoring {
11248            cancellation_scope::CancellationScopeHistory::read(
11249                &history,
11250                run_id.as_deref().unwrap_or_default(),
11251            )?
11252        } else {
11253            cancellation_scope::CancellationScopeHistory::default()
11254        };
11255        let cancellation_history = CancellationHistory::from_events(
11256            &history,
11257            run_id.as_deref().unwrap_or_default(),
11258            None,
11259        )?;
11260        if allow_cancellation_scope_authoring
11261            && cancellation_history.request.is_some()
11262            && !allow_cancellation_scope_delivery
11263        {
11264            return Err(Error::CancellationScopeExecutionUnavailable);
11265        }
11266        let scope_delivery = if allow_cancellation_scope_delivery {
11267            Some(cancellation_scope_replay::ScopeReplay::read(
11268                &history,
11269                &scopes,
11270                run_id.as_deref().unwrap_or_default(),
11271                workflow_id.as_deref().unwrap_or_default(),
11272            )?)
11273        } else {
11274            None
11275        };
11276        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
11277            &history,
11278            &payload_codec,
11279            WorkflowIdentity {
11280                workflow_id: workflow_id.clone(),
11281                run_id: run_id.clone(),
11282            },
11283        )?)?;
11284        for (sequence, opening) in &scopes.openings {
11285            if recorded_commands
11286                .iter()
11287                .any(|command| command.sequence() == *sequence)
11288            {
11289                return Err(invalid_recorded_history(
11290                    "invalid_cancellation_scope_history",
11291                    *sequence,
11292                    "distinct authored scope opening",
11293                    "operation collision",
11294                    "scope opening collides with a command",
11295                ));
11296            }
11297            recorded_commands.push(RecordedCommand::CancellationScope {
11298                sequence: *sequence,
11299                scope_id: opening.scope_id.clone(),
11300                parent_scope_id: opening.parent_scope_id.clone(),
11301                shield_parent: opening.shield_parent,
11302            });
11303        }
11304        recorded_commands.sort_by_key(RecordedCommand::sequence);
11305        if let Some(replay) = &scope_delivery {
11306            replay.bind_commands(&mut recorded_commands)?;
11307        }
11308        let selection_markers = recorded_selection_markers(&history)?;
11309        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11310        let recorded_continue_as_new = history
11311            .iter()
11312            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11313            .collect::<Vec<_>>();
11314        if recorded_continue_as_new.len() > 1 {
11315            return Err(invalid_recorded_history(
11316                "duplicate_continue_as_new_transition",
11317                recorded_continue_as_new
11318                    .last()
11319                    .and_then(|event| durable_event_sequence(event))
11320                    .unwrap_or(0),
11321                "one WorkflowContinuedAsNew event",
11322                &format!(
11323                    "{} WorkflowContinuedAsNew events",
11324                    recorded_continue_as_new.len()
11325                ),
11326                "workflow history records one continue-as-new transition more than once",
11327            ));
11328        }
11329        let recorded_continue_as_new_sequence = recorded_continue_as_new
11330            .first()
11331            .map(|event| {
11332                durable_event_sequence(event).ok_or_else(|| {
11333                    Error::NonDeterministicReplay(ReplayFailure::new(
11334                        "continue_as_new_sequence_missing",
11335                        None,
11336                        Some("recorded transition sequence".to_string()),
11337                        Some("missing sequence".to_string()),
11338                        "WorkflowContinuedAsNew history is missing its recorded sequence",
11339                    ))
11340                })
11341            })
11342            .transpose()?;
11343        let mut message_stream_cursors = HashMap::new();
11344        for event in &history {
11345            if !matches!(
11346                event.event_type.as_str(),
11347                "SignalReceived" | "SignalApplied"
11348            ) || event.payload.get("signal_name").and_then(Value::as_str)
11349                != Some(MESSAGE_STREAM_SIGNAL)
11350            {
11351                continue;
11352            }
11353            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
11354            if arguments.len() != 1 {
11355                continue;
11356            }
11357            let envelope = arguments[0].clone().into_json()?;
11358            let Some(envelope) = envelope.as_object() else {
11359                continue;
11360            };
11361            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
11362            {
11363                continue;
11364            }
11365            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11366                continue;
11367            };
11368            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11369            else {
11370                continue;
11371            };
11372            let cursor = message_stream_cursors
11373                .entry(stream_name.to_string())
11374                .or_insert(0);
11375            *cursor = (*cursor).max(through_position);
11376        }
11377        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
11378        let cancel_requested = history.iter().any(|event| {
11379            matches!(
11380                event.event_type.as_str(),
11381                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
11382            )
11383        });
11384        let cancellation_clock = cancellation_history
11385            .request
11386            .as_ref()
11387            .and_then(|request| request.context.as_ref())
11388            .map(|_| {
11389                cancellation_replay_clock::ReplayClock::new(
11390                    &history,
11391                    &recorded_commands,
11392                    cancellation_history.delivery_index,
11393                )
11394            })
11395            .or_else(|| {
11396                scope_delivery.as_ref().map(|_| {
11397                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
11398                })
11399            });
11400        Ok(Self {
11401            workflow_command_identity: String::new(),
11402            workflow_stream_command_counter: 0,
11403            workflow_id,
11404            run_id,
11405            task_queue,
11406            payload_codec,
11407            history_events: Arc::new(history),
11408            history_budget: WorkflowHistoryBudget {
11409                event_count,
11410                ..WorkflowHistoryBudget::default()
11411            },
11412            cancel_requested,
11413            cancellation_history,
11414            cancellation_consumed: false,
11415            cancellation_clock,
11416            cancellation_shield_depth: 0,
11417            cancellation_delivery_enabled: false,
11418            cancellation_delivery_intent: None,
11419            cancellation_delivery_command_count: 0,
11420            allow_cancellation_scope_authoring,
11421            cancellation_scope_opening: None,
11422            cancellation_scope_memberships: scopes.memberships,
11423            scope_delivery,
11424            resume_signal,
11425            recorded_commands,
11426            selection_markers,
11427            selection_marker_cursor: 0,
11428            cancelled_selection_members,
11429            recorded_continue_as_new_sequence,
11430            continue_as_new_consumed: false,
11431            command_cursor: 0,
11432            condition_wait_occurrence_counter: 0,
11433            matched_recorded_pending: false,
11434            version_markers: HashMap::new(),
11435            commands: Vec::new(),
11436            local_activity_requests: Vec::new(),
11437            message_stream_messages: HashMap::new(),
11438            message_stream_cursors,
11439            message_stream_waits: HashMap::new(),
11440        })
11441    }
11442}
11443
11444enum MessageStreamDelivery {
11445    Message(MessageStreamMessage),
11446    Cursor {
11447        stream_name: String,
11448        through_position: u64,
11449    },
11450}
11451
11452fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
11453    if arguments.len() != 1 {
11454        return Ok(None);
11455    }
11456    let envelope = arguments
11457        .into_iter()
11458        .next()
11459        .expect("one argument was checked");
11460    let Some(envelope) = envelope.as_object() else {
11461        return Ok(None);
11462    };
11463    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11464        return Ok(None);
11465    };
11466    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
11467        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11468        else {
11469            return Ok(None);
11470        };
11471        return Ok(Some(MessageStreamDelivery::Cursor {
11472            stream_name: stream_name.to_string(),
11473            through_position,
11474        }));
11475    }
11476    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
11477        return Ok(None);
11478    }
11479    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
11480        return Ok(None);
11481    };
11482    let Some(position) = envelope
11483        .get("position")
11484        .and_then(Value::as_u64)
11485        .filter(|value| *value > 0)
11486    else {
11487        return Ok(None);
11488    };
11489    let Some(payload_envelope) = envelope.get("payload_envelope") else {
11490        return Ok(None);
11491    };
11492    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
11493    else {
11494        return Ok(None);
11495    };
11496    let decoded = decode_avro_value(&payload_envelope)?;
11497    let AvroValue::Array(values) = decoded else {
11498        return Ok(None);
11499    };
11500    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
11501        stream_name: stream_name.to_string(),
11502        message_id: message_id.to_string(),
11503        position,
11504        arguments: values,
11505    })))
11506}
11507
11508#[derive(Clone, Debug)]
11509enum RecordedCommand {
11510    ServiceOperation {
11511        sequence: u64,
11512        call: nexus::RecordedServiceCall,
11513    },
11514    CancellationScope {
11515        sequence: u64,
11516        scope_id: String,
11517        parent_scope_id: String,
11518        shield_parent: bool,
11519    },
11520    CancellationGroup {
11521        sequence: u64,
11522        span: u64,
11523        original: Vec<RecordedCommand>,
11524    },
11525    CancellationBoundary {
11526        sequence: u64,
11527        call_kind: CancellationCallKind,
11528        original: Option<Box<RecordedCommand>>,
11529    },
11530    Activity {
11531        sequence: u64,
11532        activity_type: Option<String>,
11533        cancellation_policy: String,
11534        options: Option<RecordedActivityOptions>,
11535        outcome: Option<ActivityOutcome>,
11536        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11537    },
11538    Timer {
11539        sequence: u64,
11540        delay_seconds: u64,
11541        fired: bool,
11542        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11543    },
11544    ChildWorkflow {
11545        sequence: u64,
11546        workflow_type: Option<String>,
11547        policies: RecordedChildPolicies,
11548        outcome: Option<ChildWorkflowOutcome>,
11549        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11550    },
11551    SignalWait {
11552        sequence: u64,
11553        signal_name: String,
11554        value: Option<Vec<AvroValue>>,
11555        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11556    },
11557    ConditionWait {
11558        sequence: u64,
11559        occurrence_id: String,
11560        condition_key: Option<String>,
11561        predicate_identity: String,
11562        timeout_seconds: Option<u64>,
11563        result: Option<ConditionWaitResult>,
11564        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11565    },
11566    SearchAttributes {
11567        sequence: u64,
11568        attributes: Value,
11569        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
11570    },
11571    SideEffect {
11572        sequence: u64,
11573        value: AvroValue,
11574    },
11575    VersionMarker {
11576        sequence: u64,
11577        change_id: String,
11578        version: i32,
11579    },
11580    Memo {
11581        sequence: u64,
11582        entries: AvroValue,
11583    },
11584}
11585
11586#[derive(Clone, Debug, PartialEq, Eq)]
11587struct SelectionMarker {
11588    selection_group_id: String,
11589    selection_group_base_sequence: u64,
11590    selection_group_size: usize,
11591    member_key: SelectionKey,
11592    member_index: usize,
11593    member_base_sequence: u64,
11594    member_size: usize,
11595    operation_kind: String,
11596    operation_identity: String,
11597    outcome: String,
11598    resolution_event_id: String,
11599    resolution_event_type: String,
11600}
11601
11602#[derive(Clone, Debug, PartialEq, Eq)]
11603struct SelectionCancellation {
11604    selection_group_id: String,
11605    member_key: SelectionKey,
11606    member_index: usize,
11607    member_base_sequence: u64,
11608    member_size: usize,
11609    operation_kind: String,
11610    operation_identity: String,
11611}
11612
11613fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
11614    let mut markers: Vec<SelectionMarker> = Vec::new();
11615    for event in events
11616        .iter()
11617        .filter(|event| event.event_type == "SelectionResolved")
11618    {
11619        let payload = &event.payload;
11620        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
11621        let group_size = required_selection_usize(payload, "selection_group_size")?;
11622        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
11623        let member_size = required_selection_usize(payload, "member_size")?;
11624        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
11625        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
11626            invalid_recorded_history(
11627                "selection_marker_invalid",
11628                base_sequence,
11629                "non-empty selection_group_id",
11630                &payload.to_string(),
11631                "selection winner history is missing its durable group identity",
11632            )
11633        })?;
11634        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
11635        if group_id != expected_group_id {
11636            return Err(invalid_recorded_history(
11637                "selection_marker_invalid",
11638                base_sequence,
11639                &expected_group_id,
11640                &group_id,
11641                "selection winner history contains an incompatible group identity",
11642            ));
11643        }
11644        let group_end = base_sequence
11645            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
11646            .unwrap_or(u64::MAX);
11647        let member_end = member_base_sequence
11648            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
11649            .unwrap_or(u64::MAX);
11650        if member_index >= group_size
11651            || member_base_sequence < base_sequence
11652            || member_end > group_end
11653        {
11654            return Err(invalid_recorded_history(
11655                "selection_marker_invalid",
11656                base_sequence,
11657                "winner member within selection group bounds",
11658                &payload.to_string(),
11659                "selection winner history contains an invalid member range",
11660            ));
11661        }
11662        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
11663            invalid_recorded_history(
11664                "selection_marker_invalid",
11665                base_sequence,
11666                "selection operation kind",
11667                &payload.to_string(),
11668                "selection winner history is missing its operation kind",
11669            )
11670        })?;
11671        if !matches!(
11672            operation_kind.as_str(),
11673            "activity" | "child" | "timer" | "signal" | "condition" | "group"
11674        ) {
11675            return Err(invalid_recorded_history(
11676                "selection_marker_invalid",
11677                base_sequence,
11678                "activity, child, timer, signal, condition, or group",
11679                &operation_kind,
11680                "selection winner history contains an unsupported operation kind",
11681            ));
11682        }
11683        let operation_identity =
11684            payload_string(payload, "operation_identity").ok_or_else(|| {
11685                invalid_recorded_history(
11686                    "selection_marker_invalid",
11687                    base_sequence,
11688                    "non-empty operation identity",
11689                    &payload.to_string(),
11690                    "selection winner history is missing its durable operation identity",
11691                )
11692            })?;
11693        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
11694            invalid_recorded_history(
11695                "selection_marker_invalid",
11696                base_sequence,
11697                "completed or failed selection outcome",
11698                &payload.to_string(),
11699                "selection winner history is missing its outcome",
11700            )
11701        })?;
11702        if !matches!(outcome.as_str(), "completed" | "failed") {
11703            return Err(invalid_recorded_history(
11704                "selection_marker_invalid",
11705                base_sequence,
11706                "completed or failed selection outcome",
11707                &outcome,
11708                "selection winner history contains an unsupported outcome",
11709            ));
11710        }
11711        let marker = SelectionMarker {
11712            selection_group_id: group_id,
11713            selection_group_base_sequence: base_sequence,
11714            selection_group_size: group_size,
11715            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
11716            member_index,
11717            member_base_sequence,
11718            member_size,
11719            operation_kind,
11720            operation_identity,
11721            outcome,
11722            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
11723                || {
11724                    invalid_recorded_history(
11725                        "selection_marker_invalid",
11726                        base_sequence,
11727                        "durable resolution_event_id",
11728                        &payload.to_string(),
11729                        "selection winner history is missing its terminal event identity",
11730                    )
11731                },
11732            )?,
11733            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
11734                || {
11735                    invalid_recorded_history(
11736                        "selection_marker_invalid",
11737                        base_sequence,
11738                        "durable resolution_event_type",
11739                        &payload.to_string(),
11740                        "selection winner history is missing its terminal event type",
11741                    )
11742                },
11743            )?,
11744        };
11745        if let Some(existing) = markers
11746            .iter()
11747            .find(|existing| existing.selection_group_id == marker.selection_group_id)
11748        {
11749            if existing != &marker {
11750                return Err(invalid_recorded_history(
11751                    "selection_marker_conflict",
11752                    base_sequence,
11753                    &format!("one winner for {}", marker.selection_group_id),
11754                    &payload.to_string(),
11755                    "selection history records conflicting winners for one durable group",
11756                ));
11757            }
11758            continue;
11759        }
11760        markers.push(marker);
11761    }
11762    Ok(markers)
11763}
11764
11765fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
11766    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
11767    for event in events
11768        .iter()
11769        .filter(|event| event.event_type == "SelectionOperationCancelled")
11770    {
11771        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
11772            invalid_recorded_history(
11773                "selection_cancellation_invalid",
11774                0,
11775                "non-empty selection_group_id",
11776                &event.payload.to_string(),
11777                "selection cancellation history is missing its group identity",
11778            )
11779        })?;
11780        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
11781        let marker = SelectionCancellation {
11782            selection_group_id: group_id,
11783            member_key: selection_key_from_value(
11784                event.payload.get("member_key"),
11785                member_base_sequence,
11786            )?,
11787            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
11788            member_base_sequence,
11789            member_size: required_selection_usize(&event.payload, "member_size")?,
11790            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
11791                invalid_recorded_history(
11792                    "selection_cancellation_invalid",
11793                    member_base_sequence,
11794                    "selection operation kind",
11795                    &event.payload.to_string(),
11796                    "selection cancellation is missing its operation kind",
11797                )
11798            })?,
11799            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
11800                || {
11801                    invalid_recorded_history(
11802                        "selection_cancellation_invalid",
11803                        member_base_sequence,
11804                        "selection operation identity",
11805                        &event.payload.to_string(),
11806                        "selection cancellation is missing its operation identity",
11807                    )
11808                },
11809            )?,
11810        };
11811        if let Some(existing) = cancelled.iter().find(|recorded| {
11812            recorded.selection_group_id == marker.selection_group_id
11813                && recorded.member_base_sequence == marker.member_base_sequence
11814        }) {
11815            if existing != &marker {
11816                return Err(invalid_recorded_history(
11817                    "selection_cancellation_conflict",
11818                    member_base_sequence,
11819                    "one stable SelectionOperationCancelled marker",
11820                    &event.payload.to_string(),
11821                    "selection cancellation history contains conflicting member metadata",
11822                ));
11823            }
11824        } else {
11825            cancelled.push(marker);
11826        }
11827    }
11828    Ok(cancelled)
11829}
11830
11831fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
11832    payload
11833        .get(field)
11834        .and_then(value_as_u64)
11835        .filter(|value| *value > 0)
11836        .ok_or_else(|| {
11837            invalid_recorded_history(
11838                "selection_marker_invalid",
11839                0,
11840                &format!("positive integer {field}"),
11841                &payload.to_string(),
11842                "selection history contains invalid durable identity metadata",
11843            )
11844        })
11845}
11846
11847fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
11848    required_selection_usize_allow_zero(payload, field).and_then(|value| {
11849        if value > 0 {
11850            Ok(value)
11851        } else {
11852            Err(invalid_recorded_history(
11853                "selection_marker_invalid",
11854                0,
11855                &format!("positive integer {field}"),
11856                &payload.to_string(),
11857                "selection history contains invalid durable identity metadata",
11858            ))
11859        }
11860    })
11861}
11862
11863fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
11864    payload
11865        .get(field)
11866        .and_then(value_as_u64)
11867        .and_then(|value| usize::try_from(value).ok())
11868        .ok_or_else(|| {
11869            invalid_recorded_history(
11870                "selection_marker_invalid",
11871                0,
11872                &format!("non-negative integer {field}"),
11873                &payload.to_string(),
11874                "selection history contains invalid durable identity metadata",
11875            )
11876        })
11877}
11878
11879#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11880struct RecordedActivityOptions {
11881    task_queue: RecordedSnapshotValue<Option<String>>,
11882    execution_mode: RecordedSnapshotValue<Option<String>>,
11883    retry_policy: ActivityRetrySnapshot,
11884    worker_session: Option<Value>,
11885}
11886
11887#[derive(Clone, Debug)]
11888struct RecordedChildPolicies {
11889    parent_close_policy: String,
11890    cancellation_policy: String,
11891}
11892
11893fn recorded_activity_cancellation_policy(
11894    events: &[&HistoryEvent],
11895    sequence: u64,
11896) -> Result<String> {
11897    let mut policy: Option<String> = None;
11898    for event in events.iter().filter(|event| {
11899        matches!(
11900            event.event_type.as_str(),
11901            "ActivityScheduled"
11902                | "ActivityStarted"
11903                | "ActivityCompleted"
11904                | "ActivityFailed"
11905                | "ActivityTimedOut"
11906                | "ActivityCancelled"
11907        )
11908    }) {
11909        for source in [Some(&event.payload), event.payload.get("activity")]
11910            .into_iter()
11911            .flatten()
11912        {
11913            let Some(value) = source.get("cancellation_policy") else {
11914                continue;
11915            };
11916            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
11917                value.as_str()
11918            else {
11919                return Err(invalid_recorded_history(
11920                    "invalid_activity_cancellation_policy_history",
11921                    sequence,
11922                    "supported Activity cancellation policy",
11923                    &value.to_string(),
11924                    "Activity history contains an invalid cancellation policy",
11925                ));
11926            };
11927            if let Some(previous) = policy.as_deref() {
11928                if previous != incoming {
11929                    return Err(invalid_recorded_history(
11930                        "activity_cancellation_policy_history_conflict",
11931                        sequence,
11932                        previous,
11933                        incoming,
11934                        "Activity cancellation policy changed between history events",
11935                    ));
11936                }
11937            }
11938            policy = Some(incoming.to_string());
11939        }
11940        policy.get_or_insert_with(|| "try_cancel".to_string());
11941    }
11942    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
11943}
11944
11945fn recorded_child_policy_value<'a>(
11946    payload: &'a Value,
11947    field: &str,
11948    sequence: u64,
11949) -> Result<Option<&'a str>> {
11950    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
11951        return Ok(None);
11952    };
11953    let valid = match (field, value.as_str()) {
11954        (
11955            "parent_close_policy",
11956            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11957        ) => true,
11958        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11959            true
11960        }
11961        _ => false,
11962    };
11963    if !valid {
11964        return Err(invalid_recorded_history(
11965            "invalid_child_workflow_policy_history",
11966            sequence,
11967            "supported child workflow policy",
11968            &value.to_string(),
11969            "child workflow history contains an invalid policy",
11970        ));
11971    }
11972    Ok(value.as_str())
11973}
11974
11975fn recorded_child_policies(
11976    events: &[&HistoryEvent],
11977    scheduled: &HistoryEvent,
11978    sequence: u64,
11979) -> Result<RecordedChildPolicies> {
11980    let parent_close_policy =
11981        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11982            .unwrap_or("abandon")
11983            .to_string();
11984    let cancellation_policy =
11985        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11986            .unwrap_or("abandon")
11987            .to_string();
11988    for event in events {
11989        for (field, expected) in [
11990            ("parent_close_policy", parent_close_policy.as_str()),
11991            ("cancellation_policy", cancellation_policy.as_str()),
11992        ] {
11993            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11994                if actual != expected {
11995                    return Err(invalid_recorded_history(
11996                        "child_workflow_policy_history_conflict",
11997                        sequence,
11998                        expected,
11999                        actual,
12000                        "child workflow policy changed between history events",
12001                    ));
12002                }
12003            }
12004        }
12005    }
12006    Ok(RecordedChildPolicies {
12007        parent_close_policy,
12008        cancellation_policy,
12009    })
12010}
12011
12012fn ensure_child_policies_match(
12013    sequence: u64,
12014    recorded: &RecordedChildPolicies,
12015    current: &ChildWorkflowOptions,
12016) -> Result<()> {
12017    for (field, expected, actual) in [
12018        (
12019            "parent_close_policy",
12020            recorded.parent_close_policy.as_str(),
12021            current.parent_close_policy.as_str(),
12022        ),
12023        (
12024            "cancellation_policy",
12025            recorded.cancellation_policy.as_str(),
12026            current.cancellation_policy.as_str(),
12027        ),
12028    ] {
12029        if expected != actual {
12030            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12031                "child_workflow_policy_changed",
12032                Some(sequence),
12033                Some(expected.to_string()),
12034                Some(actual.to_string()),
12035                format!("child workflow {field} changed during replay"),
12036            )));
12037        }
12038    }
12039    Ok(())
12040}
12041
12042#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12043enum RecordedSnapshotValue<T> {
12044    /// Older history did not persist this field, so it cannot constrain replay.
12045    Unknown,
12046    Known(T),
12047}
12048
12049impl<T: PartialEq> RecordedSnapshotValue<T> {
12050    fn matches_current(&self, current: &Self) -> bool {
12051        match self {
12052            Self::Unknown => true,
12053            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
12054        }
12055    }
12056}
12057
12058#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12059struct ActivityRetrySnapshot {
12060    snapshot_version: RecordedSnapshotValue<Option<u64>>,
12061    max_attempts: RecordedSnapshotValue<Option<u64>>,
12062    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
12063    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12064    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
12065    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12066    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
12067    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
12068}
12069
12070impl ActivityRetrySnapshot {
12071    fn matches_current(&self, current: &Self) -> bool {
12072        self.snapshot_version
12073            .matches_current(&current.snapshot_version)
12074            && self.max_attempts.matches_current(&current.max_attempts)
12075            && self
12076                .backoff_seconds
12077                .matches_current(&current.backoff_seconds)
12078            && self
12079                .start_to_close_timeout
12080                .matches_current(&current.start_to_close_timeout)
12081            && self
12082                .schedule_to_start_timeout
12083                .matches_current(&current.schedule_to_start_timeout)
12084            && self
12085                .schedule_to_close_timeout
12086                .matches_current(&current.schedule_to_close_timeout)
12087            && self
12088                .heartbeat_timeout
12089                .matches_current(&current.heartbeat_timeout)
12090            && self
12091                .non_retryable_error_types
12092                .matches_current(&current.non_retryable_error_types)
12093    }
12094}
12095
12096fn recorded_optional_u64(
12097    object: Option<&serde_json::Map<String, Value>>,
12098    field: &str,
12099) -> RecordedSnapshotValue<Option<u64>> {
12100    match object.and_then(|object| object.get(field)) {
12101        None => RecordedSnapshotValue::Unknown,
12102        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12103        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
12104    }
12105}
12106
12107fn recorded_optional_string(
12108    object: &serde_json::Map<String, Value>,
12109    field: &str,
12110) -> RecordedSnapshotValue<Option<String>> {
12111    match object.get(field) {
12112        None => RecordedSnapshotValue::Unknown,
12113        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12114        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
12115    }
12116}
12117
12118fn recorded_activity_execution_mode(
12119    events: &[&HistoryEvent],
12120    sequence: u64,
12121) -> Result<RecordedSnapshotValue<Option<String>>> {
12122    let mut recorded = RecordedSnapshotValue::Unknown;
12123    for event in events {
12124        for object in [
12125            event.payload.as_object(),
12126            event.payload.get("activity").and_then(Value::as_object),
12127        ]
12128        .into_iter()
12129        .flatten()
12130        {
12131            let mode = match object.get("execution_mode") {
12132                None => None,
12133                Some(Value::Null) => Some(None),
12134                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
12135                Some(_) => {
12136                    return Err(invalid_recorded_history(
12137                        "activity_execution_mode_invalid",
12138                        sequence,
12139                        "null or a non-empty execution mode",
12140                        "invalid execution_mode",
12141                        "activity history contains an invalid execution mode",
12142                    ))
12143                }
12144            };
12145            let legacy_mode = match object.get("local_activity") {
12146                None => None,
12147                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
12148                Some(_) => {
12149                    return Err(invalid_recorded_history(
12150                        "activity_execution_mode_invalid",
12151                        sequence,
12152                        "boolean local_activity",
12153                        "invalid local_activity",
12154                        "activity history contains an invalid local-activity marker",
12155                    ))
12156                }
12157            };
12158            for mode in [mode, legacy_mode].into_iter().flatten() {
12159                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
12160                {
12161                    return Err(invalid_recorded_history(
12162                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
12163                        "activity lifecycle events at one workflow sequence disagree on execution mode",
12164                    ));
12165                }
12166                recorded = RecordedSnapshotValue::Known(mode);
12167            }
12168        }
12169    }
12170    Ok(recorded)
12171}
12172
12173fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
12174    let policy = policy.and_then(Value::as_object);
12175    let backoff_seconds = policy
12176        .and_then(|policy| policy.get("backoff_seconds"))
12177        .and_then(Value::as_array)
12178        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12179        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
12180    let mut non_retryable_error_types = Vec::new();
12181    for error_type in policy
12182        .and_then(|policy| policy.get("non_retryable_error_types"))
12183        .and_then(Value::as_array)
12184        .into_iter()
12185        .flatten()
12186        .filter_map(Value::as_str)
12187        .map(str::trim)
12188        .filter(|error_type| !error_type.is_empty())
12189    {
12190        if !non_retryable_error_types
12191            .iter()
12192            .any(|recorded| recorded == error_type)
12193        {
12194            non_retryable_error_types.push(error_type.to_string());
12195        }
12196    }
12197
12198    ActivityRetrySnapshot {
12199        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
12200        max_attempts: recorded_optional_u64(policy, "max_attempts"),
12201        backoff_seconds,
12202        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
12203        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
12204        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
12205        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
12206        non_retryable_error_types: if policy
12207            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
12208        {
12209            RecordedSnapshotValue::Known(non_retryable_error_types)
12210        } else {
12211            RecordedSnapshotValue::Unknown
12212        },
12213    }
12214}
12215
12216fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
12217    let policy = options.retry_policy.as_ref();
12218    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
12219        Some(Value::Null) => None,
12220        Some(value) => value_as_u64(value),
12221        None => Some(1),
12222    };
12223    let backoff_seconds = policy
12224        .and_then(|policy| policy.get("backoff_seconds"))
12225        .and_then(Value::as_array)
12226        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12227        .unwrap_or_default();
12228    let non_retryable_error_types = policy
12229        .and_then(|policy| policy.get("non_retryable_error_types"))
12230        .and_then(Value::as_array)
12231        .into_iter()
12232        .flatten()
12233        .filter_map(Value::as_str)
12234        .map(str::to_string)
12235        .collect();
12236
12237    ActivityRetrySnapshot {
12238        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
12239        max_attempts: RecordedSnapshotValue::Known(max_attempts),
12240        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
12241        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
12242        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
12243        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
12244        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
12245        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
12246    }
12247}
12248
12249fn activity_options_description(options: &RecordedActivityOptions) -> String {
12250    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
12251}
12252
12253impl RecordedCommand {
12254    fn sequence(&self) -> u64 {
12255        match self {
12256            Self::CancellationGroup { sequence, .. }
12257            | Self::CancellationScope { sequence, .. }
12258            | Self::CancellationBoundary { sequence, .. }
12259            | Self::Activity { sequence, .. }
12260            | Self::Timer { sequence, .. }
12261            | Self::ChildWorkflow { sequence, .. }
12262            | Self::SignalWait { sequence, .. }
12263            | Self::ConditionWait { sequence, .. }
12264            | Self::SearchAttributes { sequence, .. }
12265            | Self::SideEffect { sequence, .. }
12266            | Self::VersionMarker { sequence, .. }
12267            | Self::Memo { sequence, .. } => *sequence,
12268            Self::ServiceOperation { sequence, .. } => *sequence,
12269        }
12270    }
12271
12272    fn shape(&self) -> &'static str {
12273        match self {
12274            Self::CancellationScope { .. } => "cancellation scope",
12275            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
12276                "cooperative cancellation"
12277            }
12278            Self::Activity { .. } => "activity",
12279            Self::Timer { .. } => "timer",
12280            Self::ChildWorkflow { .. } => "child workflow",
12281            Self::SignalWait { .. } => "signal wait",
12282            Self::ConditionWait { .. } => "condition wait",
12283            Self::SearchAttributes { .. } => "search-attribute update",
12284            Self::SideEffect { .. } => "side effect",
12285            Self::VersionMarker { .. } => "version marker",
12286            Self::Memo { .. } => "memo upsert",
12287            Self::ServiceOperation { .. } => "service operation",
12288        }
12289    }
12290}
12291
12292fn ensure_version_supported(
12293    change_id: &str,
12294    version: i32,
12295    min_supported: i32,
12296    max_supported: i32,
12297    sequence: u64,
12298) -> Result<()> {
12299    if (min_supported..=max_supported).contains(&version) {
12300        return Ok(());
12301    }
12302    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12303        "version_marker_incompatible_range",
12304        (sequence != 0).then_some(sequence),
12305        Some(format!("{min_supported}..={max_supported}")),
12306        Some(format!("{change_id}:{version}")),
12307        "recorded workflow version is outside the range supported by current code",
12308    )))
12309}
12310
12311#[derive(Clone, Debug)]
12312struct ResumeSignal {
12313    signal_name: String,
12314    arguments: Vec<AvroValue>,
12315}
12316
12317const MAX_PARALLEL_OPERATIONS: usize = 1000;
12318
12319fn parallel_group_prefix(kind: &str) -> &'static str {
12320    match kind {
12321        "activity" => "parallel-activities",
12322        "child" => "parallel-children",
12323        "timer" => "parallel-timers",
12324        _ => "parallel-calls",
12325    }
12326}
12327
12328fn parallel_group_entry(
12329    base_sequence: u64,
12330    size: usize,
12331    index: usize,
12332    kind: &str,
12333) -> ParallelGroupMetadata {
12334    ParallelGroupMetadata {
12335        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12336        parallel_group_kind: kind.to_string(),
12337        parallel_group_base_sequence: base_sequence,
12338        parallel_group_size: size,
12339        parallel_group_index: index,
12340        parallel_group_mode: None,
12341        selection_member_key: None,
12342        selection_member_index: None,
12343        selection_member_base_sequence: None,
12344        selection_member_size: None,
12345        selection_member_kind: None,
12346    }
12347}
12348
12349struct SelectionMemberMetadata {
12350    key: SelectionKey,
12351    index: usize,
12352    base_sequence: u64,
12353    size: usize,
12354    kind: String,
12355}
12356
12357fn selection_group_entry(
12358    base_sequence: u64,
12359    size: usize,
12360    index: usize,
12361    kind: &str,
12362    member: &SelectionMemberMetadata,
12363) -> ParallelGroupMetadata {
12364    ParallelGroupMetadata {
12365        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
12366        parallel_group_kind: kind.to_string(),
12367        parallel_group_base_sequence: base_sequence,
12368        parallel_group_size: size,
12369        parallel_group_index: index,
12370        parallel_group_mode: Some("select".to_string()),
12371        selection_member_key: Some(member.key.clone()),
12372        selection_member_index: Some(member.index),
12373        selection_member_base_sequence: Some(member.base_sequence),
12374        selection_member_size: Some(member.size),
12375        selection_member_kind: Some(member.kind.clone()),
12376    }
12377}
12378
12379fn apply_parallel_group_path(
12380    command: &mut serde_json::Map<String, Value>,
12381    path: &[ParallelGroupMetadata],
12382) {
12383    let Some(inner) = path.last() else {
12384        return;
12385    };
12386    command.insert(
12387        "parallel_group_id".to_string(),
12388        json!(inner.parallel_group_id),
12389    );
12390    command.insert(
12391        "parallel_group_kind".to_string(),
12392        json!(inner.parallel_group_kind),
12393    );
12394    command.insert(
12395        "parallel_group_base_sequence".to_string(),
12396        json!(inner.parallel_group_base_sequence),
12397    );
12398    command.insert(
12399        "parallel_group_size".to_string(),
12400        json!(inner.parallel_group_size),
12401    );
12402    command.insert(
12403        "parallel_group_index".to_string(),
12404        json!(inner.parallel_group_index),
12405    );
12406    if let Some(mode) = &inner.parallel_group_mode {
12407        command.insert("parallel_group_mode".to_string(), json!(mode));
12408    }
12409    if let Some(key) = &inner.selection_member_key {
12410        command.insert("selection_member_key".to_string(), json!(key));
12411    }
12412    if let Some(index) = inner.selection_member_index {
12413        command.insert("selection_member_index".to_string(), json!(index));
12414    }
12415    if let Some(base_sequence) = inner.selection_member_base_sequence {
12416        command.insert(
12417            "selection_member_base_sequence".to_string(),
12418            json!(base_sequence),
12419        );
12420    }
12421    if let Some(size) = inner.selection_member_size {
12422        command.insert("selection_member_size".to_string(), json!(size));
12423    }
12424    if let Some(kind) = &inner.selection_member_kind {
12425        command.insert("selection_member_kind".to_string(), json!(kind));
12426    }
12427    command.insert("parallel_group_path".to_string(), json!(path));
12428}
12429
12430fn ensure_parallel_path_matches(
12431    sequence: u64,
12432    recorded: Option<&[ParallelGroupMetadata]>,
12433    expected: &[ParallelGroupMetadata],
12434) -> Result<()> {
12435    match (recorded, expected.is_empty()) {
12436        (None, true) => Ok(()),
12437        (Some(recorded), false) if recorded == expected => Ok(()),
12438        (None, false) => Err(invalid_recorded_history(
12439            "parallel_group_metadata_missing",
12440            sequence,
12441            &serde_json::to_string(expected).unwrap_or_default(),
12442            "<missing>",
12443            "recorded parallel member is missing its durable group path",
12444        )),
12445        (Some(recorded), true) => Err(invalid_recorded_history(
12446            "parallel_group_shape_mismatch",
12447            sequence,
12448            "sequential command",
12449            &serde_json::to_string(recorded).unwrap_or_default(),
12450            "recorded command belonged to a parallel group but current code schedules it sequentially",
12451        )),
12452        (Some(recorded), false) => Err(invalid_recorded_history(
12453            "parallel_group_shape_mismatch",
12454            sequence,
12455            &serde_json::to_string(recorded).unwrap_or_default(),
12456            &serde_json::to_string(expected).unwrap_or_default(),
12457            "recorded parallel-group identity or path changed during replay",
12458        )),
12459    }
12460}
12461
12462#[derive(Clone, Debug)]
12463enum ParallelShape {
12464    Leaf,
12465    Group(Vec<ParallelShape>),
12466}
12467
12468struct ParallelDescriptor {
12469    operation: ParallelOperation,
12470    offset: usize,
12471    member_path: Vec<usize>,
12472    group_path: Vec<ParallelGroupMetadata>,
12473}
12474
12475fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
12476    operations
12477        .iter()
12478        .map(|operation| match operation {
12479            ParallelOperation::Group(children) => parallel_leaf_count(children),
12480            _ => 1,
12481        })
12482        .sum()
12483}
12484
12485fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
12486    match operation {
12487        ParallelOperation::Activity { .. } => Some("activity"),
12488        ParallelOperation::ChildWorkflow { .. } => Some("child"),
12489        ParallelOperation::Timer(_) => Some("timer"),
12490        ParallelOperation::Signal(_) => Some("signal"),
12491        ParallelOperation::Condition { .. } => Some("condition"),
12492        ParallelOperation::Group(children) => parallel_group_kind(children),
12493    }
12494}
12495
12496fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
12497    let mut kind = None;
12498    for operation in operations {
12499        let Some(operation_kind) = parallel_operation_kind(operation) else {
12500            continue;
12501        };
12502        match kind {
12503            None => kind = Some(operation_kind),
12504            Some(current) if current == operation_kind => {}
12505            Some(_) => return Some("mixed"),
12506        }
12507    }
12508    kind
12509}
12510
12511fn validate_parallel_operations(
12512    operations: &[ParallelOperation],
12513    member_path: &mut Vec<usize>,
12514    root: bool,
12515) -> Result<()> {
12516    let leaves = parallel_leaf_count(operations);
12517    if leaves > MAX_PARALLEL_OPERATIONS {
12518        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12519            reason: "fan_out_limit_exceeded",
12520            member_path: member_path.clone(),
12521            message: format!(
12522                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12523            ),
12524        }));
12525    }
12526    if !root && operations.is_empty() {
12527        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12528            reason: "nested_group_empty",
12529            member_path: member_path.clone(),
12530            message: "a nested group must contain at least one durable leaf".to_string(),
12531        }));
12532    }
12533
12534    for (index, operation) in operations.iter().enumerate() {
12535        member_path.push(index);
12536        match operation {
12537            ParallelOperation::Activity {
12538                options, arguments, ..
12539            } => {
12540                options
12541                    .validate()
12542                    .map_err(|error| Error::InvalidActivityOptions(error))?;
12543                if let Err(error) = arguments {
12544                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12545                        reason: "arguments_invalid",
12546                        member_path: member_path.clone(),
12547                        message: error.to_string(),
12548                    }));
12549                }
12550            }
12551            ParallelOperation::ChildWorkflow {
12552                options, arguments, ..
12553            } => {
12554                validate_parallel_child_options(options)?;
12555                if let Err(error) = arguments {
12556                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12557                        reason: "arguments_invalid",
12558                        member_path: member_path.clone(),
12559                        message: error.to_string(),
12560                    }));
12561                }
12562            }
12563            ParallelOperation::Timer(duration)
12564                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
12565            {
12566                return Err(Error::TimerDurationOverflow);
12567            }
12568            ParallelOperation::Timer(_) => {}
12569            ParallelOperation::Signal(signal_name) => {
12570                validate_user_signal_name(signal_name)?;
12571                if signal_name.trim().is_empty() {
12572                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12573                        reason: "signal_name_empty",
12574                        member_path: member_path.clone(),
12575                        message: "signal wait name must not be empty".to_string(),
12576                    }));
12577                }
12578            }
12579            ParallelOperation::Condition { options, .. } => {
12580                options.validate()?;
12581            }
12582            ParallelOperation::Group(children) => {
12583                validate_parallel_operations(children, member_path, false)?;
12584            }
12585        }
12586        member_path.pop();
12587    }
12588    Ok(())
12589}
12590
12591fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
12592    if options.task_queue.trim().is_empty() {
12593        return Err(Error::InvalidChildWorkflowOptions(
12594            "task_queue must not be empty".to_string(),
12595        ));
12596    }
12597    for (name, value) in [
12598        (
12599            "execution_timeout_seconds",
12600            options.execution_timeout_seconds,
12601        ),
12602        ("run_timeout_seconds", options.run_timeout_seconds),
12603    ] {
12604        if value == Some(0) {
12605            return Err(Error::InvalidChildWorkflowOptions(format!(
12606                "{name} must be at least 1"
12607            )));
12608        }
12609    }
12610    if options
12611        .retry_policy
12612        .as_ref()
12613        .is_some_and(|policy| policy.max_attempts == Some(0))
12614    {
12615        return Err(Error::InvalidChildWorkflowOptions(
12616            "retry_policy.max_attempts must be at least 1".to_string(),
12617        ));
12618    }
12619    Ok(())
12620}
12621
12622fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
12623    ParallelShape::Group(
12624        operations
12625            .iter()
12626            .map(|operation| match operation {
12627                ParallelOperation::Group(children) => parallel_shape(children),
12628                _ => ParallelShape::Leaf,
12629            })
12630            .collect(),
12631    )
12632}
12633
12634fn parallel_descriptors(
12635    operations: Vec<ParallelOperation>,
12636    base_sequence: u64,
12637) -> Result<Vec<ParallelDescriptor>> {
12638    let size = parallel_leaf_count(&operations);
12639    let kind = parallel_group_kind(&operations).unwrap_or("activity");
12640    let mut descriptors = Vec::with_capacity(size);
12641    let mut cursor = 0;
12642
12643    for (index, operation) in operations.into_iter().enumerate() {
12644        match operation {
12645            ParallelOperation::Group(children) => {
12646                let child_base = base_sequence
12647                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12648                    .ok_or(Error::TimerDurationOverflow)?;
12649                for mut descriptor in parallel_descriptors(children, child_base)? {
12650                    let outer_index = cursor + descriptor.offset;
12651                    descriptor.group_path.insert(
12652                        0,
12653                        parallel_group_entry(base_sequence, size, outer_index, kind),
12654                    );
12655                    descriptor.member_path.insert(0, index);
12656                    descriptor.offset = outer_index;
12657                    descriptors.push(descriptor);
12658                }
12659                cursor = descriptors.len();
12660            }
12661            operation => {
12662                descriptors.push(ParallelDescriptor {
12663                    operation,
12664                    offset: cursor,
12665                    member_path: vec![index],
12666                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
12667                });
12668                cursor += 1;
12669            }
12670        }
12671    }
12672    Ok(descriptors)
12673}
12674
12675enum ParallelLeafCall {
12676    Activity(ActivityCall),
12677    ChildWorkflow(ChildWorkflowCall),
12678    Timer(TimerCall),
12679    Signal(SignalCall),
12680    Condition(ConditionWaitCall),
12681}
12682
12683fn parallel_leaf_call(
12684    ctx: &WorkflowContext,
12685    operation: ParallelOperation,
12686    parallel_group_path: Vec<ParallelGroupMetadata>,
12687) -> ParallelLeafCall {
12688    match operation {
12689        ParallelOperation::Activity {
12690            activity_type,
12691            options,
12692            arguments,
12693        } => ParallelLeafCall::Activity(ActivityCall {
12694            ctx: ctx.clone(),
12695            activity_type,
12696            options,
12697            worker_session: None,
12698            args: Some(arguments),
12699            scheduled: false,
12700            local: false,
12701            local_result: None,
12702            parallel_group_path,
12703        }),
12704        ParallelOperation::ChildWorkflow {
12705            workflow_type,
12706            options,
12707            arguments,
12708        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
12709            ctx: ctx.clone(),
12710            workflow_type,
12711            options,
12712            args: Some(arguments),
12713            scheduled: false,
12714            matched_pending: false,
12715            parallel_group_path,
12716        }),
12717        ParallelOperation::Timer(duration) => {
12718            let delay_seconds = duration
12719                .as_secs()
12720                .checked_add(u64::from(duration.subsec_nanos() > 0));
12721            ParallelLeafCall::Timer(TimerCall {
12722                ctx: ctx.clone(),
12723                delay_seconds,
12724                scheduled: false,
12725                matched_pending: false,
12726                parallel_group_path,
12727            })
12728        }
12729        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
12730            ctx: ctx.clone(),
12731            signal_name,
12732            runtime_reserved_allowed: false,
12733            opened_wait: false,
12734            matched_pending: false,
12735            parallel_group_path,
12736        }),
12737        ParallelOperation::Condition { options, predicate } => {
12738            ParallelLeafCall::Condition(ConditionWaitCall {
12739                ctx: ctx.clone(),
12740                options,
12741                predicate,
12742                occurrence_id: None,
12743                opened_wait: false,
12744                parallel_group_path,
12745            })
12746        }
12747        ParallelOperation::Group(_) => {
12748            unreachable!("parallel descriptors contain only durable leaves")
12749        }
12750    }
12751}
12752
12753impl ParallelLeafCall {
12754    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
12755        match self {
12756            Self::Activity(call) => Pin::new(call)
12757                .poll_avro_value(cx)
12758                .map_ok(ParallelAvroResult::Activity),
12759            Self::ChildWorkflow(call) => Pin::new(call)
12760                .poll_avro_value(cx)
12761                .map_ok(ParallelAvroResult::ChildWorkflow),
12762            Self::Timer(call) => Pin::new(call)
12763                .poll(cx)
12764                .map_ok(|()| ParallelAvroResult::Timer),
12765            Self::Signal(call) => Pin::new(call)
12766                .poll_avro_value(cx)
12767                .map_ok(ParallelAvroResult::Signal),
12768            Self::Condition(call) => Pin::new(call)
12769                .poll(cx)
12770                .map_ok(ParallelAvroResult::Condition),
12771        }
12772    }
12773}
12774
12775struct ParallelLeaf {
12776    call: ParallelLeafCall,
12777    sequence: u64,
12778    member_path: Vec<usize>,
12779    group_path: Vec<ParallelGroupMetadata>,
12780    result: Option<ParallelAvroResult>,
12781}
12782
12783/// Future returned by [`WorkflowContext::parallel`].
12784pub struct ParallelCall {
12785    ctx: WorkflowContext,
12786    operations: Option<Vec<ParallelOperation>>,
12787    shape: Option<ParallelShape>,
12788    leaves: Vec<ParallelLeaf>,
12789    pending_scope_delivery: bool,
12790    worker_session: Option<WorkerSessionOptions>,
12791}
12792
12793impl ParallelCall {
12794    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
12795        Self {
12796            ctx,
12797            operations: Some(operations),
12798            shape: None,
12799            leaves: Vec::new(),
12800            pending_scope_delivery: false,
12801            worker_session: None,
12802        }
12803    }
12804
12805    fn initialize(&mut self) -> Result<()> {
12806        if let Some(session) = &self.worker_session {
12807            session.to_wire()?;
12808        }
12809        let operations = self.operations.take().unwrap_or_default();
12810        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
12811        self.shape = Some(parallel_shape(&operations));
12812        if operations.is_empty() {
12813            return Ok(());
12814        }
12815
12816        let base_sequence = {
12817            let state = self
12818                .ctx
12819                .state
12820                .lock()
12821                .map_err(|_| Error::WorkflowStatePoisoned)?;
12822            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12823                recorded.sequence()
12824            } else {
12825                let last = state
12826                    .recorded_commands
12827                    .last()
12828                    .map(RecordedCommand::sequence)
12829                    .unwrap_or(0);
12830                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12831                    .and_then(|sequence| sequence.checked_add(1))
12832                    .ok_or_else(|| {
12833                        Error::InvalidParallelGroup(ParallelGroupError {
12834                            reason: "sequence_overflow",
12835                            member_path: Vec::new(),
12836                            message: "parallel group sequence identity overflowed u64".to_string(),
12837                        })
12838                    })?
12839            }
12840        };
12841
12842        let descriptors = parallel_descriptors(operations, base_sequence)?;
12843        {
12844            let mut state = self
12845                .ctx
12846                .state
12847                .lock()
12848                .map_err(|_| Error::WorkflowStatePoisoned)?;
12849            let cursor = state.command_cursor;
12850            self.ctx.validate_scope_membership(&mut state, cursor)?;
12851            if state.prepare_parallel_scope_cancellation(&descriptors)? {
12852                self.pending_scope_delivery = true;
12853                return Ok(());
12854            }
12855            state.expand_cancellation_group(&descriptors)?;
12856            state.prepare_group_cancellation(&descriptors)?;
12857        }
12858        self.leaves = descriptors
12859            .into_iter()
12860            .map(|descriptor| {
12861                let mut call = parallel_leaf_call(
12862                    &self.ctx,
12863                    descriptor.operation,
12864                    descriptor.group_path.clone(),
12865                );
12866                if let (Some(session), ParallelLeafCall::Activity(activity)) =
12867                    (&self.worker_session, &mut call)
12868                {
12869                    activity.worker_session = Some(session.clone());
12870                }
12871                ParallelLeaf {
12872                    call,
12873                    sequence: base_sequence + descriptor.offset as u64,
12874                    member_path: descriptor.member_path,
12875                    group_path: descriptor.group_path,
12876                    result: None,
12877                }
12878            })
12879            .collect();
12880        Ok(())
12881    }
12882
12883    fn poll_avro_value(
12884        mut self: Pin<&mut Self>,
12885        cx: &mut TaskContext<'_>,
12886    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
12887        if self.operations.is_some() {
12888            if let Err(error) = self.initialize() {
12889                return Poll::Ready(Err(error));
12890            }
12891        }
12892        if self.pending_scope_delivery {
12893            return Poll::Pending;
12894        }
12895        if self.leaves.is_empty() {
12896            return Poll::Ready(Ok(Vec::new()));
12897        }
12898
12899        let mut failures = Vec::new();
12900        let mut pending = false;
12901        for (index, leaf) in self.leaves.iter_mut().enumerate() {
12902            if leaf.result.is_some() {
12903                continue;
12904            }
12905            match leaf.call.poll_avro_value(cx) {
12906                Poll::Ready(Ok(result)) => leaf.result = Some(result),
12907                Poll::Ready(Err(error)) => failures.push((index, error)),
12908                Poll::Pending => pending = true,
12909            }
12910        }
12911
12912        if !failures.is_empty() {
12913            if let Some(position) = failures
12914                .iter()
12915                .position(|(_, error)| workflow_task_integrity_error(error))
12916            {
12917                return Poll::Ready(Err(failures.remove(position).1));
12918            }
12919            if self
12920                .ctx
12921                .state
12922                .lock()
12923                .map_err(|_| Error::WorkflowStatePoisoned)?
12924                .cancellation_delivery_intent
12925                .is_some()
12926            {
12927                return Poll::Pending;
12928            }
12929            if let Some(position) = failures
12930                .iter()
12931                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
12932            {
12933                return Poll::Ready(Err(failures.remove(position).1));
12934            }
12935            failures.sort_by_key(|(index, _)| *index);
12936            let (failed_index, cause) = failures.remove(0);
12937            let failed = &self.leaves[failed_index];
12938            let completed = self
12939                .leaves
12940                .iter()
12941                .filter_map(|leaf| {
12942                    leaf.result
12943                        .clone()
12944                        .and_then(|result| result.into_json_result().ok())
12945                        .map(|result| ParallelCompletion {
12946                            member_path: leaf.member_path.clone(),
12947                            result,
12948                        })
12949                })
12950                .collect();
12951            let group_id = failed
12952                .group_path
12953                .first()
12954                .map(|entry| entry.parallel_group_id.clone())
12955                .unwrap_or_default();
12956            let sequences = self
12957                .leaves
12958                .iter()
12959                .map(|leaf| leaf.sequence)
12960                .collect::<Vec<_>>();
12961            self.ctx
12962                .state
12963                .lock()
12964                .map_err(|_| Error::WorkflowStatePoisoned)?
12965                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12966            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12967                group_id,
12968                member_path: failed.member_path.clone(),
12969                group_path: failed.group_path.clone(),
12970                completed,
12971                cause: Box::new(cause),
12972            })));
12973        }
12974        if pending
12975            || self
12976                .ctx
12977                .state
12978                .lock()
12979                .map_err(|_| Error::WorkflowStatePoisoned)?
12980                .cancellation_delivery_intent
12981                .is_some()
12982        {
12983            return Poll::Pending;
12984        }
12985
12986        let mut flat_results = self
12987            .leaves
12988            .iter_mut()
12989            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12990            .collect::<Vec<_>>()
12991            .into_iter();
12992        let results = parallel_results_for_shape(
12993            self.shape.as_ref().expect("initialized parallel shape"),
12994            &mut flat_results,
12995        );
12996        let sequences = self
12997            .leaves
12998            .iter()
12999            .map(|leaf| leaf.sequence)
13000            .collect::<Vec<_>>();
13001        self.ctx
13002            .state
13003            .lock()
13004            .map_err(|_| Error::WorkflowStatePoisoned)?
13005            .advance_cancellation_sequences(&sequences, None);
13006        Poll::Ready(Ok(match results {
13007            ParallelAvroResult::Group(results) => results,
13008            ParallelAvroResult::Activity(_)
13009            | ParallelAvroResult::ChildWorkflow(_)
13010            | ParallelAvroResult::Timer
13011            | ParallelAvroResult::Signal(_)
13012            | ParallelAvroResult::Condition(_) => {
13013                unreachable!("root parallel shape is a group")
13014            }
13015        }))
13016    }
13017}
13018
13019fn parallel_results_for_shape(
13020    shape: &ParallelShape,
13021    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
13022) -> ParallelAvroResult {
13023    match shape {
13024        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
13025        ParallelShape::Group(children) => ParallelAvroResult::Group(
13026            children
13027                .iter()
13028                .map(|child| parallel_results_for_shape(child, flat_results))
13029                .collect(),
13030        ),
13031    }
13032}
13033
13034impl Future for ParallelCall {
13035    type Output = Result<Vec<ParallelResult>>;
13036
13037    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13038        self.poll_avro_value(cx)
13039            .map_ok(|results| {
13040                results
13041                    .into_iter()
13042                    .map(ParallelAvroResult::into_json_result)
13043                    .collect::<Result<Vec<_>>>()
13044            })
13045            .map_ok(|result| result)
13046            .flatten_result()
13047    }
13048}
13049
13050#[derive(Clone, Debug)]
13051struct SelectionMemberPlan {
13052    key: SelectionKey,
13053    index: usize,
13054    base_sequence: u64,
13055    size: usize,
13056    kind: String,
13057    shape: ParallelShape,
13058    leaf_start: usize,
13059}
13060
13061fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
13062    match operation {
13063        ParallelOperation::Activity { .. } => "activity",
13064        ParallelOperation::ChildWorkflow { .. } => "child",
13065        ParallelOperation::Timer(_) => "timer",
13066        ParallelOperation::Signal(_) => "signal",
13067        ParallelOperation::Condition { .. } => "condition",
13068        ParallelOperation::Group(_) => "group",
13069    }
13070}
13071
13072fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
13073    match operation {
13074        ParallelOperation::Group(children) => parallel_shape(children),
13075        _ => ParallelShape::Leaf,
13076    }
13077}
13078
13079fn selection_descriptors(
13080    operations: Vec<(SelectionKey, ParallelOperation)>,
13081    base_sequence: u64,
13082) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
13083    if operations.is_empty() {
13084        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13085            reason: "selection_empty",
13086            member_path: Vec::new(),
13087            message: "durable selection requires at least one operation".to_string(),
13088        }));
13089    }
13090    let operation_refs = operations
13091        .iter()
13092        .map(|(_, operation)| operation)
13093        .collect::<Vec<_>>();
13094    let total_size = operation_refs
13095        .iter()
13096        .map(|operation| match operation {
13097            ParallelOperation::Group(children) => parallel_leaf_count(children),
13098            _ => 1,
13099        })
13100        .sum::<usize>();
13101    if total_size > MAX_PARALLEL_OPERATIONS {
13102        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13103            reason: "fan_out_limit_exceeded",
13104            member_path: Vec::new(),
13105            message: format!(
13106                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13107            ),
13108        }));
13109    }
13110    let group_kind = {
13111        let mut kind = None;
13112        for operation in &operation_refs {
13113            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
13114            match kind {
13115                None => kind = Some(operation_kind),
13116                Some(current) if current == operation_kind => {}
13117                Some(_) => {
13118                    kind = Some("mixed");
13119                    break;
13120                }
13121            }
13122        }
13123        kind.unwrap_or("mixed")
13124    };
13125
13126    let mut descriptors = Vec::with_capacity(total_size);
13127    let mut members = Vec::with_capacity(operations.len());
13128    let mut cursor = 0usize;
13129    let mut seen_keys: Vec<SelectionKey> = Vec::new();
13130    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
13131        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
13132            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13133                reason: "selection_key_invalid",
13134                member_path: vec![member_index],
13135                message: "selection member keys must be non-empty strings or non-negative integers"
13136                    .to_string(),
13137            }));
13138        }
13139        if seen_keys.contains(&key) {
13140            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13141                reason: "selection_key_duplicate",
13142                member_path: vec![member_index],
13143                message: format!("selection member key {key:?} is duplicated"),
13144            }));
13145        }
13146        seen_keys.push(key.clone());
13147        let member_size = match &operation {
13148            ParallelOperation::Group(children) => parallel_leaf_count(children),
13149            _ => 1,
13150        };
13151        if member_size == 0 {
13152            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13153                reason: "selection_member_empty",
13154                member_path: vec![member_index],
13155                message: "a selection member must contain at least one durable leaf".to_string(),
13156            }));
13157        }
13158        let member_base = base_sequence
13159            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13160            .ok_or(Error::TimerDurationOverflow)?;
13161        let member_kind = selection_operation_kind(&operation).to_string();
13162        let member_shape = selection_operation_shape(&operation);
13163        let leaf_start = descriptors.len();
13164        match operation {
13165            ParallelOperation::Group(children) => {
13166                validate_parallel_operations(&children, &mut vec![member_index], false)?;
13167                for mut descriptor in parallel_descriptors(children, member_base)? {
13168                    let flat_index = cursor + descriptor.offset;
13169                    descriptor.group_path.insert(
13170                        0,
13171                        selection_group_entry(
13172                            base_sequence,
13173                            total_size,
13174                            flat_index,
13175                            group_kind,
13176                            &SelectionMemberMetadata {
13177                                key: key.clone(),
13178                                index: member_index,
13179                                base_sequence: member_base,
13180                                size: member_size,
13181                                kind: member_kind.clone(),
13182                            },
13183                        ),
13184                    );
13185                    descriptor.member_path.insert(0, member_index);
13186                    descriptor.offset = flat_index;
13187                    descriptors.push(descriptor);
13188                }
13189            }
13190            operation => {
13191                validate_parallel_operations(
13192                    std::slice::from_ref(&operation),
13193                    &mut Vec::new(),
13194                    true,
13195                )?;
13196                descriptors.push(ParallelDescriptor {
13197                    operation,
13198                    offset: cursor,
13199                    member_path: vec![member_index],
13200                    group_path: vec![selection_group_entry(
13201                        base_sequence,
13202                        total_size,
13203                        cursor,
13204                        group_kind,
13205                        &SelectionMemberMetadata {
13206                            key: key.clone(),
13207                            index: member_index,
13208                            base_sequence: member_base,
13209                            size: member_size,
13210                            kind: member_kind.clone(),
13211                        },
13212                    )],
13213                });
13214            }
13215        }
13216        members.push(SelectionMemberPlan {
13217            key,
13218            index: member_index,
13219            base_sequence: member_base,
13220            size: member_size,
13221            kind: member_kind,
13222            shape: member_shape,
13223            leaf_start,
13224        });
13225        cursor += member_size;
13226    }
13227    Ok((descriptors, members))
13228}
13229
13230struct SelectionLeaf {
13231    call: ParallelLeafCall,
13232    outcome: Option<Result<ParallelAvroResult>>,
13233}
13234
13235/// Stable reference to one member of a durable selection group.
13236#[derive(Clone)]
13237pub struct DurableOperationHandle {
13238    ctx: WorkflowContext,
13239    pub key: SelectionKey,
13240    pub index: usize,
13241    pub kind: String,
13242    pub identity: String,
13243    pub base_sequence: u64,
13244    pub size: usize,
13245    pub selection_group_id: String,
13246    shape: ParallelShape,
13247}
13248
13249impl std::fmt::Debug for DurableOperationHandle {
13250    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13251        formatter
13252            .debug_struct("DurableOperationHandle")
13253            .field("key", &self.key)
13254            .field("index", &self.index)
13255            .field("kind", &self.kind)
13256            .field("identity", &self.identity)
13257            .field("base_sequence", &self.base_sequence)
13258            .field("size", &self.size)
13259            .field("selection_group_id", &self.selection_group_id)
13260            .finish()
13261    }
13262}
13263
13264impl DurableOperationHandle {
13265    /// Await this member after another member has already won the selection.
13266    pub fn await_result(&self) -> DurableOperationAwaitCall {
13267        DurableOperationAwaitCall {
13268            handle: self.clone(),
13269        }
13270    }
13271
13272    /// Request cancellation without affecting siblings. The future resolves
13273    /// to unit; only `SelectionOperationCancelled` history proves cancellation
13274    /// beat a concurrently committed terminal result.
13275    pub fn cancel(&self) -> CancelDurableOperationCall {
13276        CancelDurableOperationCall {
13277            handle: self.clone(),
13278            emitted: false,
13279        }
13280    }
13281}
13282
13283/// The one winner committed for a durable selection group.
13284#[derive(Debug)]
13285pub struct SelectionResult {
13286    pub key: SelectionKey,
13287    pub index: usize,
13288    pub kind: String,
13289    pub identity: String,
13290    pub value: Option<ParallelResult>,
13291    pub failure: Option<Error>,
13292    pub winner: DurableOperationHandle,
13293    pub handles: Vec<DurableOperationHandle>,
13294}
13295
13296impl SelectionResult {
13297    pub fn succeeded(&self) -> bool {
13298        self.failure.is_none()
13299    }
13300
13301    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13302        self.handles.iter().find(|handle| &handle.key == key)
13303    }
13304
13305    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13306        self.handles
13307            .iter()
13308            .filter(|handle| handle.index != self.index)
13309            .collect()
13310    }
13311
13312    pub fn into_result(self) -> Result<ParallelResult> {
13313        match (self.value, self.failure) {
13314            (Some(value), None) => Ok(value),
13315            (_, Some(error)) => Err(error),
13316            _ => Err(Error::WorkerLoop(
13317                "selection result contained neither a value nor a failure".to_string(),
13318            )),
13319        }
13320    }
13321}
13322
13323/// Future returned by [`WorkflowContext::select`].
13324pub struct SelectCall {
13325    ctx: WorkflowContext,
13326    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13327    members: Vec<SelectionMemberPlan>,
13328    leaves: Vec<SelectionLeaf>,
13329    group_id: Option<String>,
13330}
13331
13332impl SelectCall {
13333    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13334        Self {
13335            ctx,
13336            operations: Some(operations),
13337            members: Vec::new(),
13338            leaves: Vec::new(),
13339            group_id: None,
13340        }
13341    }
13342
13343    fn initialize(&mut self) -> Result<()> {
13344        let operations = self.operations.take().unwrap_or_default();
13345        let base_sequence = {
13346            let state = self
13347                .ctx
13348                .state
13349                .lock()
13350                .map_err(|_| Error::WorkflowStatePoisoned)?;
13351            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
13352                state.recorded_commands.get(state.command_cursor)
13353            {
13354                *sequence
13355            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
13356            {
13357                marker.selection_group_base_sequence
13358            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13359                recorded.sequence()
13360            } else {
13361                let last = state
13362                    .recorded_commands
13363                    .last()
13364                    .map(RecordedCommand::sequence)
13365                    .unwrap_or(0);
13366                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13367                    .and_then(|sequence| sequence.checked_add(1))
13368                    .ok_or(Error::TimerDurationOverflow)?
13369            }
13370        };
13371        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
13372        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
13373        {
13374            let mut state = self
13375                .ctx
13376                .state
13377                .lock()
13378                .map_err(|_| Error::WorkflowStatePoisoned)?;
13379            state.expand_cancellation_group(&descriptors)?;
13380            state.prepare_group_cancellation(&descriptors)?;
13381        }
13382        self.leaves = descriptors
13383            .into_iter()
13384            .map(|descriptor| SelectionLeaf {
13385                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
13386                outcome: None,
13387            })
13388            .collect();
13389        self.members = members;
13390        self.group_id = Some(group_id);
13391        Ok(())
13392    }
13393}
13394
13395impl Future for SelectCall {
13396    type Output = Result<SelectionResult>;
13397
13398    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13399        if self.operations.is_some() {
13400            if let Err(error) = self.initialize() {
13401                return Poll::Ready(Err(error));
13402            }
13403        }
13404
13405        for leaf in &mut self.leaves {
13406            if leaf.outcome.is_some() {
13407                continue;
13408            }
13409            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
13410                if outcome
13411                    .as_ref()
13412                    .err()
13413                    .is_some_and(workflow_task_integrity_error)
13414                {
13415                    return Poll::Ready(outcome.map(|_| unreachable!()));
13416                }
13417                leaf.outcome = Some(outcome);
13418            }
13419        }
13420
13421        if self
13422            .ctx
13423            .state
13424            .lock()
13425            .map_err(|_| Error::WorkflowStatePoisoned)?
13426            .cancellation_delivery_intent
13427            .is_some()
13428        {
13429            return Poll::Pending;
13430        }
13431
13432        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
13433            matches!(
13434                leaf.outcome,
13435                Some(Err(Error::CooperativeCancellationRequested(_)))
13436            )
13437        }) {
13438            return Poll::Ready(
13439                leaf.outcome
13440                    .take()
13441                    .expect("matched cancellation")
13442                    .map(|_| unreachable!()),
13443            );
13444        }
13445
13446        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
13447        let selection_member_range = self
13448            .members
13449            .first()
13450            .map(|member| member.base_sequence)
13451            .zip(self.leaves.len().try_into().ok())
13452            .map(|(base_sequence, size): (u64, u64)| {
13453                base_sequence..base_sequence.saturating_add(size)
13454            });
13455        let marker = {
13456            let mut state = match self.ctx.state.lock() {
13457                Ok(state) => state,
13458                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13459            };
13460            let marker = state
13461                .selection_markers
13462                .get(state.selection_marker_cursor)
13463                .cloned();
13464            if marker.is_none()
13465                && all_members_terminal
13466                && selection_member_range.as_ref().is_some_and(|member_range| {
13467                    state
13468                        .recorded_commands
13469                        .iter()
13470                        .any(|command| member_range.contains(&command.sequence()))
13471                })
13472            {
13473                // Terminal member history can be committed before the server's
13474                // SelectionResolved marker becomes visible to this task. That
13475                // marker is the durable barrier the selection is still waiting
13476                // on, so an otherwise commandless replay remains legitimately
13477                // pending instead of failing as an untracked yield.
13478                state.matched_recorded_pending = true;
13479            }
13480            marker
13481        };
13482        let Some(marker) = marker else {
13483            return Poll::Pending;
13484        };
13485        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
13486            || marker.selection_group_size != self.leaves.len()
13487            || self.members.first().map(|member| member.base_sequence)
13488                != Some(marker.selection_group_base_sequence)
13489        {
13490            return Poll::Ready(Err(invalid_recorded_history(
13491                "selection_group_shape_mismatch",
13492                marker.selection_group_base_sequence,
13493                self.group_id
13494                    .as_deref()
13495                    .unwrap_or("initialized selection group"),
13496                &marker.selection_group_id,
13497                "recorded selection group differs from current workflow code",
13498            )));
13499        }
13500        let Some(member_position) = self.members.iter().position(|member| {
13501            member.key == marker.member_key
13502                && member.index == marker.member_index
13503                && member.base_sequence == marker.member_base_sequence
13504                && member.size == marker.member_size
13505                && member.kind == marker.operation_kind
13506        }) else {
13507            return Poll::Ready(Err(invalid_recorded_history(
13508                "selection_member_shape_mismatch",
13509                marker.member_base_sequence,
13510                "winner member matching current workflow code",
13511                &format!("{:?}", marker.member_key),
13512                "recorded selection winner differs from the authored member identity",
13513            )));
13514        };
13515        let member = self.members[member_position].clone();
13516        let (handles, resolution_sequence) = {
13517            let mut state = match self.ctx.state.lock() {
13518                Ok(state) => state,
13519                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13520            };
13521            let identities = self
13522                .members
13523                .iter()
13524                .map(|candidate| {
13525                    selection_operation_identity(
13526                        &state,
13527                        &candidate.kind,
13528                        candidate.base_sequence,
13529                        candidate.size,
13530                    )
13531                })
13532                .collect::<Vec<_>>();
13533            if let Some((position, missing)) = identities
13534                .iter()
13535                .enumerate()
13536                .find(|(_, identity)| identity.is_empty())
13537                .map(|(position, identity)| (position, identity.clone()))
13538            {
13539                let candidate = &self.members[position];
13540                return Poll::Ready(Err(invalid_recorded_history(
13541                    "selection_operation_identity_missing",
13542                    candidate.base_sequence,
13543                    &format!(
13544                        "durable {} resource identity from scheduled/open history",
13545                        candidate.kind
13546                    ),
13547                    &missing,
13548                    "selection member history is missing its canonical durable identity",
13549                )));
13550            }
13551            let expected_winner_identity = &identities[member_position];
13552            let resolution_sequence = match validated_selection_resolution_sequence(
13553                &state,
13554                &marker,
13555                &member,
13556                expected_winner_identity,
13557            ) {
13558                Ok(sequence) => sequence,
13559                Err(error) => return Poll::Ready(Err(error)),
13560            };
13561            let handles = self
13562                .members
13563                .iter()
13564                .zip(identities)
13565                .map(|(member, identity)| DurableOperationHandle {
13566                    ctx: self.ctx.clone(),
13567                    key: member.key.clone(),
13568                    index: member.index,
13569                    kind: member.kind.clone(),
13570                    identity,
13571                    base_sequence: member.base_sequence,
13572                    size: member.size,
13573                    selection_group_id: marker.selection_group_id.clone(),
13574                    shape: member.shape.clone(),
13575                })
13576                .collect::<Vec<_>>();
13577            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
13578                return Poll::Ready(Err(error));
13579            }
13580            state.selection_marker_cursor += 1;
13581            (handles, resolution_sequence)
13582        };
13583
13584        let mut winner_failure = None;
13585        let mut flat_results = Vec::with_capacity(member.size);
13586        if marker.outcome == "failed" {
13587            let resolution_offset = match resolution_sequence
13588                .checked_sub(member.base_sequence)
13589                .and_then(|offset| usize::try_from(offset).ok())
13590            {
13591                Some(offset) if offset < member.size => offset,
13592                _ => {
13593                    return Poll::Ready(Err(invalid_recorded_history(
13594                        "selection_resolution_event_mismatch",
13595                        member.base_sequence,
13596                        "failure event within selected member bounds",
13597                        &resolution_sequence.to_string(),
13598                        "selection failure event is outside the authored member",
13599                    )))
13600                }
13601            };
13602            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
13603            match leaf.outcome.take() {
13604                Some(Err(error)) => winner_failure = Some(error),
13605                _ => {
13606                    return Poll::Ready(Err(invalid_recorded_history(
13607                        "selection_winner_outcome_mismatch",
13608                        member.base_sequence,
13609                        "exact failed terminal history referenced by SelectionResolved",
13610                        "missing or successful resolution event",
13611                        "selection winner marker disagrees with terminal operation history",
13612                    )))
13613                }
13614            }
13615        } else {
13616            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
13617                match leaf.outcome.take() {
13618                    Some(Ok(result)) => flat_results.push(result),
13619                    Some(Err(_)) => {
13620                        return Poll::Ready(Err(invalid_recorded_history(
13621                            "selection_winner_outcome_mismatch",
13622                            member.base_sequence,
13623                            "fully completed nested selection member",
13624                            "failed durable leaf",
13625                            "completed selection winner contains a failed leaf",
13626                        )))
13627                    }
13628                    None => {
13629                        return Poll::Ready(Err(invalid_recorded_history(
13630                            "selection_winner_unresolved",
13631                            member.base_sequence,
13632                            "terminal history for every completed winner leaf",
13633                            "pending member history",
13634                            "completed SelectionResolved member has an unfinished durable barrier",
13635                        )))
13636                    }
13637                }
13638            }
13639        }
13640        let value = if winner_failure.is_none() {
13641            let mut flat_results = flat_results.into_iter();
13642            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
13643            match value.into_json_result() {
13644                Ok(value) => Some(value),
13645                Err(error) => return Poll::Ready(Err(error)),
13646            }
13647        } else {
13648            None
13649        };
13650        let winner = handles[member_position].clone();
13651        self.ctx
13652            .state
13653            .lock()
13654            .map_err(|_| Error::WorkflowStatePoisoned)?
13655            .advance_cancellation_selection(&marker.selection_group_id);
13656        Poll::Ready(Ok(SelectionResult {
13657            key: winner.key.clone(),
13658            index: winner.index,
13659            kind: winner.kind.clone(),
13660            identity: winner.identity.clone(),
13661            value,
13662            failure: winner_failure,
13663            winner,
13664            handles,
13665        }))
13666    }
13667}
13668
13669fn selection_operation_identity(
13670    state: &WorkflowState,
13671    kind: &str,
13672    base_sequence: u64,
13673    size: usize,
13674) -> String {
13675    if kind == "group" {
13676        return format!("group:{base_sequence}:{size}");
13677    }
13678    let fields: &[&str] = match kind {
13679        "activity" => &["activity_execution_id"],
13680        "child" => &["child_workflow_run_id"],
13681        "timer" => &["timer_id"],
13682        "signal" => &["signal_wait_id"],
13683        "condition" => &["condition_wait_id"],
13684        _ => &[],
13685    };
13686    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
13687        for event in state
13688            .history_events
13689            .iter()
13690            .filter(|event| durable_event_sequence(event) == Some(sequence))
13691        {
13692            for field in fields {
13693                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
13694                    if !identity.is_empty() {
13695                        return identity.to_string();
13696                    }
13697                }
13698            }
13699        }
13700    }
13701    String::new()
13702}
13703
13704fn validated_selection_resolution_sequence(
13705    state: &WorkflowState,
13706    marker: &SelectionMarker,
13707    member: &SelectionMemberPlan,
13708    expected_identity: &str,
13709) -> Result<u64> {
13710    if expected_identity.is_empty() {
13711        return Err(invalid_recorded_history(
13712            "selection_operation_identity_missing",
13713            member.base_sequence,
13714            &format!(
13715                "durable {} resource identity from scheduled/open history",
13716                member.kind
13717            ),
13718            "missing operation identity",
13719            "selection member history is missing its canonical durable identity",
13720        ));
13721    }
13722    if marker.operation_identity != expected_identity {
13723        return Err(invalid_recorded_history(
13724            "selection_operation_identity_mismatch",
13725            member.base_sequence,
13726            expected_identity,
13727            &marker.operation_identity,
13728            "selection winner identity does not match durable scheduled/open history",
13729        ));
13730    }
13731
13732    let failure_types = [
13733        "ActivityFailed",
13734        "ActivityCancelled",
13735        "ActivityTimedOut",
13736        "ChildRunFailed",
13737        "ChildRunCancelled",
13738        "ChildRunTerminated",
13739    ];
13740    let success_types = [
13741        "ActivityCompleted",
13742        "ChildRunCompleted",
13743        "TimerFired",
13744        "SignalApplied",
13745        "ConditionWaitSatisfied",
13746        "ConditionWaitTimedOut",
13747    ];
13748    let terminal_types: &[&str] = if marker.outcome == "failed" {
13749        &failure_types
13750    } else {
13751        &success_types
13752    };
13753    let mut candidates = Vec::new();
13754    let member_commands = (member.base_sequence
13755        ..member.base_sequence.saturating_add(member.size as u64))
13756        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
13757        .map(|command| (command.sequence(), command))
13758        .collect::<BTreeMap<_, _>>();
13759    let mut resolved_conditions = BTreeSet::new();
13760    for event in state.history_events.iter() {
13761        let Some(sequence) = durable_event_sequence(event) else {
13762            continue;
13763        };
13764        let Some(command) = member_commands.get(&sequence) else {
13765            continue;
13766        };
13767        if !terminal_types.contains(&event.event_type.as_str()) {
13768            continue;
13769        }
13770        if matches!(command, RecordedCommand::ConditionWait { .. }) {
13771            if !matches!(
13772                event.event_type.as_str(),
13773                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
13774            ) && !(event.event_type == "TimerFired"
13775                && event.payload.get("timer_kind").and_then(Value::as_str)
13776                    == Some("condition_timeout"))
13777            {
13778                continue;
13779            }
13780            if !resolved_conditions.insert(sequence) {
13781                continue;
13782            }
13783        }
13784        let event_id = event
13785            .raw
13786            .get("id")
13787            .or_else(|| event.raw.get("event_id"))
13788            .and_then(Value::as_str)
13789            .filter(|value| !value.is_empty())
13790            .ok_or_else(|| {
13791                invalid_recorded_history(
13792                    "selection_resolution_event_id_missing",
13793                    member.base_sequence,
13794                    "terminal selection history with a durable event id",
13795                    &event.payload.to_string(),
13796                    "selection terminal history cannot be bound to its winner marker",
13797                )
13798            })?;
13799        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
13800    }
13801    let resolution = if marker.outcome == "failed" {
13802        candidates.first()
13803    } else {
13804        candidates.last()
13805    };
13806    let Some((event_id, event_type, sequence)) = resolution else {
13807        return Err(invalid_recorded_history(
13808            "selection_resolution_event_missing",
13809            member.base_sequence,
13810            "terminal history for the selected member",
13811            &format!("{:?}", marker.member_key),
13812            "selection winner marker has no matching durable terminal event",
13813        ));
13814    };
13815    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
13816        return Err(invalid_recorded_history(
13817            "selection_resolution_event_mismatch",
13818            member.base_sequence,
13819            &format!("{event_type}:{event_id}"),
13820            &format!(
13821                "{}:{}",
13822                marker.resolution_event_type, marker.resolution_event_id
13823            ),
13824            "selection winner marker does not reference the event that made its member terminal",
13825        ));
13826    }
13827    Ok(*sequence)
13828}
13829
13830fn selection_member_recorded_command(
13831    state: &WorkflowState,
13832    authored_sequence: u64,
13833) -> Option<&RecordedCommand> {
13834    let original = state
13835        .recorded_commands
13836        .iter()
13837        .find(|command| command.sequence() == authored_sequence)?;
13838    let RecordedCommand::ConditionWait {
13839        occurrence_id,
13840        parallel_group_path: Some(_),
13841        ..
13842    } = original
13843    else {
13844        return Some(original);
13845    };
13846    // Decoding proves each physical reopen has the same authored identity and
13847    // group path after a satisfied predecessor. Only its latest wait can make
13848    // this logical member terminal.
13849    state
13850        .recorded_commands
13851        .iter()
13852        .filter(|command| {
13853            matches!(command, RecordedCommand::ConditionWait {
13854                occurrence_id: candidate, ..
13855            } if candidate == occurrence_id)
13856        })
13857        .max_by_key(|command| command.sequence())
13858}
13859
13860fn recorded_selection_member_outcome(
13861    state: &WorkflowState,
13862    handle: &DurableOperationHandle,
13863) -> Result<Option<ParallelResult>> {
13864    for event in state.history_events.iter() {
13865        let Some(sequence) = durable_event_sequence(event) else {
13866            continue;
13867        };
13868        if sequence < handle.base_sequence
13869            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
13870            || !matches!(
13871                event.event_type.as_str(),
13872                "ActivityFailed"
13873                    | "ActivityCancelled"
13874                    | "ActivityTimedOut"
13875                    | "ChildRunFailed"
13876                    | "ChildRunCancelled"
13877                    | "ChildRunTerminated"
13878            )
13879        {
13880            continue;
13881        }
13882        let Some(command) = state
13883            .recorded_commands
13884            .iter()
13885            .find(|command| command.sequence() == sequence)
13886        else {
13887            continue;
13888        };
13889        match command {
13890            RecordedCommand::Activity {
13891                outcome: Some(Err(failure)),
13892                ..
13893            } => return Err(Error::ActivityFailed(failure.clone())),
13894            RecordedCommand::ChildWorkflow {
13895                outcome: Some(Err(failure)),
13896                ..
13897            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
13898            _ => {}
13899        }
13900    }
13901
13902    let mut results = Vec::with_capacity(handle.size);
13903    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13904        let Some(command) = selection_member_recorded_command(state, sequence) else {
13905            return Ok(None);
13906        };
13907        let result = match command {
13908            RecordedCommand::Activity { outcome, .. } => match outcome {
13909                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
13910                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
13911                None => return Ok(None),
13912            },
13913            RecordedCommand::Timer { fired, .. } => {
13914                if !fired {
13915                    return Ok(None);
13916                }
13917                ParallelAvroResult::Timer
13918            }
13919            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
13920                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
13921                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
13922                None => return Ok(None),
13923            },
13924            RecordedCommand::SignalWait { value, .. } => match value {
13925                Some(value) => ParallelAvroResult::Signal(value.clone()),
13926                None => return Ok(None),
13927            },
13928            RecordedCommand::ConditionWait { result, .. } => match result {
13929                Some(result) => ParallelAvroResult::Condition(*result),
13930                None => return Ok(None),
13931            },
13932            other => {
13933                return Err(command_mismatch(
13934                    other,
13935                    format!("selected {} member", handle.kind),
13936                ))
13937            }
13938        };
13939        results.push(result);
13940    }
13941    let mut results = results.into_iter();
13942    parallel_results_for_shape(&handle.shape, &mut results)
13943        .into_json_result()
13944        .map(Some)
13945}
13946
13947fn recorded_selection_member_is_terminal(
13948    state: &WorkflowState,
13949    handle: &DurableOperationHandle,
13950) -> bool {
13951    let mut completed = 0usize;
13952    let mut all_completed = true;
13953    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13954        let Some(command) = selection_member_recorded_command(state, sequence) else {
13955            all_completed = false;
13956            continue;
13957        };
13958        let terminal = match command {
13959            RecordedCommand::Activity {
13960                outcome: Some(Err(_)),
13961                ..
13962            }
13963            | RecordedCommand::ChildWorkflow {
13964                outcome: Some(Err(_)),
13965                ..
13966            } => return true,
13967            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13968            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13969            RecordedCommand::Timer { fired, .. } => *fired,
13970            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13971            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13972            RecordedCommand::SearchAttributes { .. }
13973            | RecordedCommand::CancellationScope { .. }
13974            | RecordedCommand::SideEffect { .. }
13975            | RecordedCommand::VersionMarker { .. }
13976            | RecordedCommand::Memo { .. }
13977            | RecordedCommand::CancellationBoundary { .. }
13978            | RecordedCommand::CancellationGroup { .. } => false,
13979            RecordedCommand::ServiceOperation { .. } => false,
13980        };
13981        if !terminal {
13982            all_completed = false;
13983            continue;
13984        }
13985        completed += 1;
13986    }
13987    all_completed && completed == handle.size
13988}
13989
13990fn selection_cancellation_for_handle(
13991    state: &WorkflowState,
13992    handle: &DurableOperationHandle,
13993) -> Result<bool> {
13994    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13995        recorded.selection_group_id == handle.selection_group_id
13996            && recorded.member_base_sequence == handle.base_sequence
13997    }) else {
13998        return Ok(false);
13999    };
14000    validate_selection_cancellation_marker(marker, handle)?;
14001    Ok(true)
14002}
14003
14004fn validate_selection_cancellations_for_handles(
14005    state: &WorkflowState,
14006    handles: &[DurableOperationHandle],
14007) -> Result<()> {
14008    let Some(group_id) = handles
14009        .first()
14010        .map(|handle| handle.selection_group_id.as_str())
14011    else {
14012        return Ok(());
14013    };
14014    for marker in state
14015        .cancelled_selection_members
14016        .iter()
14017        .filter(|marker| marker.selection_group_id == group_id)
14018    {
14019        let Some(handle) = handles
14020            .iter()
14021            .find(|handle| handle.base_sequence == marker.member_base_sequence)
14022        else {
14023            return Err(invalid_recorded_history(
14024                "selection_cancellation_member_mismatch",
14025                marker.member_base_sequence,
14026                "SelectionOperationCancelled matching an authored selection handle",
14027                &format!("{marker:?}"),
14028                "selection cancellation member base does not name an authored member",
14029            ));
14030        };
14031        validate_selection_cancellation_marker(marker, handle)?;
14032    }
14033    Ok(())
14034}
14035
14036fn validate_selection_cancellation_marker(
14037    marker: &SelectionCancellation,
14038    handle: &DurableOperationHandle,
14039) -> Result<()> {
14040    if marker.selection_group_id != handle.selection_group_id
14041        || marker.member_key != handle.key
14042        || marker.member_index != handle.index
14043        || marker.member_base_sequence != handle.base_sequence
14044        || marker.member_size != handle.size
14045        || marker.operation_kind != handle.kind
14046        || marker.operation_identity != handle.identity
14047    {
14048        return Err(invalid_recorded_history(
14049            "selection_cancellation_member_mismatch",
14050            handle.base_sequence,
14051            "SelectionOperationCancelled matching the authored selection handle",
14052            &format!("{marker:?}"),
14053            "selection cancellation history targets different authored member metadata",
14054        ));
14055    }
14056    Ok(())
14057}
14058
14059/// Future returned by [`DurableOperationHandle::await_result`].
14060pub struct DurableOperationAwaitCall {
14061    handle: DurableOperationHandle,
14062}
14063
14064impl Future for DurableOperationAwaitCall {
14065    type Output = Result<ParallelResult>;
14066
14067    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14068        let mut state = match self.handle.ctx.state.lock() {
14069            Ok(state) => state,
14070            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14071        };
14072        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
14073            return Poll::Ready(Err(error));
14074        }
14075        match state.prepare_selection_handle_cancellation(&self.handle) {
14076            Ok(true) => return Poll::Pending,
14077            Ok(false) => {}
14078            Err(error) => return Poll::Ready(Err(error)),
14079        }
14080        match selection_cancellation_for_handle(&state, &self.handle) {
14081            Err(error) => return Poll::Ready(Err(error)),
14082            Ok(false) => {}
14083            Ok(true) => {
14084                state.advance_cancellation_receipt(
14085                    &self.handle.selection_group_id,
14086                    self.handle.base_sequence,
14087                );
14088                return Poll::Ready(Err(Error::DurableOperationCancelled(
14089                    DurableOperationCancelled {
14090                        selection_group_id: self.handle.selection_group_id.clone(),
14091                        member_key: self.handle.key.clone(),
14092                        member_index: self.handle.index,
14093                        operation_kind: self.handle.kind.clone(),
14094                        operation_identity: self.handle.identity.clone(),
14095                    },
14096                )));
14097            }
14098        }
14099        match recorded_selection_member_outcome(&state, &self.handle) {
14100            Ok(Some(result)) => {
14101                state.advance_cancellation_handle(&self.handle, false);
14102                Poll::Ready(Ok(result))
14103            }
14104            Ok(None) => Poll::Pending,
14105            Err(error) => {
14106                if !workflow_task_integrity_error(&error) {
14107                    state.advance_cancellation_handle(&self.handle, true);
14108                }
14109                Poll::Ready(Err(error))
14110            }
14111        }
14112    }
14113}
14114
14115fn validate_selection_delivery_handle(
14116    state: &WorkflowState,
14117    handle: &DurableOperationHandle,
14118) -> Result<()> {
14119    let path = state
14120        .recorded_commands
14121        .iter()
14122        .find(|command| command.sequence() == handle.base_sequence)
14123        .and_then(|command| match command {
14124            RecordedCommand::Activity {
14125                parallel_group_path,
14126                ..
14127            }
14128            | RecordedCommand::ChildWorkflow {
14129                parallel_group_path,
14130                ..
14131            }
14132            | RecordedCommand::Timer {
14133                parallel_group_path,
14134                ..
14135            }
14136            | RecordedCommand::SignalWait {
14137                parallel_group_path,
14138                ..
14139            }
14140            | RecordedCommand::ConditionWait {
14141                parallel_group_path,
14142                ..
14143            } => parallel_group_path.as_ref(),
14144            _ => None,
14145        })
14146        .and_then(|path| path.first());
14147    let matches = path.is_some_and(|entry| {
14148        entry.parallel_group_mode.as_deref() == Some("select")
14149            && entry.parallel_group_id == handle.selection_group_id
14150            && entry.selection_member_key.as_ref() == Some(&handle.key)
14151            && entry.selection_member_index == Some(handle.index)
14152            && entry.selection_member_base_sequence == Some(handle.base_sequence)
14153            && entry.selection_member_size == Some(handle.size)
14154            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
14155    });
14156    if !matches
14157        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
14158            != handle.identity
14159    {
14160        return Err(invalid_recorded_history(
14161            "cooperative_cancellation_call_mismatch",
14162            handle.base_sequence,
14163            "selection handle matching its authored durable identity",
14164            &format!("{handle:?}"),
14165            "selection handle identity or member metadata changed before cancellation replay",
14166        ));
14167    }
14168    Ok(())
14169}
14170
14171/// Future returned by [`DurableOperationHandle::cancel`].
14172pub struct CancelDurableOperationCall {
14173    handle: DurableOperationHandle,
14174    emitted: bool,
14175}
14176
14177impl Future for CancelDurableOperationCall {
14178    type Output = Result<()>;
14179
14180    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14181        let ctx = self.handle.ctx.clone();
14182        let mut state = match ctx.state.lock() {
14183            Ok(state) => state,
14184            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14185        };
14186        match selection_cancellation_for_handle(&state, &self.handle) {
14187            Err(error) => return Poll::Ready(Err(error)),
14188            Ok(true) => {
14189                state.advance_cancellation_receipt(
14190                    &self.handle.selection_group_id,
14191                    self.handle.base_sequence,
14192                );
14193                return Poll::Ready(Ok(()));
14194            }
14195            Ok(false) => {}
14196        }
14197        if recorded_selection_member_is_terminal(&state, &self.handle) {
14198            return Poll::Ready(Ok(()));
14199        }
14200        if !self.emitted {
14201            state.commands.push(json!({
14202                "type": "cancel_selection_operation",
14203                "selection_group_id": self.handle.selection_group_id,
14204                "member_key": self.handle.key,
14205                "member_index": self.handle.index,
14206                "member_base_sequence": self.handle.base_sequence,
14207                "member_size": self.handle.size,
14208                "operation_kind": self.handle.kind,
14209                "operation_identity": self.handle.identity,
14210            }));
14211            self.emitted = true;
14212        }
14213        // The cancellation command is only a request. Do not expose workflow
14214        // state after cancel until committed SelectionOperationCancelled
14215        // history proves that the request won the race with member completion.
14216        Poll::Pending
14217    }
14218}
14219
14220trait PollNestedResultExt<T> {
14221    fn flatten_result(self) -> Poll<Result<T>>;
14222}
14223
14224impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
14225    fn flatten_result(self) -> Poll<Result<T>> {
14226        match self {
14227            Poll::Ready(Ok(result)) => Poll::Ready(result),
14228            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14229            Poll::Pending => Poll::Pending,
14230        }
14231    }
14232}
14233
14234struct SagaCompensation {
14235    activity_type: String,
14236    options: ActivityOptions,
14237    arguments: AvroValue,
14238    registration_order: usize,
14239}
14240
14241/// Workflow-local deterministic saga compensation helper.
14242///
14243/// Register each compensation only after its forward step succeeds. Passing
14244/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
14245/// reverse registration order after any failure, including cooperative
14246/// cancellation. Each compensation is an ordinary durable activity, so replay,
14247/// duplicate delivery, and worker restart use existing history semantics.
14248pub struct Saga {
14249    ctx: WorkflowContext,
14250    compensations: Vec<SagaCompensation>,
14251}
14252
14253impl Saga {
14254    fn new(ctx: WorkflowContext) -> Self {
14255        Self {
14256            ctx,
14257            compensations: Vec::new(),
14258        }
14259    }
14260
14261    pub fn add_compensation<T: Serialize>(
14262        &mut self,
14263        activity_type: impl Into<String>,
14264        args: T,
14265    ) -> Result<&mut Self> {
14266        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
14267    }
14268
14269    pub fn add_compensation_with_options<T: Serialize>(
14270        &mut self,
14271        activity_type: impl Into<String>,
14272        options: ActivityOptions,
14273        args: T,
14274    ) -> Result<&mut Self> {
14275        let activity_type = activity_type.into();
14276        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
14277            return Err(Error::Codec(
14278                "saga compensation activity type must be non-empty without surrounding whitespace"
14279                    .to_string(),
14280            ));
14281        }
14282        options.validate().map_err(Error::InvalidActivityOptions)?;
14283        let arguments = AvroValue::from_serialize(&args)?;
14284        let registration_order = self.compensations.len() + 1;
14285        self.compensations.push(SagaCompensation {
14286            activity_type,
14287            options,
14288            arguments,
14289            registration_order,
14290        });
14291        Ok(self)
14292    }
14293
14294    /// Compensate `initiating_failure` and return the failure that must remain.
14295    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14296        let _shield = match self.ctx.cancellation_shield() {
14297            Ok(shield) => shield,
14298            Err(error) => return error,
14299        };
14300        while let Some(compensation) = self.compensations.pop() {
14301            if let Err(compensation_failure) = self
14302                .ctx
14303                .activity_with_options(
14304                    compensation.activity_type.clone(),
14305                    compensation.options,
14306                    compensation.arguments,
14307                )
14308                .await
14309            {
14310                if workflow_task_integrity_error(&compensation_failure) {
14311                    return compensation_failure;
14312                }
14313                return Error::SagaCompensationFailed(SagaCompensationFailure {
14314                    initiating_failure: Box::new(initiating_failure),
14315                    compensation_failure: Box::new(compensation_failure),
14316                    compensation_activity_type: compensation.activity_type,
14317                    compensation_registration_order: compensation.registration_order,
14318                });
14319            }
14320        }
14321        initiating_failure
14322    }
14323
14324    /// Return a successful forward value or compensate and preserve its failure.
14325    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14326        match outcome {
14327            Ok(value) => Ok(value),
14328            Err(error) => Err(self.compensate(error).await),
14329        }
14330    }
14331}
14332
14333pub struct ActivityCall {
14334    ctx: WorkflowContext,
14335    activity_type: String,
14336    options: ActivityOptions,
14337    worker_session: Option<WorkerSessionOptions>,
14338    args: Option<Result<AvroValue>>,
14339    scheduled: bool,
14340    local: bool,
14341    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
14342    parallel_group_path: Vec<ParallelGroupMetadata>,
14343}
14344
14345impl ActivityCall {
14346    fn poll_avro_value(
14347        mut self: Pin<&mut Self>,
14348        _cx: &mut TaskContext<'_>,
14349    ) -> Poll<Result<AvroValue>> {
14350        let ctx = self.ctx.clone();
14351        let mut state = match ctx.state.lock() {
14352            Ok(state) => state,
14353            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14354        };
14355
14356        if let Some(result) = &self.local_result {
14357            return match result.lock() {
14358                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
14359                    Poll::Ready(result.map_err(Error::ActivityFailed))
14360                }),
14361                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14362            };
14363        }
14364        if self.scheduled {
14365            return Poll::Pending;
14366        }
14367
14368        let options = match self.options.validate() {
14369            Ok(options) => options,
14370            Err(error) => {
14371                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
14372            }
14373        };
14374        if self.local {
14375            if self.worker_session.is_some() {
14376                return Poll::Ready(Err(Error::WorkerLoop(
14377                    "local activities cannot use worker-session routing".into(),
14378                )));
14379            }
14380            if let Err(error) = local_activity::validate(&options) {
14381                return Poll::Ready(Err(error));
14382            }
14383        }
14384        let session = match self
14385            .worker_session
14386            .as_ref()
14387            .map(WorkerSessionOptions::to_wire)
14388            .transpose()
14389        {
14390            Ok(value) => value,
14391            Err(error) => return Poll::Ready(Err(error)),
14392        };
14393        let session_queue = session
14394            .as_ref()
14395            .and_then(|session| session["queue"].as_str());
14396        let task_queue = options
14397            .task_queue
14398            .clone()
14399            .or_else(|| session_queue.map(str::to_owned))
14400            .unwrap_or_else(|| state.task_queue.clone());
14401        if session_queue.is_some_and(|queue| queue != task_queue) {
14402            return Poll::Ready(Err(Error::WorkerLoop(
14403                "worker-session queue must match the activity task queue".into(),
14404            )));
14405        }
14406        let current_recorded_options = RecordedActivityOptions {
14407            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
14408            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
14409            retry_policy: current_activity_retry_snapshot(&options),
14410            worker_session: session,
14411        };
14412
14413        let cursor = state.command_cursor;
14414        let call_kind = if self.local {
14415            CancellationCallKind::LocalActivity
14416        } else {
14417            CancellationCallKind::Activity
14418        };
14419        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14420            return Poll::Ready(Err(error));
14421        }
14422        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
14423            Ok(recorded) => recorded,
14424            Err(error) => return Poll::Ready(Err(error)),
14425        };
14426        if let Some(recorded) = recorded {
14427            let sequence = recorded.sequence();
14428            match recorded {
14429                RecordedCommand::Activity {
14430                    activity_type,
14431                    cancellation_policy,
14432                    options: recorded_options,
14433                    outcome,
14434                    parallel_group_path,
14435                    ..
14436                } => {
14437                    let current_policy = options
14438                        .cancellation_policy
14439                        .unwrap_or(CancellationPolicy::TryCancel)
14440                        .as_str();
14441                    if cancellation_policy != current_policy {
14442                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14443                            ReplayFailure::new(
14444                                "activity_cancellation_policy_changed",
14445                                Some(sequence),
14446                                Some(cancellation_policy),
14447                                Some(current_policy.to_string()),
14448                                "Activity cancellation policy changed during replay",
14449                            ),
14450                        )));
14451                    }
14452                    if let Err(error) = ensure_parallel_path_matches(
14453                        sequence,
14454                        parallel_group_path.as_deref(),
14455                        &self.parallel_group_path,
14456                    ) {
14457                        return Poll::Ready(Err(error));
14458                    }
14459                    if let Some(recorded_type) = activity_type {
14460                        if recorded_type != self.activity_type {
14461                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14462                                ReplayFailure::new(
14463                                    "recorded_command_detail_mismatch",
14464                                    Some(sequence),
14465                                    Some(format!("activity:{recorded_type}")),
14466                                    Some(format!("activity:{}", self.activity_type)),
14467                                    "recorded activity type differs from the current workflow command",
14468                                ),
14469                            )));
14470                        }
14471                    }
14472                    if let Some(recorded_options) = recorded_options {
14473                        if recorded_options.worker_session
14474                            != current_recorded_options.worker_session
14475                        {
14476                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14477                                "activity_worker_session_mismatch", Some(sequence),
14478                                Some(activity_options_description(&recorded_options)),
14479                                Some(activity_options_description(&current_recorded_options)),
14480                                "recorded worker-session routing differs from the current activity",
14481                            ))));
14482                        }
14483                        if !recorded_options
14484                            .task_queue
14485                            .matches_current(&current_recorded_options.task_queue)
14486                        {
14487                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14488                                ReplayFailure::new(
14489                                    "activity_task_queue_mismatch",
14490                                    Some(sequence),
14491                                    Some(activity_options_description(&recorded_options)),
14492                                    Some(activity_options_description(&current_recorded_options)),
14493                                    "recorded activity task queue differs from the current workflow command",
14494                                ),
14495                            )));
14496                        }
14497                        if (self.local
14498                            && matches!(
14499                                recorded_options.execution_mode,
14500                                RecordedSnapshotValue::Unknown
14501                            ))
14502                            || !recorded_options
14503                                .execution_mode
14504                                .matches_current(&current_recorded_options.execution_mode)
14505                        {
14506                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14507                                ReplayFailure::new(
14508                                    "activity_execution_mode_mismatch",
14509                                    Some(sequence),
14510                                    Some(activity_options_description(&recorded_options)),
14511                                    Some(activity_options_description(&current_recorded_options)),
14512                                    "recorded activity execution mode differs from the current workflow command",
14513                                ),
14514                            )));
14515                        }
14516                        if !recorded_options
14517                            .retry_policy
14518                            .matches_current(&current_recorded_options.retry_policy)
14519                        {
14520                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14521                                ReplayFailure::new(
14522                                    "activity_retry_policy_mismatch",
14523                                    Some(sequence),
14524                                    Some(activity_options_description(&recorded_options)),
14525                                    Some(activity_options_description(&current_recorded_options)),
14526                                    "recorded activity retry policy differs from the current workflow command",
14527                                ),
14528                            )));
14529                        }
14530                    }
14531                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
14532                        return Poll::Ready(Err(error));
14533                    }
14534                    match state.prepare_scalar_cancellation(
14535                        cursor,
14536                        call_kind,
14537                        &self.parallel_group_path,
14538                    ) {
14539                        Ok(true) => {
14540                            self.scheduled = true;
14541                            return Poll::Pending;
14542                        }
14543                        Ok(false) => {}
14544                        Err(error) => return Poll::Ready(Err(error)),
14545                    }
14546                    state.command_cursor += 1;
14547                    if let Some(outcome) = outcome {
14548                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14549                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
14550                    }
14551                    state.matched_recorded_pending = true;
14552                    self.scheduled = true;
14553                    return Poll::Pending;
14554                }
14555                other => {
14556                    return Poll::Ready(Err(command_mismatch(
14557                        &other,
14558                        format!("activity:{}", self.activity_type),
14559                    )));
14560                }
14561            }
14562        }
14563
14564        if !self.scheduled {
14565            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14566                Ok(args) => args,
14567                Err(error) => return Poll::Ready(Err(error)),
14568            };
14569            let arguments = normalize_avro_arguments(args);
14570            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
14571                Ok(envelope) => envelope,
14572                Err(error) => return Poll::Ready(Err(error)),
14573            };
14574
14575            let mut command = serde_json::Map::from_iter([
14576                (
14577                    "type".to_string(),
14578                    json!(if self.local {
14579                        "record_local_activity"
14580                    } else {
14581                        "schedule_activity"
14582                    }),
14583                ),
14584                (
14585                    "activity_type".to_string(),
14586                    json!(self.activity_type.clone()),
14587                ),
14588                ("queue".to_string(), json!(task_queue)),
14589                ("arguments".to_string(), envelope),
14590            ]);
14591            for (field, value) in [
14592                ("start_to_close_timeout", options.start_to_close_timeout),
14593                (
14594                    "schedule_to_start_timeout",
14595                    options.schedule_to_start_timeout,
14596                ),
14597                (
14598                    "schedule_to_close_timeout",
14599                    options.schedule_to_close_timeout,
14600                ),
14601                ("heartbeat_timeout", options.heartbeat_timeout),
14602            ] {
14603                if let Some(value) = value {
14604                    command.insert(field.to_string(), json!(value));
14605                }
14606            }
14607            if let Some(retry_policy) = &options.retry_policy {
14608                command.insert("retry_policy".to_string(), retry_policy.clone());
14609            }
14610            if let Some(policy) = options.cancellation_policy {
14611                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
14612            }
14613            if let Some(session) = current_recorded_options.worker_session {
14614                command.insert("worker_session".into(), session);
14615            }
14616            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14617            ctx.apply_scope_membership(&mut command);
14618            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
14619                Ok(true) => {
14620                    self.scheduled = true;
14621                    return Poll::Pending;
14622                }
14623                Ok(false) => {}
14624                Err(error) => return Poll::Ready(Err(error)),
14625            }
14626            if self.local {
14627                command.remove("queue");
14628                command.insert("execution_mode".into(), json!("local"));
14629                let result = Arc::new(Mutex::new(None));
14630                let command_index = state.commands.len();
14631                state.local_activity_requests.push(local_activity::Request {
14632                    command_index,
14633                    options,
14634                    arguments,
14635                    result: result.clone(),
14636                });
14637                self.local_result = Some(result);
14638            }
14639            state.commands.push(Value::Object(command));
14640            self.scheduled = true;
14641        }
14642
14643        Poll::Pending
14644    }
14645}
14646
14647impl Future for ActivityCall {
14648    type Output = Result<Value>;
14649
14650    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14651        match self.poll_avro_value(cx) {
14652            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
14653            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14654            Poll::Pending => Poll::Pending,
14655        }
14656    }
14657}
14658
14659/// Future returned by [`WorkflowContext::sleep`].
14660pub struct TimerCall {
14661    ctx: WorkflowContext,
14662    delay_seconds: Option<u64>,
14663    scheduled: bool,
14664    matched_pending: bool,
14665    parallel_group_path: Vec<ParallelGroupMetadata>,
14666}
14667
14668impl Future for TimerCall {
14669    type Output = Result<()>;
14670
14671    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14672        if self.matched_pending {
14673            return Poll::Pending;
14674        }
14675
14676        let ctx = self.ctx.clone();
14677        let Some(requested_delay) = self.delay_seconds else {
14678            return Poll::Ready(Err(Error::TimerDurationOverflow));
14679        };
14680        let mut state = match ctx.state.lock() {
14681            Ok(state) => state,
14682            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14683        };
14684
14685        let cursor = state.command_cursor;
14686        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14687            return Poll::Ready(Err(error));
14688        }
14689        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
14690        {
14691            Ok(recorded) => recorded,
14692            Err(error) => return Poll::Ready(Err(error)),
14693        };
14694        if let Some(recorded) = recorded {
14695            match recorded {
14696                RecordedCommand::Timer {
14697                    sequence,
14698                    delay_seconds,
14699                    fired,
14700                    parallel_group_path,
14701                    ..
14702                } => {
14703                    if let Err(error) =
14704                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
14705                    {
14706                        return Poll::Ready(Err(error));
14707                    }
14708                    if let Err(error) = ensure_parallel_path_matches(
14709                        sequence,
14710                        parallel_group_path.as_deref(),
14711                        &self.parallel_group_path,
14712                    ) {
14713                        return Poll::Ready(Err(error));
14714                    }
14715                    if delay_seconds != requested_delay {
14716                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14717                            ReplayFailure::new(
14718                                "timer_delay_mismatch",
14719                                Some(sequence),
14720                                Some(format!("timer:{delay_seconds}s")),
14721                                Some(format!("timer:{requested_delay}s")),
14722                                "recorded timer delay differs from the current workflow command",
14723                            ),
14724                        )));
14725                    }
14726                    if let Err(error) =
14727                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
14728                    {
14729                        return Poll::Ready(Err(error));
14730                    }
14731                    match state.prepare_scalar_cancellation(
14732                        cursor,
14733                        CancellationCallKind::Timer,
14734                        &self.parallel_group_path,
14735                    ) {
14736                        Ok(true) => {
14737                            self.scheduled = true;
14738                            self.matched_pending = true;
14739                            return Poll::Pending;
14740                        }
14741                        Ok(false) => {}
14742                        Err(error) => return Poll::Ready(Err(error)),
14743                    }
14744                    state.command_cursor += 1;
14745                    if fired {
14746                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14747                        return Poll::Ready(Ok(()));
14748                    }
14749                    state.matched_recorded_pending = true;
14750                    self.scheduled = true;
14751                    self.matched_pending = true;
14752                    return Poll::Pending;
14753                }
14754                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
14755            }
14756        }
14757
14758        if !self.scheduled {
14759            let mut command = serde_json::Map::from_iter([
14760                ("type".to_string(), json!("start_timer")),
14761                ("delay_seconds".to_string(), json!(requested_delay)),
14762            ]);
14763            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
14764                Ok(Some(proof)) => {
14765                    command.insert("cancellation_cleanup".into(), proof);
14766                }
14767                Ok(None) => {}
14768                Err(error) => return Poll::Ready(Err(error)),
14769            }
14770            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14771            ctx.apply_scope_membership(&mut command);
14772            match state.prepare_scalar_cancellation(
14773                cursor,
14774                CancellationCallKind::Timer,
14775                &self.parallel_group_path,
14776            ) {
14777                Ok(true) => {
14778                    self.scheduled = true;
14779                    self.matched_pending = true;
14780                    return Poll::Pending;
14781                }
14782                Ok(false) => {}
14783                Err(error) => return Poll::Ready(Err(error)),
14784            }
14785            state.commands.push(Value::Object(command));
14786            self.scheduled = true;
14787        }
14788
14789        Poll::Pending
14790    }
14791}
14792
14793/// Future returned by [`WorkflowContext::wait_condition`].
14794pub struct ConditionWaitCall {
14795    ctx: WorkflowContext,
14796    options: ConditionWaitOptions,
14797    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
14798    occurrence_id: Option<String>,
14799    opened_wait: bool,
14800    parallel_group_path: Vec<ParallelGroupMetadata>,
14801}
14802
14803impl Future for ConditionWaitCall {
14804    type Output = Result<ConditionWaitResult>;
14805
14806    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14807        if self.opened_wait {
14808            return Poll::Pending;
14809        }
14810
14811        let options = match self.options.validate() {
14812            Ok(options) => options,
14813            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
14814        };
14815        let ctx = self.ctx.clone();
14816        let occurrence_id = match self.occurrence_id.as_ref() {
14817            Some(occurrence_id) => occurrence_id.clone(),
14818            None => {
14819                let mut state = match ctx.state.lock() {
14820                    Ok(state) => state,
14821                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14822                };
14823                let ordinal = state.condition_wait_occurrence_counter;
14824                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
14825                    Some(next) => next,
14826                    None => {
14827                        return Poll::Ready(Err(Error::WorkerLoop(
14828                            "condition wait occurrence counter overflowed".to_string(),
14829                        )))
14830                    }
14831                };
14832                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
14833                drop(state);
14834                self.occurrence_id = Some(occurrence_id.clone());
14835                occurrence_id
14836            }
14837        };
14838
14839        let recorded_result = {
14840            let mut state = match ctx.state.lock() {
14841                Ok(state) => state,
14842                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14843            };
14844            let initial_cursor = state.command_cursor;
14845            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
14846                return Poll::Ready(Err(error));
14847            }
14848            let recorded = match state
14849                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
14850            {
14851                Ok(recorded) => recorded,
14852                Err(error) => return Poll::Ready(Err(error)),
14853            };
14854            let Some(recorded) = recorded else {
14855                drop(state);
14856                return self.poll_new_condition(options);
14857            };
14858            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
14859                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
14860            }
14861
14862            let mut cursor = state.command_cursor;
14863            let mut result = None;
14864            let mut pending_delivery = false;
14865            loop {
14866                if cursor > initial_cursor
14867                    && matches!(
14868                        state.recorded_commands.get(cursor),
14869                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
14870                    )
14871                {
14872                    break;
14873                }
14874                let recorded = match state
14875                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
14876                {
14877                    Ok(recorded) => recorded,
14878                    Err(error) => return Poll::Ready(Err(error)),
14879                };
14880                let Some(RecordedCommand::ConditionWait {
14881                    sequence,
14882                    occurrence_id: ref recorded_occurrence_id,
14883                    ref condition_key,
14884                    ref predicate_identity,
14885                    timeout_seconds,
14886                    result: recorded_result,
14887                    ref parallel_group_path,
14888                    ..
14889                }) = recorded
14890                else {
14891                    break;
14892                };
14893
14894                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
14895                    break;
14896                }
14897                if let Err(error) = ensure_parallel_path_matches(
14898                    sequence,
14899                    parallel_group_path.as_deref(),
14900                    &self.parallel_group_path,
14901                ) {
14902                    return Poll::Ready(Err(error));
14903                }
14904                if let Err(error) = validate_recorded_condition_wait(
14905                    sequence,
14906                    recorded_occurrence_id,
14907                    condition_key.as_deref(),
14908                    predicate_identity,
14909                    timeout_seconds,
14910                    &occurrence_id,
14911                    &options,
14912                ) {
14913                    return Poll::Ready(Err(error));
14914                }
14915                if result == Some(ConditionWaitResult::TimedOut) {
14916                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14917                        "condition_wait_reopened_after_timeout",
14918                        Some(sequence),
14919                        Some("timed-out condition is terminal".to_string()),
14920                        Some("another physical wait-open".to_string()),
14921                        "condition history reopened one logical wait after its durable timeout",
14922                    ))));
14923                }
14924                if let Err(error) =
14925                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
14926                {
14927                    return Poll::Ready(Err(error));
14928                }
14929                match state.prepare_scalar_cancellation(
14930                    cursor,
14931                    CancellationCallKind::Condition,
14932                    &self.parallel_group_path,
14933                ) {
14934                    Ok(pending) => pending_delivery |= pending,
14935                    Err(error) => return Poll::Ready(Err(error)),
14936                }
14937                result = recorded_result;
14938                if result.is_some() {
14939                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14940                }
14941                cursor += 1;
14942            }
14943            state.command_cursor = cursor;
14944            if pending_delivery {
14945                self.opened_wait = true;
14946                return Poll::Pending;
14947            }
14948            result
14949        };
14950
14951        if let Some(result) = recorded_result {
14952            return Poll::Ready(Ok(result));
14953        }
14954
14955        self.poll_open_condition(options, true)
14956    }
14957}
14958
14959impl ConditionWaitCall {
14960    fn poll_new_condition(
14961        self: Pin<&mut Self>,
14962        options: ValidatedConditionWaitOptions,
14963    ) -> Poll<Result<ConditionWaitResult>> {
14964        self.poll_open_condition(options, false)
14965    }
14966
14967    fn poll_open_condition(
14968        mut self: Pin<&mut Self>,
14969        options: ValidatedConditionWaitOptions,
14970        recorded_wait: bool,
14971    ) -> Poll<Result<ConditionWaitResult>> {
14972        {
14973            let ctx = self.ctx.clone();
14974            let mut state = match ctx.state.lock() {
14975                Ok(state) => state,
14976                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14977            };
14978            let cursor = state.command_cursor;
14979            match state.prepare_scalar_cancellation(
14980                cursor,
14981                CancellationCallKind::Condition,
14982                &self.parallel_group_path,
14983            ) {
14984                Ok(true) => {
14985                    self.opened_wait = true;
14986                    return Poll::Pending;
14987                }
14988                Ok(false) => {}
14989                Err(error) => return Poll::Ready(Err(error)),
14990            }
14991        }
14992        let selection_member = self
14993            .parallel_group_path
14994            .first()
14995            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14996        match (self.predicate)() {
14997            Ok(true) if !selection_member || recorded_wait => {
14998                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14999            }
15000            Ok(_) => {}
15001            Err(error) => return Poll::Ready(Err(error)),
15002        }
15003        if options.timeout_seconds == Some(0) && !selection_member {
15004            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
15005        }
15006
15007        let ctx = self.ctx.clone();
15008        let mut state = match ctx.state.lock() {
15009            Ok(state) => state,
15010            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15011        };
15012        let mut command = serde_json::Map::from_iter([
15013            ("type".to_string(), json!("open_condition_wait")),
15014            (
15015                "condition_wait_occurrence_id".to_string(),
15016                json!(self.occurrence_id.as_deref().unwrap_or_default()),
15017            ),
15018            ("condition_key".to_string(), json!(options.condition_key)),
15019            (
15020                "condition_definition_fingerprint".to_string(),
15021                json!(options.predicate_identity),
15022            ),
15023        ]);
15024        if let Some(timeout_seconds) = options.timeout_seconds {
15025            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
15026        }
15027        apply_parallel_group_path(&mut command, &self.parallel_group_path);
15028        ctx.apply_scope_membership(&mut command);
15029        state.commands.push(Value::Object(command));
15030        drop(state);
15031        self.opened_wait = true;
15032        Poll::Pending
15033    }
15034}
15035
15036fn validate_recorded_condition_wait(
15037    sequence: u64,
15038    recorded_occurrence_id: &str,
15039    recorded_key: Option<&str>,
15040    recorded_predicate_identity: &str,
15041    recorded_timeout_seconds: Option<u64>,
15042    current_occurrence_id: &str,
15043    current: &ValidatedConditionWaitOptions,
15044) -> Result<()> {
15045    if recorded_occurrence_id != current_occurrence_id {
15046        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15047            "condition_wait_occurrence_mismatch",
15048            Some(sequence),
15049            Some(recorded_occurrence_id.to_string()),
15050            Some(current_occurrence_id.to_string()),
15051            "recorded condition occurrence differs from the current authored wait position",
15052        )));
15053    }
15054    if recorded_key != Some(current.condition_key.as_str()) {
15055        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15056            "condition_wait_key_mismatch",
15057            Some(sequence),
15058            recorded_key.map(str::to_string),
15059            Some(current.condition_key.clone()),
15060            "recorded condition identity differs from the current workflow wait",
15061        )));
15062    }
15063    if recorded_predicate_identity != current.predicate_identity {
15064        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15065            "condition_wait_predicate_mismatch",
15066            Some(sequence),
15067            Some(recorded_predicate_identity.to_string()),
15068            Some(current.predicate_identity.clone()),
15069            "recorded condition predicate behavior differs from current workflow code",
15070        )));
15071    }
15072    if recorded_timeout_seconds != current.timeout_seconds {
15073        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15074            "condition_wait_timeout_mismatch",
15075            Some(sequence),
15076            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
15077            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
15078            "recorded condition timeout differs from the current workflow wait",
15079        )));
15080    }
15081    Ok(())
15082}
15083
15084/// Future returned by [`WorkflowContext::start_child_workflow`].
15085pub struct ChildWorkflowCall {
15086    ctx: WorkflowContext,
15087    workflow_type: String,
15088    options: ChildWorkflowOptions,
15089    args: Option<Result<AvroValue>>,
15090    scheduled: bool,
15091    matched_pending: bool,
15092    parallel_group_path: Vec<ParallelGroupMetadata>,
15093}
15094
15095impl ChildWorkflowCall {
15096    fn poll_avro_value(
15097        mut self: Pin<&mut Self>,
15098        _cx: &mut TaskContext<'_>,
15099    ) -> Poll<Result<ChildWorkflowAvroResult>> {
15100        if self.matched_pending {
15101            return Poll::Pending;
15102        }
15103
15104        let ctx = self.ctx.clone();
15105        let mut state = match ctx.state.lock() {
15106            Ok(state) => state,
15107            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15108        };
15109
15110        let cursor = state.command_cursor;
15111        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15112            return Poll::Ready(Err(error));
15113        }
15114        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
15115        {
15116            Ok(recorded) => recorded,
15117            Err(error) => return Poll::Ready(Err(error)),
15118        };
15119        if let Some(recorded) = recorded {
15120            let sequence = recorded.sequence();
15121            match recorded {
15122                RecordedCommand::ChildWorkflow {
15123                    workflow_type,
15124                    policies,
15125                    outcome,
15126                    parallel_group_path,
15127                    ..
15128                } => {
15129                    if let Err(error) = ensure_parallel_path_matches(
15130                        sequence,
15131                        parallel_group_path.as_deref(),
15132                        &self.parallel_group_path,
15133                    ) {
15134                        return Poll::Ready(Err(error));
15135                    }
15136                    if let Some(recorded_type) = workflow_type {
15137                        if recorded_type != self.workflow_type {
15138                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15139                                ReplayFailure::new(
15140                                    "recorded_command_detail_mismatch",
15141                                    Some(sequence),
15142                                    Some(format!("child workflow:{recorded_type}")),
15143                                    Some(format!("child workflow:{}", self.workflow_type)),
15144                                    "recorded child workflow type differs from the current workflow command",
15145                                ),
15146                            )));
15147                        }
15148                    }
15149                    if let Err(error) =
15150                        ensure_child_policies_match(sequence, &policies, &self.options)
15151                    {
15152                        return Poll::Ready(Err(error));
15153                    }
15154                    if let Err(error) =
15155                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
15156                    {
15157                        return Poll::Ready(Err(error));
15158                    }
15159                    match state.prepare_scalar_cancellation(
15160                        cursor,
15161                        CancellationCallKind::Child,
15162                        &self.parallel_group_path,
15163                    ) {
15164                        Ok(true) => {
15165                            self.scheduled = true;
15166                            self.matched_pending = true;
15167                            return Poll::Pending;
15168                        }
15169                        Ok(false) => {}
15170                        Err(error) => return Poll::Ready(Err(error)),
15171                    }
15172                    state.command_cursor += 1;
15173                    if let Some(outcome) = outcome {
15174                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15175                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
15176                    }
15177                    state.matched_recorded_pending = true;
15178                    self.scheduled = true;
15179                    self.matched_pending = true;
15180                    return Poll::Pending;
15181                }
15182                other => {
15183                    return Poll::Ready(Err(command_mismatch(
15184                        &other,
15185                        format!("child workflow:{}", self.workflow_type),
15186                    )));
15187                }
15188            }
15189        }
15190
15191        if !self.scheduled {
15192            if self.options.task_queue.trim().is_empty() {
15193                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15194                    "task_queue must not be empty".to_string(),
15195                )));
15196            }
15197            for (name, value) in [
15198                (
15199                    "execution_timeout_seconds",
15200                    self.options.execution_timeout_seconds,
15201                ),
15202                ("run_timeout_seconds", self.options.run_timeout_seconds),
15203            ] {
15204                if value == Some(0) {
15205                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
15206                        "{name} must be at least 1"
15207                    ))));
15208                }
15209            }
15210
15211            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15212                Ok(args) => args,
15213                Err(error) => return Poll::Ready(Err(error)),
15214            };
15215            let arguments = match encode_typed_envelope(
15216                &normalize_avro_arguments(args),
15217                &state.payload_codec,
15218            ) {
15219                Ok(arguments) => arguments,
15220                Err(error) => return Poll::Ready(Err(error)),
15221            };
15222            let mut command = json!({
15223                "type": "start_child_workflow",
15224                "workflow_type": self.workflow_type,
15225                "queue": self.options.task_queue,
15226                "parent_close_policy": self.options.parent_close_policy.as_str(),
15227                "arguments": arguments,
15228            });
15229            let object = command
15230                .as_object_mut()
15231                .expect("child workflow command is always an object");
15232            if self.options.cancellation_policy != CancellationPolicy::Abandon {
15233                object.insert(
15234                    "cancellation_policy".to_string(),
15235                    json!(self.options.cancellation_policy.as_str()),
15236                );
15237            }
15238            if let Some(policy) = &self.options.retry_policy {
15239                let mut retry_policy = serde_json::Map::new();
15240                if let Some(max_attempts) = policy.max_attempts {
15241                    if max_attempts == 0 {
15242                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15243                            "retry_policy.max_attempts must be at least 1".to_string(),
15244                        )));
15245                    }
15246                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
15247                }
15248                if !policy.backoff_seconds.is_empty() {
15249                    retry_policy
15250                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
15251                }
15252                if !policy.non_retryable_error_types.is_empty() {
15253                    retry_policy.insert(
15254                        "non_retryable_error_types".to_string(),
15255                        json!(policy.non_retryable_error_types),
15256                    );
15257                }
15258                if retry_policy.is_empty() {
15259                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15260                        "retry_policy must configure at least one field".to_string(),
15261                    )));
15262                }
15263                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
15264            }
15265            if let Some(seconds) = self.options.execution_timeout_seconds {
15266                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
15267            }
15268            if let Some(seconds) = self.options.run_timeout_seconds {
15269                object.insert("run_timeout_seconds".to_string(), json!(seconds));
15270            }
15271            apply_parallel_group_path(object, &self.parallel_group_path);
15272            ctx.apply_scope_membership(object);
15273            match state.prepare_scalar_cancellation(
15274                cursor,
15275                CancellationCallKind::Child,
15276                &self.parallel_group_path,
15277            ) {
15278                Ok(true) => {
15279                    self.scheduled = true;
15280                    self.matched_pending = true;
15281                    return Poll::Pending;
15282                }
15283                Ok(false) => {}
15284                Err(error) => return Poll::Ready(Err(error)),
15285            }
15286            state.commands.push(command);
15287            self.scheduled = true;
15288        }
15289
15290        Poll::Pending
15291    }
15292}
15293
15294impl Future for ChildWorkflowCall {
15295    type Output = Result<ChildWorkflowResult>;
15296
15297    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15298        match self.poll_avro_value(cx) {
15299            Poll::Ready(Ok(result)) => match result.result.into_json() {
15300                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15301                    parent: result.parent,
15302                    child: result.child,
15303                    child_workflow_type: result.child_workflow_type,
15304                    result: projected,
15305                })),
15306                Err(error) => Poll::Ready(Err(error)),
15307            },
15308            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15309            Poll::Pending => Poll::Pending,
15310        }
15311    }
15312}
15313
15314fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15315    Error::NonDeterministicReplay(ReplayFailure::new(
15316        "recorded_command_mismatch",
15317        Some(recorded.sequence()),
15318        Some(recorded.shape().to_string()),
15319        Some(actual.into()),
15320        "current workflow command does not match the recorded durable command sequence",
15321    ))
15322}
15323
15324pub struct SignalCall {
15325    ctx: WorkflowContext,
15326    signal_name: String,
15327    runtime_reserved_allowed: bool,
15328    opened_wait: bool,
15329    matched_pending: bool,
15330    parallel_group_path: Vec<ParallelGroupMetadata>,
15331}
15332
15333impl SignalCall {
15334    fn poll_avro_value(
15335        mut self: Pin<&mut Self>,
15336        _cx: &mut TaskContext<'_>,
15337    ) -> Poll<Result<Vec<AvroValue>>> {
15338        if self.matched_pending {
15339            return Poll::Pending;
15340        }
15341        if !self.runtime_reserved_allowed {
15342            if let Err(error) = validate_user_signal_name(&self.signal_name) {
15343                return Poll::Ready(Err(error));
15344            }
15345        }
15346
15347        let ctx = self.ctx.clone();
15348        let mut state = match ctx.state.lock() {
15349            Ok(state) => state,
15350            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15351        };
15352
15353        let cursor = state.command_cursor;
15354        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15355            return Poll::Ready(Err(error));
15356        }
15357        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
15358        {
15359            Ok(recorded) => recorded,
15360            Err(error) => return Poll::Ready(Err(error)),
15361        };
15362        if let Some(recorded) = recorded {
15363            match recorded {
15364                RecordedCommand::SignalWait {
15365                    sequence,
15366                    signal_name,
15367                    value,
15368                    parallel_group_path,
15369                } => {
15370                    if let Err(error) = ensure_parallel_path_matches(
15371                        sequence,
15372                        parallel_group_path.as_deref(),
15373                        &self.parallel_group_path,
15374                    ) {
15375                        return Poll::Ready(Err(error));
15376                    }
15377                    if signal_name != self.signal_name {
15378                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15379                            ReplayFailure::new(
15380                                "recorded_command_detail_mismatch",
15381                                Some(sequence),
15382                                Some(format!("signal wait:{signal_name}")),
15383                                Some(format!("signal wait:{}", self.signal_name)),
15384                                "recorded signal name differs from the current workflow command",
15385                            ),
15386                        )));
15387                    }
15388
15389                    if let Err(error) =
15390                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
15391                    {
15392                        return Poll::Ready(Err(error));
15393                    }
15394                    match state.prepare_scalar_cancellation(
15395                        cursor,
15396                        CancellationCallKind::Signal,
15397                        &self.parallel_group_path,
15398                    ) {
15399                        Ok(true) => {
15400                            self.opened_wait = true;
15401                            self.matched_pending = true;
15402                            return Poll::Pending;
15403                        }
15404                        Ok(false) => {}
15405                        Err(error) => return Poll::Ready(Err(error)),
15406                    }
15407                    state.command_cursor += 1;
15408                    if let Some(value) = value {
15409                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15410                        return Poll::Ready(Ok(value));
15411                    }
15412                    if state
15413                        .resume_signal
15414                        .as_ref()
15415                        .is_some_and(|signal| signal.signal_name == self.signal_name)
15416                    {
15417                        let signal = state
15418                            .resume_signal
15419                            .take()
15420                            .expect("matching resume signal is present");
15421                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
15422                        return Poll::Ready(Ok(signal.arguments));
15423                    }
15424
15425                    state.matched_recorded_pending = true;
15426                    self.opened_wait = true;
15427                    self.matched_pending = true;
15428                    return Poll::Pending;
15429                }
15430                other => {
15431                    return Poll::Ready(Err(command_mismatch(
15432                        &other,
15433                        format!("signal wait:{}", self.signal_name),
15434                    )));
15435                }
15436            }
15437        }
15438
15439        match state.prepare_scalar_cancellation(
15440            cursor,
15441            CancellationCallKind::Signal,
15442            &self.parallel_group_path,
15443        ) {
15444            Ok(true) => {
15445                self.opened_wait = true;
15446                self.matched_pending = true;
15447                return Poll::Pending;
15448            }
15449            Ok(false) => {}
15450            Err(error) => return Poll::Ready(Err(error)),
15451        }
15452
15453        if state
15454            .resume_signal
15455            .as_ref()
15456            .is_some_and(|signal| signal.signal_name == self.signal_name)
15457        {
15458            let signal = state
15459                .resume_signal
15460                .take()
15461                .expect("matching resume signal is present");
15462            state.unavailable_cancellation_boundary(&self.parallel_group_path);
15463            return Poll::Ready(Ok(signal.arguments));
15464        }
15465
15466        if !self.opened_wait {
15467            let mut command = serde_json::Map::from_iter([
15468                ("type".to_string(), json!("open_signal_wait")),
15469                ("signal_name".to_string(), json!(self.signal_name)),
15470            ]);
15471            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15472            ctx.apply_scope_membership(&mut command);
15473            state.commands.push(Value::Object(command));
15474            self.opened_wait = true;
15475        }
15476
15477        Poll::Pending
15478    }
15479}
15480
15481impl Future for SignalCall {
15482    type Output = Result<Vec<Value>>;
15483
15484    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15485        match self.poll_avro_value(cx) {
15486            Poll::Ready(Ok(values)) => Poll::Ready(
15487                values
15488                    .into_iter()
15489                    .map(AvroValue::into_json)
15490                    .collect::<Result<Vec<_>>>(),
15491            ),
15492            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15493            Poll::Pending => Poll::Pending,
15494        }
15495    }
15496}
15497
15498#[derive(Clone, Debug)]
15499pub struct ActivityContext {
15500    client: Client,
15501    pub task_id: String,
15502    pub activity_attempt_id: String,
15503    pub lease_owner: String,
15504    pub activity_type: String,
15505    pub attempt_number: u64,
15506    pub task_queue: String,
15507    pub worker_id: String,
15508    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
15509    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
15510    worker_session: Option<WorkerSession>,
15511}
15512
15513impl ActivityContext {
15514    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
15515        if let Some(heartbeats) = &self.local_heartbeats {
15516            return heartbeats
15517                .lock()
15518                .map_err(|_| Error::WorkflowStatePoisoned)?
15519                .record(details);
15520        }
15521        if let Some(guard) = &self.claim_guard {
15522            return guard.heartbeat(self, details).await;
15523        }
15524        if let Some(session) = &self.worker_session {
15525            if !session.active() {
15526                return Err(Error::ActivityExecutionAbandoned(
15527                    "worker-session lease or TTL is no longer active".into(),
15528                ));
15529            }
15530            let result = self
15531                .client
15532                .heartbeat_activity_task_value(
15533                    &self.task_id,
15534                    &self.activity_attempt_id,
15535                    &self.lease_owner,
15536                    details,
15537                )
15538                .await;
15539            return worker_session::settle_activity_heartbeat(
15540                session,
15541                result,
15542                &self.task_id,
15543                &self.activity_attempt_id,
15544                &self.lease_owner,
15545            );
15546        }
15547        self.client
15548            .heartbeat_activity_task(
15549                &self.task_id,
15550                &self.activity_attempt_id,
15551                &self.lease_owner,
15552                details,
15553            )
15554            .await
15555    }
15556}
15557
15558fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
15559    validate_payload_codec(codec)?;
15560    match value {
15561        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
15562            value, codec,
15563        )?)),
15564        None => Ok(AvroValue::Array(Vec::new())),
15565    }
15566}
15567
15568fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
15569    let Some(signal_name) = task
15570        .signal_name
15571        .as_deref()
15572        .filter(|value| !value.is_empty())
15573    else {
15574        return Ok(None);
15575    };
15576    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
15577    let AvroValue::Array(arguments) = decoded else {
15578        unreachable!("normalize_avro_arguments always returns an array");
15579    };
15580
15581    Ok(Some(ResumeSignal {
15582        signal_name: signal_name.to_string(),
15583        arguments,
15584    }))
15585}
15586
15587fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
15588    validate_payload_codec(&task.payload_codec)?;
15589    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
15590    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
15591    for event in &task.history_events {
15592        validate_history_event_payloads(event, &task.payload_codec)?;
15593    }
15594    Ok(())
15595}
15596
15597fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
15598    validate_payload_codec(&task.payload_codec)?;
15599    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
15600}
15601
15602fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
15603    validate_payload_codec(&task.payload_codec)?;
15604    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
15605    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
15606    for event in &task.history_events {
15607        validate_history_event_payloads(event, &task.payload_codec)?;
15608    }
15609
15610    let Some(export) = task.history_export.as_ref() else {
15611        return Ok(());
15612    };
15613    let export_codec = match export.get("payloads") {
15614        Some(payloads) => declared_payload_codec(payloads, "codec")?,
15615        None => None,
15616    }
15617    .unwrap_or(&task.payload_codec);
15618    validate_payload_codec(export_codec)?;
15619
15620    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
15621        for event in events {
15622            let event_type = event
15623                .get("event_type")
15624                .or_else(|| event.get("type"))
15625                .and_then(Value::as_str)
15626                .unwrap_or_default();
15627            if let Some(payload) = event.get("payload") {
15628                validate_history_payloads(event_type, payload, export_codec)?;
15629            }
15630        }
15631    }
15632    for signal in export
15633        .get("signals")
15634        .and_then(Value::as_array)
15635        .into_iter()
15636        .flatten()
15637    {
15638        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
15639        validate_payload_codec(codec)?;
15640        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
15641    }
15642    for activity in export
15643        .get("activities")
15644        .and_then(Value::as_array)
15645        .into_iter()
15646        .flatten()
15647    {
15648        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
15649        validate_payload_codec(codec)?;
15650        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
15651        validate_optional_inbound_payload(activity.get("result"), codec)?;
15652    }
15653    Ok(())
15654}
15655
15656fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
15657    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
15658}
15659
15660fn validate_history_payloads(
15661    event_type: &str,
15662    payload: &Value,
15663    fallback_codec: &str,
15664) -> Result<()> {
15665    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
15666    validate_payload_codec(codec)?;
15667    for field in history_payload_fields(event_type) {
15668        validate_optional_inbound_payload(payload.get(*field), codec)?;
15669    }
15670    Ok(())
15671}
15672
15673const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
15674
15675fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
15676    match event_type {
15677        "ActivityCompleted" => &["result"],
15678        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
15679        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
15680        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
15681        "ChildRunCompleted" => &["result", "output"],
15682        "WorkflowCompleted" => &["output"],
15683        "ServiceCallStarted"
15684        | "ServiceCallCompleted"
15685        | "ServiceCallFailed"
15686        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
15687        _ => &[],
15688    }
15689}
15690
15691fn signal_history_payload(payload: &Value) -> Option<&Value> {
15692    SIGNAL_HISTORY_PAYLOAD_FIELDS
15693        .iter()
15694        .find_map(|field| payload.get(*field))
15695}
15696
15697fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
15698    match value.get(field) {
15699        None => Ok(None),
15700        Some(Value::String(codec)) => Ok(Some(codec)),
15701        Some(_) => Err(invalid_payload_envelope()),
15702    }
15703}
15704
15705fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
15706    validate_payload_codec(codec)?;
15707    if let Some(value) = value.filter(|value| !value.is_null()) {
15708        decode_wire_avro_value(value, codec)?;
15709    }
15710    Ok(())
15711}
15712
15713fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
15714    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
15715        invalid_recorded_history(
15716            "parallel_group_metadata_invalid",
15717            sequence,
15718            "non-empty parallel_group_id",
15719            &payload.to_string(),
15720            "parallel-group history is missing its stable identity",
15721        )
15722    })?;
15723    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
15724        invalid_recorded_history(
15725            "parallel_group_metadata_invalid",
15726            sequence,
15727            "activity, child, timer, signal, condition, or mixed group kind",
15728            &payload.to_string(),
15729            "parallel-group history is missing its group kind",
15730        )
15731    })?;
15732    if !matches!(
15733        kind.as_str(),
15734        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
15735    ) {
15736        return Err(invalid_recorded_history(
15737            "parallel_group_metadata_invalid",
15738            sequence,
15739            "activity, child, timer, signal, condition, or mixed group kind",
15740            &kind,
15741            "parallel-group history contains an unsupported group kind",
15742        ));
15743    }
15744    let base_sequence = payload
15745        .get("parallel_group_base_sequence")
15746        .and_then(value_as_u64)
15747        .filter(|value| *value > 0)
15748        .ok_or_else(|| {
15749            invalid_recorded_history(
15750                "parallel_group_metadata_invalid",
15751                sequence,
15752                "positive parallel_group_base_sequence",
15753                &payload.to_string(),
15754                "parallel-group history contains an invalid base sequence",
15755            )
15756        })?;
15757    let size = payload
15758        .get("parallel_group_size")
15759        .and_then(value_as_u64)
15760        .and_then(|value| usize::try_from(value).ok())
15761        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
15762        .ok_or_else(|| {
15763            invalid_recorded_history(
15764                "parallel_group_metadata_invalid",
15765                sequence,
15766                "bounded positive parallel_group_size",
15767                &payload.to_string(),
15768                "parallel-group history contains an invalid group size",
15769            )
15770        })?;
15771    let index = payload
15772        .get("parallel_group_index")
15773        .and_then(value_as_u64)
15774        .and_then(|value| usize::try_from(value).ok())
15775        .filter(|value| *value < size)
15776        .ok_or_else(|| {
15777            invalid_recorded_history(
15778                "parallel_group_metadata_invalid",
15779                sequence,
15780                "parallel_group_index within group bounds",
15781                &payload.to_string(),
15782                "parallel-group history contains an invalid member index",
15783            )
15784        })?;
15785    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
15786        return Err(invalid_recorded_history(
15787            "parallel_group_metadata_invalid",
15788            sequence,
15789            "base sequence plus member index equals workflow sequence",
15790            &payload.to_string(),
15791            "parallel-group path does not preserve durable workflow position",
15792        ));
15793    }
15794    let mode = payload
15795        .get("parallel_group_mode")
15796        .and_then(Value::as_str)
15797        .unwrap_or("all");
15798    if !matches!(mode, "all" | "select") {
15799        return Err(invalid_recorded_history(
15800            "parallel_group_metadata_invalid",
15801            sequence,
15802            "parallel group mode all or select",
15803            mode,
15804            "parallel-group history contains an unsupported group mode",
15805        ));
15806    }
15807    let expected_id = if mode == "select" {
15808        format!("select-calls:{base_sequence}:{size}")
15809    } else {
15810        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
15811    };
15812    if group_id != expected_id {
15813        return Err(invalid_recorded_history(
15814            "parallel_group_metadata_invalid",
15815            sequence,
15816            &expected_id,
15817            &group_id,
15818            "parallel-group history contains an incompatible stable group ID",
15819        ));
15820    }
15821    let selection_member_key = if mode == "select" {
15822        Some(selection_key_from_value(
15823            payload.get("selection_member_key"),
15824            sequence,
15825        )?)
15826    } else {
15827        None
15828    };
15829    let selection_member_index = if mode == "select" {
15830        Some(required_parallel_usize(
15831            payload,
15832            "selection_member_index",
15833            sequence,
15834        )?)
15835    } else {
15836        None
15837    };
15838    let selection_member_base_sequence = if mode == "select" {
15839        Some(
15840            payload
15841                .get("selection_member_base_sequence")
15842                .and_then(value_as_u64)
15843                .filter(|value| *value >= base_sequence)
15844                .ok_or_else(|| {
15845                    invalid_recorded_history(
15846                        "parallel_group_metadata_invalid",
15847                        sequence,
15848                        "selection member base within its group",
15849                        &payload.to_string(),
15850                        "selection history contains an invalid member base sequence",
15851                    )
15852                })?,
15853        )
15854    } else {
15855        None
15856    };
15857    let selection_member_size = if mode == "select" {
15858        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
15859        if member_size == 0 {
15860            return Err(invalid_recorded_history(
15861                "parallel_group_metadata_invalid",
15862                sequence,
15863                "positive selection member size",
15864                &payload.to_string(),
15865                "selection history contains an invalid member size",
15866            ));
15867        }
15868        Some(member_size)
15869    } else {
15870        None
15871    };
15872    let selection_member_kind = if mode == "select" {
15873        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
15874            invalid_recorded_history(
15875                "parallel_group_metadata_invalid",
15876                sequence,
15877                "selection member operation kind",
15878                &payload.to_string(),
15879                "selection history is missing its authored member kind",
15880            )
15881        })?;
15882        if !matches!(
15883            kind.as_str(),
15884            "activity" | "child" | "timer" | "signal" | "condition" | "group"
15885        ) {
15886            return Err(invalid_recorded_history(
15887                "parallel_group_metadata_invalid",
15888                sequence,
15889                "activity, child, timer, signal, condition, or group selection member kind",
15890                &kind,
15891                "selection history contains an unsupported member kind",
15892            ));
15893        }
15894        Some(kind)
15895    } else {
15896        None
15897    };
15898    if let (Some(member_base), Some(member_size)) =
15899        (selection_member_base_sequence, selection_member_size)
15900    {
15901        let member_end = member_base
15902            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
15903            .ok_or_else(|| {
15904                invalid_recorded_history(
15905                    "parallel_group_metadata_invalid",
15906                    sequence,
15907                    "bounded selection member range",
15908                    &payload.to_string(),
15909                    "selection member range overflowed",
15910                )
15911            })?;
15912        let group_end = base_sequence
15913            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
15914            .unwrap_or(u64::MAX);
15915        if sequence < member_base || sequence >= member_end || member_end > group_end {
15916            return Err(invalid_recorded_history(
15917                "parallel_group_metadata_invalid",
15918                sequence,
15919                "workflow sequence within one bounded selection member",
15920                &payload.to_string(),
15921                "selection member range does not contain its durable leaf",
15922            ));
15923        }
15924    }
15925    Ok(ParallelGroupMetadata {
15926        parallel_group_id: group_id,
15927        parallel_group_kind: kind,
15928        parallel_group_base_sequence: base_sequence,
15929        parallel_group_size: size,
15930        parallel_group_index: index,
15931        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
15932        selection_member_key,
15933        selection_member_index,
15934        selection_member_base_sequence,
15935        selection_member_size,
15936        selection_member_kind,
15937    })
15938}
15939
15940fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
15941    payload
15942        .get(field)
15943        .and_then(value_as_u64)
15944        .and_then(|value| usize::try_from(value).ok())
15945        .ok_or_else(|| {
15946            invalid_recorded_history(
15947                "parallel_group_metadata_invalid",
15948                sequence,
15949                &format!("non-negative integer {field}"),
15950                &payload.to_string(),
15951                "selection history contains invalid member metadata",
15952            )
15953        })
15954}
15955
15956fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15957    match value {
15958        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15959        Some(value) => value_as_u64(value)
15960            .and_then(|value| usize::try_from(value).ok())
15961            .map(SelectionKey::Index)
15962            .ok_or_else(|| {
15963                invalid_recorded_history(
15964                    "selection_member_key_invalid",
15965                    sequence,
15966                    "non-empty string or non-negative integer member key",
15967                    &value.to_string(),
15968                    "selection history contains an invalid member key",
15969                )
15970            }),
15971        None => Err(invalid_recorded_history(
15972            "selection_member_key_missing",
15973            sequence,
15974            "selection_member_key",
15975            "<missing>",
15976            "selection history is missing its stable member key",
15977        )),
15978    }
15979}
15980
15981fn recorded_parallel_group_path(
15982    events: &[&HistoryEvent],
15983    sequence: u64,
15984) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15985    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15986    for event in events {
15987        let payload = &event.payload;
15988        let has_metadata = payload.get("parallel_group_path").is_some()
15989            || payload.get("parallel_group_id").is_some()
15990            || payload.get("parallel_group_kind").is_some()
15991            || payload.get("parallel_group_base_sequence").is_some()
15992            || payload.get("parallel_group_size").is_some()
15993            || payload.get("parallel_group_index").is_some()
15994            || payload.get("parallel_group_mode").is_some()
15995            || payload.get("selection_member_key").is_some();
15996        if !has_metadata {
15997            continue;
15998        }
15999
16000        let top_level = recorded_parallel_group_entry(payload, sequence)?;
16001        let path = match payload.get("parallel_group_path") {
16002            None => vec![top_level.clone()],
16003            Some(Value::Array(entries)) if !entries.is_empty() => entries
16004                .iter()
16005                .map(|entry| recorded_parallel_group_entry(entry, sequence))
16006                .collect::<Result<Vec<_>>>()?,
16007            Some(value) => {
16008                return Err(invalid_recorded_history(
16009                    "parallel_group_metadata_invalid",
16010                    sequence,
16011                    "non-empty parallel_group_path list",
16012                    &value.to_string(),
16013                    "parallel-group history contains an invalid group path",
16014                ));
16015            }
16016        };
16017        if path.last() != Some(&top_level) {
16018            return Err(invalid_recorded_history(
16019                "parallel_group_metadata_invalid",
16020                sequence,
16021                &serde_json::to_string(&path.last()).unwrap_or_default(),
16022                &serde_json::to_string(&top_level).unwrap_or_default(),
16023                "parallel-group top-level fields do not match the innermost path entry",
16024            ));
16025        }
16026        if recorded.as_ref().is_some_and(|existing| existing != &path) {
16027            return Err(invalid_recorded_history(
16028                "parallel_group_history_conflict",
16029                sequence,
16030                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
16031                &serde_json::to_string(&path).unwrap_or_default(),
16032                "parallel-group metadata changed between scheduling and resolution history",
16033            ));
16034        }
16035        recorded = Some(path);
16036    }
16037    Ok(recorded)
16038}
16039
16040fn recorded_commands(
16041    events: &[HistoryEvent],
16042    fallback_codec: &str,
16043    parent: WorkflowIdentity,
16044) -> Result<Vec<RecordedCommand>> {
16045    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
16046    let mut last_new_sequence = None;
16047
16048    for event in events {
16049        let is_activity = matches!(
16050            event.event_type.as_str(),
16051            "ActivityScheduled"
16052                | "ActivityStarted"
16053                | "ActivityHeartbeatRecorded"
16054                | "ActivityRetryScheduled"
16055                | "ActivityCompleted"
16056                | "ActivityFailed"
16057                | "ActivityCancelled"
16058                | "ActivityTimedOut"
16059        );
16060        let is_workflow_timer = matches!(
16061            event.event_type.as_str(),
16062            "TimerScheduled" | "TimerCancelled" | "TimerFired"
16063        ) && !is_internal_timer_event(event);
16064        let is_child_workflow = matches!(
16065            event.event_type.as_str(),
16066            "ChildWorkflowScheduled"
16067                | "ChildRunStarted"
16068                | "ChildRunCompleted"
16069                | "ChildRunFailed"
16070                | "ChildRunCancelled"
16071                | "ChildRunTerminated"
16072        );
16073        let is_signal_wait = is_recorded_signal_wait_event(event);
16074        let is_condition_wait = is_recorded_condition_wait_event(event);
16075        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
16076        let is_side_effect = event.event_type == "SideEffectRecorded";
16077        let is_version_marker = event.event_type == "VersionMarkerRecorded";
16078        let is_memo = event.event_type == "MemoUpserted";
16079        let is_service_operation = nexus::is_service_event(event);
16080        if !is_activity
16081            && !is_workflow_timer
16082            && !is_child_workflow
16083            && !is_signal_wait
16084            && !is_condition_wait
16085            && !is_search_attributes
16086            && !is_side_effect
16087            && !is_version_marker
16088            && !is_memo
16089            && !is_service_operation
16090        {
16091            continue;
16092        }
16093
16094        let sequence = durable_event_sequence(event).ok_or_else(|| {
16095            Error::NonDeterministicReplay(ReplayFailure::new(
16096                "durable_command_sequence_missing",
16097                None,
16098                Some("positive workflow sequence".to_string()),
16099                Some(event.event_type.clone()),
16100                "durable command history event has no workflow sequence",
16101            ))
16102        })?;
16103        if sequence == 0 {
16104            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16105                "durable_command_sequence_invalid",
16106                Some(sequence),
16107                Some("positive workflow sequence".to_string()),
16108                Some(sequence.to_string()),
16109                "durable command history uses an invalid workflow sequence",
16110            )));
16111        }
16112        if !events_by_sequence.contains_key(&sequence) {
16113            if let Some(previous) = last_new_sequence {
16114                if sequence < previous {
16115                    return Err(invalid_recorded_history(
16116                        "durable_command_sequence_mismatch",
16117                        sequence,
16118                        &format!("workflow sequence greater than {previous}"),
16119                        &sequence.to_string(),
16120                        "durable commands are not strictly ordered by their recorded workflow sequence",
16121                    ));
16122                }
16123            }
16124            last_new_sequence = Some(sequence);
16125        }
16126        events_by_sequence.entry(sequence).or_default().push(event);
16127    }
16128
16129    let commands: Vec<RecordedCommand> = events_by_sequence
16130        .into_iter()
16131        .map(|(sequence, sequence_events)| {
16132            let activity_events: Vec<_> = sequence_events
16133                .iter()
16134                .copied()
16135                .filter(|event| event.event_type.starts_with("Activity"))
16136                .collect();
16137            let timer_events: Vec<_> = sequence_events
16138                .iter()
16139                .copied()
16140                .filter(|event| event.event_type.starts_with("Timer"))
16141                .collect();
16142            let child_events: Vec<_> = sequence_events
16143                .iter()
16144                .copied()
16145                .filter(|event| {
16146                    event.event_type == "ChildWorkflowScheduled"
16147                        || event.event_type.starts_with("ChildRun")
16148                })
16149                .collect();
16150            let signal_wait_events: Vec<_> = sequence_events
16151                .iter()
16152                .copied()
16153                .filter(|event| is_recorded_signal_wait_event(event))
16154                .collect();
16155            let condition_wait_events: Vec<_> = sequence_events
16156                .iter()
16157                .copied()
16158                .filter(|event| is_recorded_condition_wait_event(event))
16159                .collect();
16160            let search_attribute_events: Vec<_> = sequence_events
16161                .iter()
16162                .copied()
16163                .filter(|event| event.event_type == "SearchAttributesUpserted")
16164                .collect();
16165            let side_effect_events: Vec<_> = sequence_events
16166                .iter()
16167                .copied()
16168                .filter(|event| event.event_type == "SideEffectRecorded")
16169                .collect();
16170            let version_marker_events: Vec<_> = sequence_events
16171                .iter()
16172                .copied()
16173                .filter(|event| event.event_type == "VersionMarkerRecorded")
16174                .collect();
16175            let memo_events: Vec<_> = sequence_events
16176                .iter()
16177                .copied()
16178                .filter(|event| event.event_type == "MemoUpserted")
16179                .collect();
16180            let service_events: Vec<_> = sequence_events.iter().copied()
16181                .filter(|event| nexus::is_service_event(event)).collect();
16182
16183            let command_kind_count = usize::from(!activity_events.is_empty())
16184                + usize::from(!timer_events.is_empty())
16185                + usize::from(!child_events.is_empty())
16186                + usize::from(!signal_wait_events.is_empty())
16187                + usize::from(!condition_wait_events.is_empty())
16188                + usize::from(!search_attribute_events.is_empty())
16189                + usize::from(!side_effect_events.is_empty())
16190                + usize::from(!version_marker_events.is_empty())
16191                + usize::from(!memo_events.is_empty())
16192                + usize::from(!service_events.is_empty());
16193            if command_kind_count > 1 {
16194                let actual = [
16195                    (!activity_events.is_empty()).then_some("activity"),
16196                    (!timer_events.is_empty()).then_some("timer"),
16197                    (!child_events.is_empty()).then_some("child workflow"),
16198                    (!signal_wait_events.is_empty()).then_some("signal wait"),
16199                    (!condition_wait_events.is_empty()).then_some("condition wait"),
16200                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
16201                    (!side_effect_events.is_empty()).then_some("side effect"),
16202                    (!version_marker_events.is_empty()).then_some("version marker"),
16203                    (!memo_events.is_empty()).then_some("memo upsert"),
16204                    (!service_events.is_empty()).then_some("service operation"),
16205                ]
16206                .into_iter()
16207                .flatten()
16208                .collect::<Vec<_>>()
16209                .join(" and ");
16210                return Err(invalid_recorded_history(
16211                    "durable_command_sequence_collision",
16212                    sequence,
16213                    "one durable command kind",
16214                    &actual,
16215                    "one workflow sequence records more than one durable command kind",
16216                ));
16217            }
16218
16219            if !service_events.is_empty() {
16220                return Ok(RecordedCommand::ServiceOperation {
16221                    sequence, call: nexus::recorded_call(&service_events, sequence, fallback_codec, &parent)?,
16222                });
16223            }
16224
16225            if !activity_events.is_empty() {
16226                let parallel_group_path =
16227                    recorded_parallel_group_path(&activity_events, sequence)?;
16228                let scheduled_count = activity_events
16229                    .iter()
16230                    .filter(|event| event.event_type == "ActivityScheduled")
16231                    .count();
16232                if scheduled_count > 1 {
16233                    return Err(invalid_recorded_history(
16234                        "duplicate_activity_schedule",
16235                        sequence,
16236                        "at most one ActivityScheduled event",
16237                        "multiple ActivityScheduled events",
16238                        "activity history schedules more than one command at one workflow sequence",
16239                    ));
16240                }
16241                let activity_type = activity_events.iter().find_map(|event| {
16242                    event
16243                        .payload
16244                        .get("activity_type")
16245                        .or_else(|| event.payload.get("activity_name"))
16246                        .and_then(Value::as_str)
16247                        .map(str::to_string)
16248                });
16249                if activity_events.iter().filter_map(|event| {
16250                    event
16251                        .payload
16252                        .get("activity_type")
16253                        .or_else(|| event.payload.get("activity_name"))
16254                        .and_then(Value::as_str)
16255                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
16256                    return Err(invalid_recorded_history(
16257                        "activity_identity_mismatch",
16258                        sequence,
16259                        activity_type.as_deref().unwrap_or("one activity identity"),
16260                        "conflicting activity identities",
16261                        "activity lifecycle events at one workflow sequence disagree on identity",
16262                    ));
16263                }
16264                let terminal: Vec<_> = activity_events
16265                    .iter()
16266                    .copied()
16267                    .filter(|event| {
16268                        matches!(
16269                            event.event_type.as_str(),
16270                            "ActivityCompleted"
16271                                | "ActivityFailed"
16272                                | "ActivityCancelled"
16273                                | "ActivityTimedOut"
16274                        )
16275                    })
16276                    .collect();
16277                let duplicate_delivery = terminal.first().is_some_and(|first| {
16278                    terminal.iter().all(|event| {
16279                        event.event_type == first.event_type && event.payload == first.payload
16280                    })
16281                });
16282                if terminal.len() > 1 && !duplicate_delivery {
16283                    return Err(invalid_recorded_history(
16284                        "duplicate_activity_terminal_event",
16285                        sequence,
16286                        "at most one terminal activity event",
16287                        "multiple terminal activity events",
16288                        "activity history settles one command more than once",
16289                    ));
16290                }
16291                let outcome = terminal
16292                    .first()
16293                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
16294                    .transpose()?;
16295                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
16296                let activity_snapshot = activity_events
16297                    .iter()
16298                    .find(|event| event.event_type == "ActivityScheduled")
16299                    .and_then(|event| event.payload.get("activity"))
16300                    .and_then(Value::as_object);
16301                let options = Some(match activity_snapshot {
16302                    Some(activity) => RecordedActivityOptions {
16303                        task_queue: recorded_optional_string(activity, "queue"),
16304                        execution_mode,
16305                        retry_policy: recorded_activity_retry_snapshot(
16306                            activity.get("retry_policy"),
16307                        ),
16308                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16309                    },
16310                    None => RecordedActivityOptions {
16311                        task_queue: RecordedSnapshotValue::Unknown,
16312                        execution_mode,
16313                        retry_policy: recorded_activity_retry_snapshot(None),
16314                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16315                    },
16316                });
16317                return Ok(RecordedCommand::Activity {
16318                    sequence,
16319                    activity_type,
16320                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
16321                    options,
16322                    outcome,
16323                    parallel_group_path,
16324                });
16325            }
16326
16327            if !child_events.is_empty() {
16328                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
16329                let scheduled: Vec<_> = child_events
16330                    .iter()
16331                    .copied()
16332                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
16333                    .collect();
16334                if scheduled.len() != 1 {
16335                    return Err(invalid_recorded_history(
16336                        "child_workflow_schedule_missing_or_duplicate",
16337                        sequence,
16338                        "one ChildWorkflowScheduled event",
16339                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
16340                        "child workflow replay requires exactly one recorded schedule event",
16341                    ));
16342                }
16343                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
16344                let workflow_type = child_events.iter().find_map(|event| {
16345                    event
16346                        .payload
16347                        .get("child_workflow_type")
16348                        .or_else(|| event.payload.get("workflow_type"))
16349                        .and_then(Value::as_str)
16350                        .filter(|value| !value.is_empty())
16351                        .map(str::to_string)
16352                });
16353                if child_events
16354                    .iter()
16355                    .filter_map(|event| {
16356                        event
16357                            .payload
16358                            .get("child_workflow_type")
16359                            .or_else(|| event.payload.get("workflow_type"))
16360                            .and_then(Value::as_str)
16361                    })
16362                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
16363                {
16364                    return Err(invalid_recorded_history(
16365                        "child_workflow_identity_mismatch",
16366                        sequence,
16367                        workflow_type
16368                            .as_deref()
16369                            .unwrap_or("one child workflow type"),
16370                        "conflicting child workflow types",
16371                        "child workflow lifecycle events at one sequence disagree on type",
16372                    ));
16373                }
16374                let mut outcomes = child_workflow_outcomes(
16375                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
16376                    fallback_codec,
16377                    parent.clone(),
16378                )?;
16379                let terminal_events = child_events
16380                    .iter()
16381                    .copied()
16382                    .filter(|event| event.event_type.starts_with("ChildRun"))
16383                    .collect::<Vec<_>>();
16384                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
16385                    terminal_events.iter().all(|event| {
16386                        event.event_type == first.event_type && event.payload == first.payload
16387                    })
16388                });
16389                if outcomes.len() > 1 && !duplicate_delivery {
16390                    return Err(invalid_recorded_history(
16391                        "duplicate_child_workflow_terminal_event",
16392                        sequence,
16393                        "at most one terminal child event",
16394                        "multiple terminal child events",
16395                        "child workflow history settles one command more than once",
16396                    ));
16397                }
16398                return Ok(RecordedCommand::ChildWorkflow {
16399                    sequence,
16400                    workflow_type,
16401                    policies,
16402                    outcome: outcomes.pop(),
16403                    parallel_group_path,
16404                });
16405            }
16406
16407            if !signal_wait_events.is_empty() {
16408                let opened: Vec<_> = signal_wait_events
16409                    .iter()
16410                    .copied()
16411                    .filter(|event| event.event_type == "SignalWaitOpened")
16412                    .collect();
16413                if opened.len() != 1 {
16414                    return Err(invalid_recorded_history(
16415                        "signal_wait_open_missing_or_duplicate",
16416                        sequence,
16417                        "one SignalWaitOpened event",
16418                        &format!("{} SignalWaitOpened events", opened.len()),
16419                        "signal replay requires exactly one canonical wait-open event",
16420                    ));
16421                }
16422
16423                let applied: Vec<_> = signal_wait_events
16424                    .iter()
16425                    .copied()
16426                    .filter(|event| event.event_type == "SignalApplied")
16427                    .collect();
16428                if applied.len() > 1 {
16429                    return Err(invalid_recorded_history(
16430                        "duplicate_signal_wait_apply",
16431                        sequence,
16432                        "at most one SignalApplied event",
16433                        "multiple SignalApplied events",
16434                        "signal history applies one durable wait more than once",
16435                    ));
16436                }
16437
16438                let signal_names = signal_wait_events
16439                    .iter()
16440                    .map(|event| required_signal_wait_name(event, sequence))
16441                    .collect::<Result<Vec<_>>>()?;
16442                let signal_name = signal_names
16443                    .first()
16444                    .expect("signal wait events are not empty")
16445                    .clone();
16446                if signal_names.iter().any(|candidate| candidate != &signal_name) {
16447                    return Err(invalid_recorded_history(
16448                        "signal_wait_identity_mismatch",
16449                        sequence,
16450                        &signal_name,
16451                        "conflicting signal names",
16452                        "signal wait lifecycle events at one workflow sequence disagree on identity",
16453                    ));
16454                }
16455                let value = applied
16456                    .first()
16457                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
16458                    .transpose()?;
16459                return Ok(RecordedCommand::SignalWait {
16460                    sequence,
16461                    signal_name,
16462                    value,
16463                    parallel_group_path: recorded_parallel_group_path(
16464                        &signal_wait_events,
16465                        sequence,
16466                    )?,
16467                });
16468            }
16469
16470            if !condition_wait_events.is_empty() {
16471                return recorded_condition_wait(
16472                    sequence,
16473                    &condition_wait_events,
16474                    events,
16475                );
16476            }
16477
16478            if !search_attribute_events.is_empty() {
16479                if search_attribute_events.len() != 1 {
16480                    return Err(invalid_recorded_history(
16481                        "duplicate_search_attribute_update",
16482                        sequence,
16483                        "one SearchAttributesUpserted event",
16484                        &format!(
16485                            "{} SearchAttributesUpserted events",
16486                            search_attribute_events.len()
16487                        ),
16488                        "search-attribute history records one workflow command more than once",
16489                    ));
16490                }
16491                let payload = &search_attribute_events[0].payload;
16492                let attributes = payload
16493                    .get("attributes")
16494                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
16495                    .cloned()
16496                    .ok_or_else(|| {
16497                        invalid_recorded_history(
16498                            "search_attribute_update_missing",
16499                            sequence,
16500                            "non-empty attributes object",
16501                            "missing or invalid attributes",
16502                            "search-attribute history is missing its recorded mutation",
16503                        )
16504                    })?;
16505                let attribute_types =
16506                    recorded_search_attribute_types(payload, &attributes, sequence)?;
16507                return Ok(RecordedCommand::SearchAttributes {
16508                    sequence,
16509                    attributes,
16510                    attribute_types,
16511                });
16512            }
16513
16514            if !side_effect_events.is_empty() {
16515                if side_effect_events.len() != 1 {
16516                    return Err(invalid_recorded_history(
16517                        "duplicate_side_effect_record",
16518                        sequence,
16519                        "one SideEffectRecorded event",
16520                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
16521                        "side-effect history records one workflow command more than once",
16522                    ));
16523                }
16524                let event = side_effect_events[0];
16525                let result = event.payload.get("result").ok_or_else(|| {
16526                    invalid_recorded_history(
16527                        "side_effect_result_missing",
16528                        sequence,
16529                        "recorded result payload",
16530                        "missing result",
16531                        "side-effect history is missing its recorded value",
16532                    )
16533                })?;
16534                let has_published_envelope = result.as_str().is_some()
16535                    || result.as_object().is_some_and(|envelope| {
16536                        envelope.get("codec").and_then(Value::as_str).is_some()
16537                            && envelope.get("blob").and_then(Value::as_str).is_some()
16538                    });
16539                if !has_published_envelope {
16540                    return Err(invalid_recorded_history(
16541                        "side_effect_payload_malformed",
16542                        sequence,
16543                        "payload blob or {codec, blob} envelope",
16544                        &result.to_string(),
16545                        "side-effect history result does not use a published payload envelope",
16546                    ));
16547                }
16548                let codec = event
16549                    .payload
16550                    .get("payload_codec")
16551                    .and_then(Value::as_str)
16552                    .unwrap_or(fallback_codec);
16553                let value = decode_wire_avro_value(result, codec).map_err(|error| {
16554                    if error.to_string().contains("unsupported_payload_codec") {
16555                        return error;
16556                    }
16557
16558                    invalid_recorded_history(
16559                        "side_effect_payload_incompatible",
16560                        sequence,
16561                        &format!("valid {codec} payload envelope"),
16562                        &error.to_string(),
16563                        "side-effect history payload cannot be decoded with its recorded codec",
16564                    )
16565                })?;
16566                return Ok(RecordedCommand::SideEffect { sequence, value });
16567            }
16568
16569            if !version_marker_events.is_empty() {
16570                if version_marker_events.len() != 1 {
16571                    return Err(invalid_recorded_history(
16572                        "duplicate_version_marker_record",
16573                        sequence,
16574                        "one VersionMarkerRecorded event",
16575                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
16576                        "version-marker history records one workflow command more than once",
16577                    ));
16578                }
16579                let payload = &version_marker_events[0].payload;
16580                let change_id = payload
16581                    .get("change_id")
16582                    .and_then(Value::as_str)
16583                    .filter(|value| !value.is_empty())
16584                    .map(str::to_string)
16585                    .ok_or_else(|| {
16586                        invalid_recorded_history(
16587                            "version_marker_field_missing",
16588                            sequence,
16589                            "non-empty change_id",
16590                            "missing or invalid change_id",
16591                            "version-marker history is missing its stable change ID",
16592                        )
16593                    })?;
16594                let version = required_version_i32(payload, "version", sequence)?;
16595                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
16596                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
16597                if min_supported > max_supported || version < min_supported || version > max_supported {
16598                    return Err(invalid_recorded_history(
16599                        "version_marker_history_range_invalid",
16600                        sequence,
16601                        "min_supported <= version <= max_supported",
16602                        &format!("{min_supported} <= {version} <= {max_supported}"),
16603                        "recorded version marker contains an internally incompatible range",
16604                    ));
16605                }
16606                return Ok(RecordedCommand::VersionMarker {
16607                    sequence,
16608                    change_id,
16609                    version,
16610                });
16611            }
16612
16613            if !memo_events.is_empty() {
16614                if memo_events.len() != 1 {
16615                    return Err(invalid_recorded_history(
16616                        "duplicate_memo_upsert_record",
16617                        sequence,
16618                        "one MemoUpserted event",
16619                        &format!("{} MemoUpserted events", memo_events.len()),
16620                        "memo history records one workflow update more than once",
16621                    ));
16622                }
16623                let payload = &memo_events[0].payload;
16624                let entries = payload.get("entries").cloned().ok_or_else(|| {
16625                    invalid_recorded_history(
16626                        "memo_entries_missing",
16627                        sequence,
16628                        "memo entries object",
16629                        "missing entries",
16630                        "MemoUpserted history is missing replay identity entries",
16631                    )
16632                })?;
16633                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
16634                    invalid_recorded_history(
16635                        "memo_entries_invalid",
16636                        sequence,
16637                        "valid canonical memo entries",
16638                        &error.to_string(),
16639                        "MemoUpserted history contains invalid replay identity entries",
16640                    )
16641                })?;
16642                let merged = payload.get("merged").cloned().ok_or_else(|| {
16643                    invalid_recorded_history(
16644                        "memo_merged_projection_missing",
16645                        sequence,
16646                        "merged memo projection",
16647                        "missing merged",
16648                        "MemoUpserted history is missing its merged projection",
16649                    )
16650                })?;
16651                decode_memo_history_map(&merged, false).map_err(|error| {
16652                    invalid_recorded_history(
16653                        "memo_merged_projection_invalid",
16654                        sequence,
16655                        "valid merged memo projection",
16656                        &error.to_string(),
16657                        "MemoUpserted history contains an invalid merged projection",
16658                    )
16659                })?;
16660
16661                return Ok(RecordedCommand::Memo { sequence, entries });
16662            }
16663            let scheduled: Vec<_> = timer_events
16664                .iter()
16665                .copied()
16666                .filter(|event| event.event_type == "TimerScheduled")
16667                .collect();
16668            let fired: Vec<_> = timer_events
16669                .iter()
16670                .copied()
16671                .filter(|event| event.event_type == "TimerFired")
16672                .collect();
16673            if scheduled.len() != 1 {
16674                return Err(invalid_recorded_history(
16675                    "timer_schedule_missing_or_duplicate",
16676                    sequence,
16677                    "one TimerScheduled event",
16678                    &format!("{} TimerScheduled events", scheduled.len()),
16679                    "timer replay requires exactly one recorded schedule event",
16680                ));
16681            }
16682            if fired.len() > 1 {
16683                return Err(invalid_recorded_history(
16684                    "duplicate_timer_fire",
16685                    sequence,
16686                    "at most one TimerFired event",
16687                    "multiple TimerFired events",
16688                    "timer history contains more than one fire event for a workflow sequence",
16689                ));
16690            }
16691
16692            let scheduled = scheduled[0];
16693            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16694            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16695            if let Some(fired) = fired.first() {
16696                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16697                if fired_timer_id != timer_id {
16698                    return Err(invalid_recorded_history(
16699                        "timer_identity_mismatch",
16700                        sequence,
16701                        &timer_id,
16702                        &fired_timer_id,
16703                        "TimerFired does not correspond to the recorded TimerScheduled event",
16704                    ));
16705                }
16706                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16707                if fired_delay != delay_seconds {
16708                    return Err(invalid_recorded_history(
16709                        "timer_history_delay_mismatch",
16710                        sequence,
16711                        &delay_seconds.to_string(),
16712                        &fired_delay.to_string(),
16713                        "TimerScheduled and TimerFired record different delays",
16714                    ));
16715                }
16716            }
16717
16718            Ok(RecordedCommand::Timer {
16719                sequence,
16720                delay_seconds,
16721                fired: !fired.is_empty(),
16722                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
16723            })
16724        })
16725        .collect::<Result<_>>()?;
16726
16727    let mut marker_decisions = HashMap::new();
16728    for command in &commands {
16729        if let RecordedCommand::VersionMarker {
16730            sequence,
16731            change_id,
16732            version,
16733        } = command
16734        {
16735            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
16736                if version != first_version {
16737                    return Err(invalid_recorded_history(
16738                        "version_marker_conflict",
16739                        *sequence,
16740                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
16741                        &format!("version {version} at sequence {sequence}"),
16742                        "workflow history contains conflicting decisions for one stable change ID",
16743                    ));
16744                }
16745            } else {
16746                marker_decisions.insert(change_id.clone(), (*version, *sequence));
16747            }
16748        }
16749    }
16750
16751    Ok(commands)
16752}
16753
16754fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
16755    payload
16756        .get(field)
16757        .and_then(Value::as_i64)
16758        .and_then(|value| i32::try_from(value).ok())
16759        .ok_or_else(|| {
16760            invalid_recorded_history(
16761                "version_marker_field_missing",
16762                sequence,
16763                &format!("integer {field}"),
16764                "missing or out-of-range integer",
16765                "version-marker history is missing a required integer field",
16766            )
16767        })
16768}
16769
16770fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
16771    event
16772        .payload
16773        .get("sequence")
16774        .or_else(|| event.payload.get("workflow_sequence"))
16775        .or_else(|| event.raw.get("sequence"))
16776        .or_else(|| event.raw.get("workflow_sequence"))
16777        .and_then(value_as_u64)
16778}
16779
16780fn is_internal_timer_event(event: &HistoryEvent) -> bool {
16781    matches!(
16782        event
16783            .payload
16784            .get("timer_kind")
16785            .or_else(|| event.raw.get("timer_kind"))
16786            .and_then(Value::as_str),
16787        Some("condition_timeout" | "signal_timeout")
16788    )
16789}
16790
16791fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
16792    matches!(
16793        event.event_type.as_str(),
16794        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16795    )
16796}
16797
16798fn recorded_condition_wait(
16799    sequence: u64,
16800    condition_events: &[&HistoryEvent],
16801    all_events: &[HistoryEvent],
16802) -> Result<RecordedCommand> {
16803    let opened = condition_events
16804        .iter()
16805        .copied()
16806        .filter(|event| event.event_type == "ConditionWaitOpened")
16807        .collect::<Vec<_>>();
16808    if opened.len() != 1 {
16809        return Err(invalid_recorded_history(
16810            "condition_wait_open_missing_or_duplicate",
16811            sequence,
16812            "one ConditionWaitOpened event",
16813            &format!("{} ConditionWaitOpened events", opened.len()),
16814            "condition replay requires exactly one canonical wait-open event",
16815        ));
16816    }
16817    let terminal = condition_events
16818        .iter()
16819        .copied()
16820        .filter(|event| {
16821            matches!(
16822                event.event_type.as_str(),
16823                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16824            )
16825        })
16826        .collect::<Vec<_>>();
16827    if terminal.len() > 1 {
16828        return Err(invalid_recorded_history(
16829            "duplicate_condition_wait_terminal_event",
16830            sequence,
16831            "at most one condition terminal event",
16832            "multiple condition terminal events",
16833            "condition history settles one durable wait more than once",
16834        ));
16835    }
16836
16837    let opened = opened[0];
16838    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
16839    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
16840    for event in condition_events
16841        .iter()
16842        .copied()
16843        .filter(|event| !std::ptr::eq(*event, opened))
16844    {
16845        let event_wait_id = required_condition_wait_id(event, sequence)?;
16846        if event_wait_id != condition_wait_id {
16847            return Err(invalid_recorded_history(
16848                "condition_wait_id_mismatch",
16849                sequence,
16850                &condition_wait_id,
16851                &event_wait_id,
16852                "condition lifecycle events at one sequence disagree on wait identity",
16853            ));
16854        }
16855        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
16856        if event_occurrence_id != occurrence_id {
16857            return Err(invalid_recorded_history(
16858                "condition_wait_occurrence_history_mismatch",
16859                sequence,
16860                &occurrence_id,
16861                &event_occurrence_id,
16862                "condition lifecycle events at one sequence disagree on authored occurrence identity",
16863            ));
16864        }
16865    }
16866
16867    let condition_key = optional_non_empty_history_string(opened, "condition_key");
16868    let predicate_identity = opened
16869        .payload
16870        .get("condition_definition_fingerprint")
16871        .and_then(Value::as_str)
16872        .filter(|value| !value.is_empty())
16873        .map(str::to_string)
16874        .ok_or_else(|| {
16875            invalid_recorded_history(
16876                "condition_wait_predicate_fingerprint_missing",
16877                sequence,
16878                "non-empty condition_definition_fingerprint",
16879                &opened.event_type,
16880                "canonical condition history is missing its predicate identity",
16881            )
16882        })?;
16883    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
16884    for event in condition_events
16885        .iter()
16886        .copied()
16887        .filter(|event| !std::ptr::eq(*event, opened))
16888    {
16889        for (field, opened_value) in [
16890            ("condition_key", condition_key.as_deref()),
16891            (
16892                "condition_definition_fingerprint",
16893                Some(predicate_identity.as_str()),
16894            ),
16895        ] {
16896            if let Some(value) = optional_non_empty_history_string(event, field) {
16897                if opened_value.is_some_and(|opened_value| opened_value != value) {
16898                    return Err(invalid_recorded_history(
16899                        "condition_wait_definition_history_mismatch",
16900                        sequence,
16901                        opened_value.unwrap_or_default(),
16902                        &value,
16903                        "condition lifecycle events disagree on the recorded definition",
16904                    ));
16905                }
16906            }
16907        }
16908        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
16909            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
16910                return Err(invalid_recorded_history(
16911                    "condition_wait_definition_history_mismatch",
16912                    sequence,
16913                    &format!("{}s", timeout_seconds.unwrap_or_default()),
16914                    &format!("{event_timeout}s"),
16915                    "condition lifecycle events disagree on the recorded timeout",
16916                ));
16917            }
16918        }
16919    }
16920
16921    let timeout_timer_events = all_events
16922        .iter()
16923        .filter(|event| {
16924            matches!(
16925                event.event_type.as_str(),
16926                "TimerScheduled" | "TimerCancelled" | "TimerFired"
16927            ) && event.payload.get("timer_kind").and_then(Value::as_str)
16928                == Some("condition_timeout")
16929                && event
16930                    .payload
16931                    .get("condition_wait_id")
16932                    .and_then(Value::as_str)
16933                    == Some(condition_wait_id.as_str())
16934        })
16935        .collect::<Vec<_>>();
16936    let scheduled = timeout_timer_events
16937        .iter()
16938        .copied()
16939        .filter(|event| event.event_type == "TimerScheduled")
16940        .collect::<Vec<_>>();
16941    let fired = timeout_timer_events
16942        .iter()
16943        .copied()
16944        .filter(|event| event.event_type == "TimerFired")
16945        .collect::<Vec<_>>();
16946    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
16947        return Err(invalid_recorded_history(
16948            "condition_wait_timeout_history_invalid",
16949            sequence,
16950            "one timeout schedule and at most one fire",
16951            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
16952            "condition timeout history has a missing or duplicate lifecycle event",
16953        ));
16954    }
16955    if let Some(scheduled) = scheduled.first() {
16956        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16957        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16958        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
16959            return Err(invalid_recorded_history(
16960                "condition_wait_timeout_delay_mismatch",
16961                sequence,
16962                &format!("{}s", timeout_seconds.unwrap_or_default()),
16963                &format!("{delay_seconds}s"),
16964                "condition timeout timer differs from the wait definition",
16965            ));
16966        }
16967        if let Some(fired) = fired.first() {
16968            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16969            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16970            if fired_timer_id != timer_id || fired_delay != delay_seconds {
16971                return Err(invalid_recorded_history(
16972                    "condition_wait_timeout_identity_mismatch",
16973                    sequence,
16974                    &format!("{timer_id}:{delay_seconds}s"),
16975                    &format!("{fired_timer_id}:{fired_delay}s"),
16976                    "condition timeout fire does not match its durable schedule",
16977                ));
16978            }
16979        }
16980    }
16981
16982    let result = terminal.first().map(|event| {
16983        if event.event_type == "ConditionWaitTimedOut" {
16984            ConditionWaitResult::TimedOut
16985        } else {
16986            ConditionWaitResult::Satisfied
16987        }
16988    });
16989    let result = if !fired.is_empty() {
16990        if result == Some(ConditionWaitResult::Satisfied) {
16991            return Err(invalid_recorded_history(
16992                "condition_wait_terminal_conflict",
16993                sequence,
16994                "one satisfied or timed-out outcome",
16995                "satisfied event and fired timeout",
16996                "condition history records conflicting terminal outcomes",
16997            ));
16998        }
16999        Some(ConditionWaitResult::TimedOut)
17000    } else {
17001        result
17002    };
17003
17004    Ok(RecordedCommand::ConditionWait {
17005        sequence,
17006        occurrence_id,
17007        condition_key,
17008        predicate_identity,
17009        timeout_seconds,
17010        result,
17011        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
17012    })
17013}
17014
17015fn recorded_condition_group_path(
17016    condition_events: &[&HistoryEvent],
17017    all_events: &[HistoryEvent],
17018    sequence: u64,
17019) -> Result<Option<Vec<ParallelGroupMetadata>>> {
17020    let opened = condition_events
17021        .iter()
17022        .copied()
17023        .find(|event| event.event_type == "ConditionWaitOpened")
17024        .expect("canonical condition opener is validated first");
17025    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
17026    let previous_events = all_events
17027        .iter()
17028        .take_while(|event| !std::ptr::eq(*event, opened))
17029        .collect::<Vec<_>>();
17030    let originals = previous_events
17031        .iter()
17032        .copied()
17033        .filter(|event| event.event_type == "ConditionWaitOpened")
17034        .filter(|event| {
17035            event
17036                .payload
17037                .get("condition_wait_occurrence_id")
17038                .and_then(Value::as_str)
17039                == Some(occurrence.as_str())
17040        })
17041        .collect::<Vec<_>>();
17042    let Some(original) = originals.first().copied() else {
17043        return recorded_parallel_group_path(condition_events, sequence);
17044    };
17045    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
17046    if authored_sequence == sequence {
17047        return recorded_parallel_group_path(condition_events, sequence);
17048    }
17049    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
17050    if original_path.is_none() {
17051        return recorded_parallel_group_path(condition_events, sequence);
17052    }
17053    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
17054    let identity_matches = [
17055        "condition_key",
17056        "condition_definition_fingerprint",
17057        "timeout_seconds",
17058    ]
17059    .iter()
17060    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
17061    let previous = originals
17062        .iter()
17063        .copied()
17064        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
17065        .max_by_key(|event| durable_event_sequence(event));
17066    let previously_satisfied = previous.is_some_and(|previous| {
17067        previous_events.iter().any(|event| {
17068            event.event_type == "ConditionWaitSatisfied"
17069                && event.payload.get("condition_wait_id")
17070                    == previous.payload.get("condition_wait_id")
17071                && event.payload.get("condition_wait_occurrence_id")
17072                    == previous.payload.get("condition_wait_occurrence_id")
17073                && durable_event_sequence(event) == durable_event_sequence(previous)
17074        })
17075    });
17076    if !identity_matches || reopened_path != original_path || !previously_satisfied {
17077        return Err(invalid_recorded_history(
17078            "condition_wait_group_reopen_mismatch",
17079            sequence,
17080            "same authored condition and group path after a satisfied physical wait",
17081            &opened.payload.to_string(),
17082            "grouped condition reopen has no matching recorded predecessor",
17083        ));
17084    }
17085    Ok(reopened_path)
17086}
17087
17088fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17089    event
17090        .payload
17091        .get("condition_wait_occurrence_id")
17092        .and_then(Value::as_str)
17093        .filter(|value| !value.is_empty())
17094        .map(str::to_string)
17095        .ok_or_else(|| {
17096            invalid_recorded_history(
17097                "condition_wait_occurrence_id_missing",
17098                sequence,
17099                "non-empty condition_wait_occurrence_id",
17100                &event.event_type,
17101                "condition history is missing authored occurrence identity",
17102            )
17103        })
17104}
17105
17106fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17107    event
17108        .payload
17109        .get("condition_wait_id")
17110        .and_then(Value::as_str)
17111        .filter(|value| !value.is_empty())
17112        .map(str::to_string)
17113        .ok_or_else(|| {
17114            invalid_recorded_history(
17115                "condition_wait_id_missing",
17116                sequence,
17117                "non-empty condition_wait_id",
17118                &event.event_type,
17119                "canonical condition history is missing its durable wait identity",
17120            )
17121        })
17122}
17123
17124fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
17125    event
17126        .payload
17127        .get(field)
17128        .and_then(Value::as_str)
17129        .filter(|value| !value.is_empty())
17130        .map(str::to_string)
17131}
17132
17133fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
17134    match event.payload.get(field) {
17135        None | Some(Value::Null) => Ok(None),
17136        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
17137            invalid_recorded_history(
17138                "condition_wait_definition_invalid",
17139                sequence,
17140                &format!("non-negative integer {field}"),
17141                &value.to_string(),
17142                "condition history contains an invalid numeric definition field",
17143            )
17144        }),
17145    }
17146}
17147
17148fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
17149    event
17150        .payload
17151        .get("signal_name")
17152        .or_else(|| event.raw.get("signal_name"))
17153        .and_then(Value::as_str)
17154        .filter(|value| !value.is_empty())
17155        .map(str::to_string)
17156        .ok_or_else(|| {
17157            invalid_recorded_history(
17158                "signal_wait_name_missing",
17159                sequence,
17160                "non-empty signal_name",
17161                &event.event_type,
17162                "canonical signal-wait history is missing its signal identity",
17163            )
17164        })
17165}
17166
17167fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
17168    // Applying a buffered control-plane signal has no authored call sequence.
17169    // Its outer sequence orders history events and must not become a wait.
17170    if event.event_type == "SignalApplied"
17171        && event
17172            .payload
17173            .get("signal_wait_id")
17174            .and_then(Value::as_str)
17175            .is_some_and(|id| id.starts_with("signal-command:"))
17176        && event.payload.get("sequence").is_none()
17177        && event.payload.get("workflow_sequence").is_none()
17178    {
17179        return false;
17180    }
17181    matches!(
17182        event.event_type.as_str(),
17183        "SignalWaitOpened" | "SignalApplied"
17184    )
17185}
17186
17187fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
17188    event
17189        .payload
17190        .get(field)
17191        .and_then(Value::as_str)
17192        .filter(|value| !value.is_empty())
17193        .map(str::to_string)
17194        .ok_or_else(|| {
17195            invalid_recorded_history(
17196                "timer_history_field_missing",
17197                sequence,
17198                field,
17199                &event.event_type,
17200                "timer history is missing a required identity field",
17201            )
17202        })
17203}
17204
17205fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
17206    event
17207        .payload
17208        .get(field)
17209        .and_then(value_as_u64)
17210        .ok_or_else(|| {
17211            invalid_recorded_history(
17212                "timer_history_field_missing",
17213                sequence,
17214                field,
17215                &event.event_type,
17216                "timer history is missing a required numeric field",
17217            )
17218        })
17219}
17220
17221fn recorded_search_attribute_types(
17222    payload: &Value,
17223    attributes: &Value,
17224    sequence: u64,
17225) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
17226    let Some(raw_types) = payload.get("attribute_types") else {
17227        // This is the explicit compatibility rule for histories recorded
17228        // before typed identity was persisted. Values still constrain replay;
17229        // the unknown type snapshot does not assert a typed match.
17230        return Ok(RecordedSnapshotValue::Unknown);
17231    };
17232    let Some(raw_types) = raw_types.as_object() else {
17233        return Err(invalid_recorded_history(
17234            "search_attribute_types_malformed",
17235            sequence,
17236            "canonical attribute type map",
17237            &raw_types.to_string(),
17238            "search-attribute history contains malformed type identity",
17239        ));
17240    };
17241    let attribute_keys = attributes
17242        .as_object()
17243        .expect("recorded search attributes were validated as an object");
17244    let mut types = BTreeMap::new();
17245    for (key, value) in raw_types {
17246        let Some(attribute_type) = value.as_str() else {
17247            return Err(invalid_recorded_history(
17248                "search_attribute_types_malformed",
17249                sequence,
17250                "canonical string type name",
17251                &value.to_string(),
17252                "search-attribute history contains a non-string type identity",
17253            ));
17254        };
17255        if !attribute_keys.contains_key(key)
17256            || !matches!(
17257                attribute_type,
17258                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
17259            )
17260        {
17261            return Err(invalid_recorded_history(
17262                "search_attribute_types_malformed",
17263                sequence,
17264                "canonical types for keys present in attributes",
17265                &format!("{key}:{attribute_type}"),
17266                "search-attribute history contains unsupported or orphaned type identity",
17267            ));
17268        }
17269        types.insert(key.clone(), attribute_type.to_string());
17270    }
17271    Ok(RecordedSnapshotValue::Known(types))
17272}
17273
17274fn invalid_recorded_history(
17275    reason: &str,
17276    sequence: u64,
17277    expected: &str,
17278    actual: &str,
17279    message: &str,
17280) -> Error {
17281    Error::NonDeterministicReplay(ReplayFailure::new(
17282        reason,
17283        Some(sequence),
17284        Some(expected.to_string()),
17285        Some(actual.to_string()),
17286        message,
17287    ))
17288}
17289
17290type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
17291
17292fn activity_outcome(
17293    event: &HistoryEvent,
17294    fallback_codec: &str,
17295    recorded_activity_type: Option<String>,
17296) -> Result<ActivityOutcome> {
17297    if event.event_type == "ActivityCompleted" {
17298        let codec = event
17299            .payload
17300            .get("payload_codec")
17301            .and_then(Value::as_str)
17302            .unwrap_or(fallback_codec);
17303        return Ok(Ok(decode_wire_avro_value(
17304            event.payload.get("result").unwrap_or(&Value::Null),
17305            codec,
17306        )?));
17307    }
17308
17309    let payload = &event.payload;
17310    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
17311        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
17312        "ActivityCancelled" => (
17313            ActivityFailureKind::Cancelled,
17314            "cancelled",
17315            "activity was cancelled",
17316        ),
17317        "ActivityTimedOut" => (
17318            ActivityFailureKind::TimedOut,
17319            "timeout",
17320            "activity timed out",
17321        ),
17322        _ => unreachable!("activity_outcome is called only for terminal activity events"),
17323    };
17324    let exception = payload
17325        .get("exception")
17326        .filter(|value| !value.is_null())
17327        .cloned();
17328    let failure_category = payload_string(payload, "failure_category");
17329    let timeout_kind = payload_string(payload, "timeout_kind");
17330    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
17331        ActivityFailureKind::Failed => failure_category
17332            .clone()
17333            .unwrap_or_else(|| fallback_reason.to_string()),
17334        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
17335        ActivityFailureKind::TimedOut => timeout_kind
17336            .clone()
17337            .unwrap_or_else(|| fallback_reason.to_string()),
17338    });
17339    let message = payload_string(payload, "message")
17340        .or_else(|| {
17341            exception
17342                .as_ref()
17343                .and_then(|value| payload_string(value, "message"))
17344        })
17345        .unwrap_or_else(|| fallback_message.to_string());
17346
17347    Ok(Err(ActivityFailure {
17348        kind,
17349        reason,
17350        message,
17351        activity_execution_id: payload_string(payload, "activity_execution_id"),
17352        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
17353        activity_type: payload_string(payload, "activity_type")
17354            .or_else(|| payload_string(payload, "activity_name"))
17355            .or(recorded_activity_type),
17356        activity_class: payload_string(payload, "activity_class"),
17357        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
17358        failure_id: payload_string(payload, "failure_id"),
17359        failure_category,
17360        timeout_kind,
17361        non_retryable: payload
17362            .get("non_retryable")
17363            .and_then(Value::as_bool)
17364            .unwrap_or(false),
17365        exception_type: payload_string(payload, "exception_type").or_else(|| {
17366            exception
17367                .as_ref()
17368                .and_then(|value| payload_string(value, "type"))
17369        }),
17370        exception_class: payload_string(payload, "exception_class").or_else(|| {
17371            exception
17372                .as_ref()
17373                .and_then(|value| payload_string(value, "class"))
17374        }),
17375        code: payload
17376            .get("code")
17377            .filter(|value| !value.is_null())
17378            .cloned(),
17379        exception,
17380    }))
17381}
17382
17383type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
17384
17385fn child_workflow_outcomes(
17386    events: &[HistoryEvent],
17387    fallback_codec: &str,
17388    parent: WorkflowIdentity,
17389) -> Result<Vec<ChildWorkflowOutcome>> {
17390    let mut outcomes = Vec::new();
17391
17392    for event in events {
17393        let kind = match event.event_type.as_str() {
17394            "ChildRunCompleted" => None,
17395            "ChildRunFailed" => Some((
17396                ChildWorkflowFailureKind::Failed,
17397                "child_workflow",
17398                "child workflow failed",
17399            )),
17400            "ChildRunCancelled" => Some((
17401                ChildWorkflowFailureKind::Cancelled,
17402                "cancelled",
17403                "child workflow was cancelled",
17404            )),
17405            "ChildRunTerminated" => Some((
17406                ChildWorkflowFailureKind::Terminated,
17407                "terminated",
17408                "child workflow was terminated",
17409            )),
17410            _ => continue,
17411        };
17412        let payload = &event.payload;
17413        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
17414        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
17415        let child_workflow_type = payload_string(payload, "child_workflow_type");
17416
17417        if let Some((kind, reason, fallback_message)) = kind {
17418            let exception = payload
17419                .get("exception")
17420                .filter(|value| !value.is_null())
17421                .cloned();
17422            let message = payload_string(payload, "message")
17423                .or_else(|| {
17424                    exception
17425                        .as_ref()
17426                        .and_then(|value| payload_string(value, "message"))
17427                })
17428                .unwrap_or_else(|| fallback_message.to_string());
17429            let exception_type = payload_string(payload, "exception_type").or_else(|| {
17430                exception
17431                    .as_ref()
17432                    .and_then(|value| payload_string(value, "type"))
17433            });
17434            let exception_class = payload_string(payload, "exception_class").or_else(|| {
17435                exception
17436                    .as_ref()
17437                    .and_then(|value| payload_string(value, "class"))
17438            });
17439            outcomes.push(Err(ChildWorkflowFailure {
17440                kind,
17441                reason: reason.to_string(),
17442                message,
17443                parent_workflow_id: parent.workflow_id.clone(),
17444                parent_workflow_run_id: parent.run_id.clone(),
17445                child_workflow_id,
17446                child_workflow_run_id,
17447                child_workflow_type,
17448                failure_id: payload_string(payload, "failure_id"),
17449                failure_category: payload_string(payload, "failure_category"),
17450                exception_type,
17451                exception_class,
17452                non_retryable: payload
17453                    .get("non_retryable")
17454                    .and_then(Value::as_bool)
17455                    .unwrap_or(false),
17456                code: payload
17457                    .get("code")
17458                    .filter(|value| !value.is_null())
17459                    .cloned(),
17460                exception,
17461            }));
17462            continue;
17463        }
17464
17465        let codec = payload
17466            .get("payload_codec")
17467            .and_then(Value::as_str)
17468            .unwrap_or(fallback_codec);
17469        let result = payload
17470            .get("result")
17471            .or_else(|| payload.get("output"))
17472            .unwrap_or(&Value::Null);
17473        outcomes.push(Ok(ChildWorkflowAvroResult {
17474            parent: parent.clone(),
17475            child: WorkflowIdentity {
17476                workflow_id: child_workflow_id,
17477                run_id: child_workflow_run_id,
17478            },
17479            child_workflow_type,
17480            result: decode_wire_avro_value(result, codec)?,
17481        }));
17482    }
17483
17484    Ok(outcomes)
17485}
17486
17487fn payload_string(payload: &Value, key: &str) -> Option<String> {
17488    payload
17489        .get(key)
17490        .and_then(Value::as_str)
17491        .filter(|value| !value.is_empty())
17492        .map(str::to_string)
17493}
17494
17495fn recorded_activity_failure_boundary(
17496    ctx: &WorkflowContext,
17497    error: &Error,
17498) -> Option<(u64, String)> {
17499    let Error::ActivityFailed(failure) = error else {
17500        return None;
17501    };
17502    if failure.kind != ActivityFailureKind::Failed {
17503        return None;
17504    }
17505    let activity_execution_id = failure
17506        .activity_execution_id
17507        .as_deref()
17508        .filter(|value| !value.is_empty())?;
17509    let state = ctx.state.lock().ok()?;
17510    let mut matches = state.recorded_commands.iter().filter_map(|command| {
17511        let RecordedCommand::Activity {
17512            sequence,
17513            outcome: Some(Err(recorded_failure)),
17514            ..
17515        } = command
17516        else {
17517            return None;
17518        };
17519        (*sequence > 0 && recorded_failure == failure)
17520            .then_some((*sequence, activity_execution_id.to_string()))
17521    });
17522    let boundary = matches.next()?;
17523    matches.next().is_none().then_some(boundary)
17524}
17525
17526fn workflow_failure_command(
17527    error: &Error,
17528    failed_activity_boundary: Option<(u64, String)>,
17529) -> Value {
17530    let (exception_type, exception_class, properties) = match error {
17531        Error::NexusOperationFailed(failure) => (
17532            "NexusOperationFailed",
17533            "durable_workflow::NexusOperationFailure",
17534            json!({"service_call_id":failure.service_call_id, "status":failure.status,
17535                "caller_observed_error_type":failure.exception_type, "service_exception":failure.exception}),
17536        ),
17537        Error::ActivityFailed(failure) => (
17538            match failure.kind {
17539                ActivityFailureKind::Failed => "ActivityFailed",
17540                ActivityFailureKind::Cancelled => "ActivityCancelled",
17541                ActivityFailureKind::TimedOut => "ActivityTimedOut",
17542            },
17543            "durable_workflow::ActivityFailure",
17544            json!({
17545                "reason": failure.reason,
17546                "activity_execution_id": failure.activity_execution_id,
17547                "activity_attempt_id": failure.activity_attempt_id,
17548                "activity_type": failure.activity_type,
17549                "activity_class": failure.activity_class,
17550                "attempt_number": failure.attempt_number,
17551                "failure_id": failure.failure_id,
17552                "failure_category": failure.failure_category,
17553                "timeout_kind": failure.timeout_kind,
17554                "activity_non_retryable": failure.non_retryable,
17555                "activity_exception_type": failure.exception_type,
17556                "activity_exception_class": failure.exception_class,
17557                "activity_code": failure.code,
17558                "activity_exception": failure.exception,
17559            }),
17560        ),
17561        Error::ChildWorkflowFailed(failure) => (
17562            match failure.kind {
17563                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17564                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17565                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17566            },
17567            "durable_workflow::ChildWorkflowFailure",
17568            json!({
17569                "reason": failure.reason,
17570                "parent_workflow_id": failure.parent_workflow_id,
17571                "parent_workflow_run_id": failure.parent_workflow_run_id,
17572                "child_workflow_id": failure.child_workflow_id,
17573                "child_workflow_run_id": failure.child_workflow_run_id,
17574                "child_workflow_type": failure.child_workflow_type,
17575                "failure_id": failure.failure_id,
17576                "failure_category": failure.failure_category,
17577                "child_exception_type": failure.exception_type,
17578                "child_exception_class": failure.exception_class,
17579                "child_non_retryable": failure.non_retryable,
17580                "child_code": failure.code,
17581                "child_exception": failure.exception,
17582            }),
17583        ),
17584        Error::ParallelFailed(failure) => (
17585            "ParallelFailed",
17586            "durable_workflow::ParallelFailure",
17587            json!({
17588                "parallel_group_id": failure.group_id,
17589                "parallel_member_path": failure.member_path,
17590                "parallel_group_path": failure.group_path,
17591                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
17592                "cause_type": workflow_error_type(&failure.cause),
17593                "cause_message": failure.cause.to_string(),
17594            }),
17595        ),
17596        Error::SagaCompensationFailed(failure) => (
17597            "SagaCompensationFailed",
17598            "durable_workflow::SagaCompensationFailure",
17599            json!({
17600                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
17601                "initiating_failure_message": failure.initiating_failure.to_string(),
17602                "compensation_activity_type": failure.compensation_activity_type,
17603                "compensation_registration_order": failure.compensation_registration_order,
17604                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
17605                "compensation_failure_message": failure.compensation_failure.to_string(),
17606            }),
17607        ),
17608        Error::WorkflowCancellationRequested(_) => (
17609            "WorkflowCancellationRequested",
17610            "durable_workflow::WorkflowCancellationRequested",
17611            json!({"reason": "cancelled"}),
17612        ),
17613        Error::CooperativeCancellationRequested(cancellation) => (
17614            "WorkflowCancellationRequested",
17615            "durable_workflow::CooperativeCancellationRequested",
17616            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
17617                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
17618        ),
17619        Error::CancellationScopeRequested(cancellation) => (
17620            "WorkflowCancellationRequested",
17621            "durable_workflow::CancellationScopeRequested",
17622            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
17623                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
17624                "cancellation":cancellation.context.to_value()}),
17625        ),
17626        Error::NonDeterministicReplay(_) => (
17627            "NonDeterministicReplay",
17628            "durable_workflow::Error",
17629            Value::Null,
17630        ),
17631        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
17632    };
17633    let non_retryable = match error {
17634        Error::ActivityFailed(failure) => failure.non_retryable,
17635        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17636        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17637        Error::SagaCompensationFailed(failure) => {
17638            workflow_error_non_retryable(&failure.compensation_failure)
17639        }
17640        Error::WorkflowCancellationRequested(_)
17641        | Error::CooperativeCancellationRequested(_)
17642        | Error::CancellationScopeRequested(_) => true,
17643        Error::NonDeterministicReplay(_) => true,
17644        _ => false,
17645    };
17646
17647    let mut command = json!({
17648        "type": "fail_workflow",
17649        "message": error.to_string(),
17650        "exception_type": exception_type,
17651        "exception_class": exception_class,
17652        "non_retryable": non_retryable,
17653        "exception": {
17654            "type": exception_type,
17655            "class": exception_class,
17656            "message": error.to_string(),
17657            "properties": properties,
17658        }
17659    });
17660
17661    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
17662        command["failed_step_sequence"] = json!(sequence);
17663        command["failed_activity_execution_id"] = json!(activity_execution_id);
17664    }
17665
17666    command
17667}
17668
17669fn workflow_error_type(error: &Error) -> &'static str {
17670    match error {
17671        Error::NexusOperationFailed(_) => "NexusOperationFailed",
17672        Error::ActivityFailed(failure) => match failure.kind {
17673            ActivityFailureKind::Failed => "ActivityFailed",
17674            ActivityFailureKind::Cancelled => "ActivityCancelled",
17675            ActivityFailureKind::TimedOut => "ActivityTimedOut",
17676        },
17677        Error::ChildWorkflowFailed(failure) => match failure.kind {
17678            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17679            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17680            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17681        },
17682        Error::ParallelFailed(_) => "ParallelFailed",
17683        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
17684        Error::WorkflowCancellationRequested(_)
17685        | Error::CooperativeCancellationRequested(_)
17686        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
17687        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
17688        _ => "RustWorkflowError",
17689    }
17690}
17691
17692fn workflow_error_non_retryable(error: &Error) -> bool {
17693    match error {
17694        Error::ActivityFailed(failure) => failure.non_retryable,
17695        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17696        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17697        Error::SagaCompensationFailed(failure) => {
17698            workflow_error_non_retryable(&failure.compensation_failure)
17699        }
17700        Error::WorkflowCancellationRequested(_)
17701        | Error::CooperativeCancellationRequested(_)
17702        | Error::CancellationScopeRequested(_)
17703        | Error::NonDeterministicReplay(_) => true,
17704        _ => false,
17705    }
17706}
17707
17708fn workflow_task_integrity_error(error: &Error) -> bool {
17709    matches!(
17710        error,
17711        Error::NonDeterministicReplay(_)
17712            | Error::Protocol(_)
17713            | Error::CancellationScopeExecutionUnavailable
17714            | Error::MissingWorkflowCommandIdentity
17715            | Error::WorkflowStatePoisoned
17716    )
17717}
17718
17719fn decode_signal_event_arguments(
17720    event: &HistoryEvent,
17721    fallback_codec: &str,
17722) -> Result<Vec<AvroValue>> {
17723    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17724    validate_payload_codec(codec)?;
17725    let raw = signal_history_payload(&event.payload);
17726    let decoded = match raw.filter(|value| !value.is_null()) {
17727        Some(value) => decode_wire_avro_value(value, codec)?,
17728        None => AvroValue::Array(Vec::new()),
17729    };
17730    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17731        unreachable!("normalize_avro_arguments always returns an array");
17732    };
17733    Ok(arguments)
17734}
17735
17736fn decode_update_event_arguments(
17737    event: &HistoryEvent,
17738    fallback_codec: &str,
17739) -> Result<Vec<AvroValue>> {
17740    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17741    validate_payload_codec(codec)?;
17742    let decoded = match event
17743        .payload
17744        .get("arguments")
17745        .filter(|value| !value.is_null())
17746    {
17747        Some(value) => decode_wire_avro_value(value, codec)?,
17748        None => AvroValue::Array(Vec::new()),
17749    };
17750    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17751        unreachable!("normalize_avro_arguments always returns an array");
17752    };
17753    Ok(arguments)
17754}
17755
17756fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17757    let Some(export_events) = task
17758        .history_export
17759        .as_ref()
17760        .and_then(|export| export.get("history_events"))
17761        .and_then(Value::as_array)
17762    else {
17763        return Ok(());
17764    };
17765
17766    if export_events.len() > task.history_events.len() {
17767        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
17768    }
17769
17770    Ok(())
17771}
17772
17773fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17774    let Some(export) = task.history_export.as_ref() else {
17775        return Ok(());
17776    };
17777    let signals = export
17778        .get("signals")
17779        .and_then(Value::as_array)
17780        .cloned()
17781        .unwrap_or_default();
17782    let activities = export
17783        .get("activities")
17784        .and_then(Value::as_array)
17785        .cloned()
17786        .unwrap_or_default();
17787    let export_codec = export
17788        .get("payloads")
17789        .and_then(|payloads| payloads.get("codec"))
17790        .and_then(Value::as_str)
17791        .unwrap_or(&task.payload_codec)
17792        .to_string();
17793    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
17794
17795    for event in &mut task.history_events {
17796        if event.event_type == "ActivityCompleted" {
17797            let sequence = event
17798                .payload
17799                .get("sequence")
17800                .or_else(|| event.payload.get("workflow_sequence"))
17801                .and_then(value_as_u64);
17802            let Some(activity) = sequence.and_then(|sequence| {
17803                activities.iter().find(|activity| {
17804                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
17805                })
17806            }) else {
17807                continue;
17808            };
17809            let Some(payload) = event.payload.as_object_mut() else {
17810                continue;
17811            };
17812            if missing_payload(payload.get("result")) {
17813                if let Some(result) = activity
17814                    .get("result")
17815                    .filter(|value| !missing_payload(Some(value)))
17816                {
17817                    payload.insert("result".to_string(), result.clone());
17818                }
17819            }
17820            for field in ["payload_codec", "activity_type"] {
17821                if payload
17822                    .get(field)
17823                    .and_then(Value::as_str)
17824                    .unwrap_or_default()
17825                    .is_empty()
17826                {
17827                    if let Some(value) = activity.get(field) {
17828                        payload.insert(field.to_string(), value.clone());
17829                    }
17830                }
17831            }
17832            continue;
17833        }
17834
17835        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
17836            continue;
17837        }
17838        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17839        let command_id = event
17840            .payload
17841            .get("workflow_command_id")
17842            .or_else(|| event.raw.get("workflow_command_id"))
17843            .and_then(Value::as_str);
17844        let signal_name = event
17845            .payload
17846            .get("signal_name")
17847            .and_then(Value::as_str)
17848            .unwrap_or_default()
17849            .to_string();
17850        let matched = signals
17851            .iter()
17852            .find(|signal| {
17853                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
17854            })
17855            .or_else(|| {
17856                signals.iter().find(|signal| {
17857                    command_id.is_some()
17858                        && signal.get("command_id").and_then(Value::as_str) == command_id
17859                })
17860            })
17861            .or_else(|| {
17862                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
17863                let signal = signals
17864                    .iter()
17865                    .filter(|signal| {
17866                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
17867                    })
17868                    .nth(*offset);
17869                if signal.is_some() {
17870                    *offset += 1;
17871                }
17872                signal
17873            });
17874        let Some(signal) = matched else {
17875            continue;
17876        };
17877        let signal_codec = signal
17878            .get("payload_codec")
17879            .and_then(Value::as_str)
17880            .unwrap_or(&export_codec);
17881        let Some(payload) = event.payload.as_object_mut() else {
17882            continue;
17883        };
17884        if missing_payload(payload.get("arguments")) {
17885            if let Some(arguments) = signal
17886                .get("arguments")
17887                .filter(|value| !missing_payload(Some(value)))
17888            {
17889                let envelope = match arguments {
17890                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
17891                    other => other.clone(),
17892                };
17893                payload.insert("arguments".to_string(), envelope);
17894            }
17895        }
17896        if payload
17897            .get("payload_codec")
17898            .and_then(Value::as_str)
17899            .unwrap_or_default()
17900            .is_empty()
17901        {
17902            payload.insert("payload_codec".to_string(), json!(signal_codec));
17903        }
17904    }
17905
17906    Ok(())
17907}
17908
17909fn missing_payload(value: Option<&Value>) -> bool {
17910    match value {
17911        None | Some(Value::Null) => true,
17912        Some(Value::String(value)) => value.is_empty(),
17913        Some(_) => false,
17914    }
17915}
17916
17917fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
17918    history_signal_events(
17919        &task.history_events,
17920        task.history_export.as_ref(),
17921        &task.payload_codec,
17922    )
17923}
17924
17925fn history_signal_events(
17926    history_events: &[HistoryEvent],
17927    history_export: Option<&Value>,
17928    payload_codec: &str,
17929) -> Result<Vec<QuerySignal>> {
17930    let export_signals = history_export
17931        .and_then(|export| export.get("signals"))
17932        .and_then(Value::as_array)
17933        .cloned()
17934        .unwrap_or_default();
17935    let export_codec = history_export
17936        .and_then(|export| export.get("payloads"))
17937        .and_then(|payloads| payloads.get("codec"))
17938        .and_then(Value::as_str)
17939        .unwrap_or(payload_codec);
17940    let mut name_offsets: HashMap<String, usize> = HashMap::new();
17941    let mut signals: Vec<QuerySignal> = Vec::new();
17942    let mut signal_indices = HashMap::new();
17943    let mut command_indices = HashMap::new();
17944
17945    for event in history_events {
17946        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
17947            continue;
17948        }
17949
17950        let name = event
17951            .payload
17952            .get("signal_name")
17953            .and_then(Value::as_str)
17954            .unwrap_or_default();
17955        if name.is_empty() {
17956            continue;
17957        }
17958        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17959        let command_id = event
17960            .payload
17961            .get("workflow_command_id")
17962            .or_else(|| event.raw.get("workflow_command_id"))
17963            .and_then(Value::as_str);
17964        let matched_export = export_signals
17965            .iter()
17966            .find(|candidate| {
17967                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
17968            })
17969            .or_else(|| {
17970                export_signals.iter().find(|candidate| {
17971                    command_id.is_some()
17972                        && candidate.get("command_id").and_then(Value::as_str) == command_id
17973                })
17974            })
17975            .or_else(|| {
17976                let offset = name_offsets.entry(name.to_string()).or_default();
17977                let candidate = export_signals
17978                    .iter()
17979                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
17980                    .nth(*offset);
17981                if candidate.is_some() {
17982                    *offset += 1;
17983                }
17984                candidate
17985            });
17986        let codec = event
17987            .payload
17988            .get("payload_codec")
17989            .and_then(Value::as_str)
17990            .or_else(|| {
17991                matched_export
17992                    .and_then(|signal| signal.get("payload_codec"))
17993                    .and_then(Value::as_str)
17994            })
17995            .unwrap_or(export_codec);
17996        let raw_arguments = signal_history_payload(&event.payload)
17997            .filter(|value| !value.is_null())
17998            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
17999        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
18000        let workflow_sequence = event
18001            .payload
18002            .get("workflow_sequence")
18003            .and_then(value_as_u64)
18004            .or_else(|| {
18005                matched_export
18006                    .and_then(|signal| signal.get("workflow_sequence"))
18007                    .and_then(value_as_u64)
18008            });
18009
18010        let id = signal_id.or_else(|| {
18011            matched_export
18012                .and_then(|signal| signal.get("id"))
18013                .and_then(Value::as_str)
18014        });
18015        let command_id = command_id.or_else(|| {
18016            matched_export
18017                .and_then(|signal| signal.get("command_id"))
18018                .and_then(Value::as_str)
18019        });
18020        let duplicate = id
18021            .and_then(|id| signal_indices.get(id))
18022            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
18023            .copied();
18024        let index = duplicate.unwrap_or(signals.len());
18025        if let Some(index) = duplicate {
18026            let original = &mut signals[index];
18027            let same_arguments = if event.event_type == "SignalApplied" {
18028                if let Some(value) = event.payload.get("value") {
18029                    let expected = match original.avro_arguments.as_slice() {
18030                        [] => AvroValue::Boolean(true),
18031                        [value] => value.clone(),
18032                        values => AvroValue::Array(values.to_vec()),
18033                    };
18034                    let applied = decode_wire_avro_value(value, codec)?;
18035                    applied == expected
18036                        || applied == AvroValue::Array(original.avro_arguments.clone())
18037                } else {
18038                    original.avro_arguments == avro_arguments
18039                }
18040            } else {
18041                original.avro_arguments == avro_arguments
18042            };
18043            if original.name != name
18044                || !same_arguments
18045                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
18046            {
18047                return Err(Error::Codec("conflicting committed signal identity".into()));
18048            }
18049            if original.id.is_none() {
18050                original.id = id.map(str::to_string);
18051            }
18052            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
18053        } else {
18054            signals.push(QuerySignal {
18055                id: id.map(str::to_string),
18056                name: name.to_string(),
18057                arguments,
18058                avro_arguments,
18059                workflow_sequence,
18060            });
18061        }
18062        if let Some(id) = id {
18063            signal_indices.insert(id.to_string(), index);
18064        }
18065        if let Some(id) = command_id {
18066            command_indices.insert(id.to_string(), index);
18067        }
18068    }
18069
18070    if signals.is_empty() {
18071        for signal in export_signals {
18072            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
18073                continue;
18074            }
18075            let Some(name) = signal.get("name").and_then(Value::as_str) else {
18076                continue;
18077            };
18078            let codec = signal
18079                .get("payload_codec")
18080                .and_then(Value::as_str)
18081                .unwrap_or(export_codec);
18082            let (arguments, avro_arguments) =
18083                decode_query_signal_arguments(signal.get("arguments"), codec)?;
18084            signals.push(QuerySignal {
18085                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
18086                name: name.to_string(),
18087                arguments,
18088                avro_arguments,
18089                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
18090            });
18091        }
18092        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
18093    }
18094
18095    Ok(signals)
18096}
18097
18098fn decode_query_signal_arguments(
18099    raw: Option<&Value>,
18100    codec: &str,
18101) -> Result<(Vec<Value>, Vec<AvroValue>)> {
18102    validate_payload_codec(codec)?;
18103    let decoded = match raw.filter(|value| !value.is_null()) {
18104        Some(value) => decode_wire_avro_value(value, codec)?,
18105        None => AvroValue::Array(Vec::new()),
18106    };
18107    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
18108        unreachable!("normalize_avro_arguments always returns an array");
18109    };
18110    let arguments = avro_arguments
18111        .iter()
18112        .cloned()
18113        .map(AvroValue::into_json)
18114        .collect::<Result<Vec<_>>>()?;
18115    Ok((arguments, avro_arguments))
18116}
18117
18118fn value_as_u64(value: &Value) -> Option<u64> {
18119    value
18120        .as_u64()
18121        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
18122}
18123
18124#[cfg(test)]
18125mod tests {
18126    use super::*;
18127    mod activity_cancellation_policies;
18128    mod cancellation_scope_admission;
18129    mod cancellation_scope_authoring;
18130    mod cancellation_scope_history;
18131    mod cancellation_scope_opening;
18132    mod cancellation_scope_replay;
18133    mod child_workflow_policies;
18134    mod cooperative_cancellation;
18135    mod local_activity;
18136    mod nexus;
18137    mod runtime_payloads;
18138    mod runtime_uploads;
18139    mod version_marker_contract;
18140    mod worker_session;
18141    use std::{
18142        fs,
18143        io::{Read, Write},
18144        net::{SocketAddr, TcpListener, TcpStream},
18145        process::Command as ProcessCommand,
18146        sync::atomic::AtomicUsize,
18147        thread,
18148    };
18149
18150    #[derive(Clone, Copy, Debug)]
18151    enum InvalidTaskPayloadCodec {
18152        Missing,
18153        Null,
18154        NonString,
18155    }
18156
18157    impl InvalidTaskPayloadCodec {
18158        fn label(self) -> &'static str {
18159            match self {
18160                Self::Missing => "missing",
18161                Self::Null => "null",
18162                Self::NonString => "non-string",
18163            }
18164        }
18165
18166        fn apply(self, task: &mut Value) {
18167            let task = task.as_object_mut().expect("task fixture object");
18168            match self {
18169                Self::Missing => {
18170                    task.remove("payload_codec");
18171                }
18172                Self::Null => {
18173                    task.insert("payload_codec".to_string(), Value::Null);
18174                }
18175                Self::NonString => {
18176                    task.insert("payload_codec".to_string(), json!(42));
18177                }
18178            }
18179        }
18180    }
18181
18182    fn fixture_envelope(value: Value) -> Value {
18183        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
18184    }
18185
18186    fn fixture_blob(value: Value) -> String {
18187        encode_payload(&value, DEFAULT_CODEC)
18188            .expect("encode Avro test fixture")
18189            .blob
18190    }
18191
18192    #[test]
18193    fn client_builder_rejects_the_sdk_owned_api_suffix() {
18194        for base_url in [
18195            "http://127.0.0.1:8080/api",
18196            "http://localhost:8080/api/",
18197            "https://runtime.example.test/namespaces/orders/api",
18198        ] {
18199            let error = Client::builder(base_url)
18200                .build()
18201                .expect_err("SDK-owned /api suffix must be rejected during build");
18202
18203            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
18204            assert!(
18205                error.to_string().contains("SDK appends /api automatically"),
18206                "the validation error must explain how to fix the endpoint"
18207            );
18208        }
18209    }
18210
18211    #[test]
18212    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
18213        for (base_url, expected) in [
18214            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
18215            (
18216                "http://localhost:8080/durable-workflow/",
18217                "http://localhost:8080/durable-workflow",
18218            ),
18219            (
18220                "https://runtime.example.test/namespaces/orders",
18221                "https://runtime.example.test/namespaces/orders",
18222            ),
18223            (
18224                "https://runtime.example.test/gateway/api/namespaces/orders",
18225                "https://runtime.example.test/gateway/api/namespaces/orders",
18226            ),
18227            (
18228                "https://api.example.test/runtime/orders/",
18229                "https://api.example.test/runtime/orders",
18230            ),
18231        ] {
18232            let client = Client::builder(base_url)
18233                .build()
18234                .expect("Server and Cloud runtime base URL must remain valid");
18235
18236            assert_eq!(client.base_url, expected);
18237        }
18238    }
18239
18240    #[test]
18241    fn workflow_completion_uses_the_additive_command_protocol_floor() {
18242        assert_eq!(
18243            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
18244            MINIMUM_WORKER_PROTOCOL_VERSION
18245        );
18246        assert_eq!(
18247            workflow_completion_protocol_version(&[json!({
18248                "type": "upsert_search_attributes",
18249                "attributes": {"OrderStatus": "waiting"},
18250            })]),
18251            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
18252        );
18253        assert_eq!(
18254            workflow_completion_protocol_version(&[json!({
18255                "type": "upsert_search_attributes",
18256                "attributes": {"OrderStatus": "waiting"},
18257                "attribute_types": {"OrderStatus": "keyword"},
18258            })]),
18259            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
18260        );
18261        assert_eq!(
18262            workflow_completion_protocol_version(&[
18263                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
18264                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18265            ]),
18266            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
18267        );
18268        assert_eq!(
18269            workflow_completion_protocol_version(&[
18270                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
18271                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18272            ]),
18273            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
18274        );
18275        assert_eq!(
18276            workflow_completion_protocol_version(&[json!({
18277                "type": "open_condition_wait",
18278                "condition_wait_occurrence_id": "rust:condition-wait:0",
18279                "condition_key": "ready",
18280            })]),
18281            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18282        );
18283        assert_eq!(
18284            workflow_completion_protocol_version_with_message_streams(
18285                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
18286                true,
18287            ),
18288            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
18289        );
18290        assert_eq!(
18291            workflow_completion_protocol_version_with_message_streams(
18292                &[json!({
18293                    "type": "open_condition_wait",
18294                    "condition_wait_occurrence_id": "rust:condition-wait:0",
18295                    "condition_key": "ready",
18296                })],
18297                true,
18298            ),
18299            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18300        );
18301    }
18302
18303    #[test]
18304    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
18305        let manifest = portable_worker_affinity_capability_manifest();
18306
18307        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
18308            assert_eq!(manifest[capability]["supported"], json!(false));
18309            assert_eq!(
18310                manifest[capability]["minimum_protocol_version"],
18311                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
18312            );
18313            assert!(manifest[capability]["reason"]
18314                .as_str()
18315                .is_some_and(|reason| !reason.is_empty()));
18316        }
18317    }
18318
18319    fn typed_fidelity_probe() -> AvroValue {
18320        AvroValue::Map(BTreeMap::from([
18321            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
18322            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
18323            (
18324                "numeric".to_string(),
18325                AvroValue::Map(BTreeMap::from([
18326                    ("0".to_string(), AvroValue::String("zero".to_string())),
18327                    ("1".to_string(), AvroValue::String("one".to_string())),
18328                ])),
18329            ),
18330            (
18331                "nested".to_string(),
18332                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
18333                    "enabled".to_string(),
18334                    AvroValue::Boolean(true),
18335                )]))]),
18336            ),
18337            (
18338                "projection_collisions".to_string(),
18339                AvroValue::Array(projection_collision_probe()),
18340            ),
18341        ]))
18342    }
18343
18344    fn projection_collision_probe() -> Vec<AvroValue> {
18345        vec![
18346            AvroValue::Map(BTreeMap::from([
18347                ("$type".to_string(), AvroValue::String("bytes".to_string())),
18348                (
18349                    "base64".to_string(),
18350                    AvroValue::String("ordinary user text".to_string()),
18351                ),
18352            ])),
18353            AvroValue::Map(BTreeMap::from([
18354                ("$type".to_string(), AvroValue::String("map".to_string())),
18355                (
18356                    "entries".to_string(),
18357                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
18358                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
18359                        (
18360                            "value".to_string(),
18361                            AvroValue::String("user map".to_string()),
18362                        ),
18363                    ]))]),
18364                ),
18365            ])),
18366        ]
18367    }
18368
18369    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18370    struct TypedContract {
18371        nested: TypedNested,
18372        mode: TypedMode,
18373        optional: Option<String>,
18374        absent: Option<String>,
18375        items: Vec<i64>,
18376        labels: BTreeMap<String, String>,
18377        bytes: serde_bytes::ByteBuf,
18378        signed: i64,
18379        finite: f64,
18380    }
18381
18382    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18383    struct TypedNested {
18384        enabled: bool,
18385    }
18386
18387    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18388    enum TypedMode {
18389        Detailed { label: String },
18390    }
18391
18392    fn typed_contract() -> TypedContract {
18393        TypedContract {
18394            nested: TypedNested { enabled: true },
18395            mode: TypedMode::Detailed {
18396                label: "compiler-checked".to_string(),
18397            },
18398            optional: Some("present".to_string()),
18399            absent: None,
18400            items: vec![i64::MIN, 0, i64::MAX],
18401            labels: BTreeMap::from([
18402                ("language".to_string(), "rust".to_string()),
18403                ("wire".to_string(), "avro".to_string()),
18404            ]),
18405            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
18406            signed: -9_223_372_036_854_775_000,
18407            finite: 12.5,
18408        }
18409    }
18410
18411    #[derive(Clone, Debug, Default, PartialEq)]
18412    struct ReplayCounterState {
18413        loaded: Option<String>,
18414        count: i64,
18415        finished: bool,
18416    }
18417
18418    fn replay_counter_worker() -> Worker {
18419        let client = Client::new("http://127.0.0.1:8080").expect("client");
18420        let mut worker = Worker::new(client, "rust-workers");
18421        worker.register_replayed_workflow(
18422            "replay-counter",
18423            ReplayCounterState::default,
18424            |ctx, _input, state| async move {
18425                let loaded = ctx.activity("load-counter", json!([])).await?;
18426                state.update(|current| {
18427                    current.loaded = loaded.as_str().map(str::to_string);
18428                })?;
18429                for _ in 0..2 {
18430                    let signal = ctx.wait_signal("increment").await?;
18431                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
18432                    state.update(|current| current.count += amount)?;
18433                }
18434                state.update(|current| current.finished = true)?;
18435                state.read(|current| Ok(json!(current.count)))?
18436            },
18437        );
18438        worker.register_replayed_query::<ReplayCounterState, _, _>(
18439            "replay-counter",
18440            "current",
18441            |_ctx, state, _args| async move {
18442                Ok(json!({
18443                    "loaded": state.loaded,
18444                    "count": state.count,
18445                    "finished": state.finished,
18446                }))
18447            },
18448        );
18449        worker.register_replayed_query::<ReplayCounterState, _, _>(
18450            "replay-counter",
18451            "detached-mutation",
18452            |_ctx, state, _args| async move {
18453                let mut detached = (*state).clone();
18454                detached.count = 999;
18455                Ok(json!(detached.count))
18456            },
18457        );
18458        worker.register_replayed_query::<ReplayCounterState, _, _>(
18459            "replay-counter",
18460            "failed-mutation",
18461            |_ctx, state, _args| async move {
18462                let mut detached = (*state).clone();
18463                detached.count = 999;
18464                Err(Error::WorkerLoop("query refused".to_string()))
18465            },
18466        );
18467        worker
18468    }
18469
18470    fn replay_counter_query(
18471        query_name: &str,
18472        history_events: Value,
18473        run_status: &str,
18474    ) -> QueryTask {
18475        let arguments = fixture_envelope(json!([]));
18476        serde_json::from_value(json!({
18477            "query_task_id": format!("query-{query_name}"),
18478            "workflow_type": "replay-counter",
18479            "query_name": query_name,
18480            "payload_codec": DEFAULT_CODEC,
18481            "workflow_arguments": arguments.clone(),
18482            "query_arguments": arguments,
18483            "history_events": history_events,
18484            "run_status": run_status,
18485        }))
18486        .expect("query task")
18487    }
18488
18489    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
18490        workflow_context_with_codec(history, DEFAULT_CODEC)
18491    }
18492
18493    fn workflow_context_with_codec(
18494        history: Vec<HistoryEvent>,
18495        payload_codec: &str,
18496    ) -> WorkflowContext {
18497        WorkflowContext {
18498            cancellation_scope_id: "root".into(),
18499            state: Arc::new(Mutex::new(
18500                WorkflowState::new_with_identity(
18501                    history,
18502                    None,
18503                    None,
18504                    "rust-workers".to_string(),
18505                    payload_codec.to_string(),
18506                    None,
18507                )
18508                .expect("valid workflow history"),
18509            )),
18510        }
18511    }
18512
18513    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
18514        HistoryEvent {
18515            event_type: event_type.to_string(),
18516            payload,
18517            raw: HashMap::new(),
18518        }
18519    }
18520
18521    fn parallel_path_entry(
18522        kind: &str,
18523        base: u64,
18524        size: usize,
18525        index: usize,
18526    ) -> ParallelGroupMetadata {
18527        parallel_group_entry(base, size, index, kind)
18528    }
18529
18530    fn parallel_history_event(
18531        event_type: &str,
18532        sequence: u64,
18533        identity_field: &str,
18534        identity: &str,
18535        path: Vec<ParallelGroupMetadata>,
18536        result: Option<Value>,
18537    ) -> HistoryEvent {
18538        let mut payload = serde_json::Map::from_iter([
18539            ("sequence".to_string(), json!(sequence)),
18540            (identity_field.to_string(), json!(identity)),
18541        ]);
18542        let inner = path.last().expect("parallel history path");
18543        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
18544        payload.insert("parallel_group_path".to_string(), json!(path));
18545        if let Some(result) = result {
18546            let field = if event_type == "ChildRunCompleted" {
18547                "result"
18548            } else {
18549                "result"
18550            };
18551            payload.insert(field.to_string(), fixture_envelope(result));
18552            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
18553        }
18554        history_event(event_type, Value::Object(payload))
18555    }
18556
18557    fn nested_parallel_operations() -> Vec<ParallelOperation> {
18558        vec![
18559            ParallelOperation::activity("first", json!([])),
18560            ParallelOperation::group(vec![
18561                ParallelOperation::child_workflow(
18562                    "second",
18563                    ChildWorkflowOptions::new("child-workers"),
18564                    json!([]),
18565                ),
18566                ParallelOperation::activity("third", json!([])),
18567            ]),
18568        ]
18569    }
18570
18571    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
18572        let outer = [
18573            parallel_path_entry("mixed", 1, 3, 0),
18574            parallel_path_entry("mixed", 1, 3, 1),
18575            parallel_path_entry("mixed", 1, 3, 2),
18576        ];
18577        [
18578            vec![outer[0].clone()],
18579            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
18580            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
18581        ]
18582    }
18583
18584    #[test]
18585    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
18586        let ctx = workflow_context(Vec::new());
18587        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18588        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18589
18590        assert!(matches!(
18591            call.as_mut().poll(&mut task_context),
18592            Poll::Pending
18593        ));
18594        let commands = ctx.take_commands().expect("parallel commands");
18595        assert_eq!(
18596            commands
18597                .iter()
18598                .map(|command| command["type"].as_str().unwrap_or_default())
18599                .collect::<Vec<_>>(),
18600            [
18601                "schedule_activity",
18602                "start_child_workflow",
18603                "schedule_activity"
18604            ]
18605        );
18606        let paths = nested_parallel_paths();
18607        for (command, path) in commands.iter().zip(paths) {
18608            assert_eq!(command["parallel_group_path"], json!(path));
18609            assert_eq!(
18610                command["parallel_group_id"],
18611                json!(path.last().expect("inner group").parallel_group_id)
18612            );
18613        }
18614    }
18615
18616    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
18617        let paths = nested_parallel_paths();
18618        let third = parallel_history_event(
18619            "ActivityCompleted",
18620            3,
18621            "activity_type",
18622            "third",
18623            paths[2].clone(),
18624            Some(json!("three")),
18625        );
18626        vec![
18627            parallel_history_event(
18628                "ActivityCompleted",
18629                1,
18630                "activity_type",
18631                "first",
18632                paths[0].clone(),
18633                Some(json!("one")),
18634            ),
18635            parallel_history_event(
18636                "ChildWorkflowScheduled",
18637                2,
18638                "child_workflow_type",
18639                "second",
18640                paths[1].clone(),
18641                None,
18642            ),
18643            parallel_history_event(
18644                "ChildRunCompleted",
18645                2,
18646                "child_workflow_type",
18647                "second",
18648                paths[1].clone(),
18649                Some(json!("two")),
18650            ),
18651            third.clone(),
18652            third,
18653        ]
18654    }
18655
18656    #[test]
18657    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
18658        for _restart_or_completed_replay in 0..2 {
18659            let ctx = workflow_context(completed_nested_parallel_history());
18660            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18661            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18662            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
18663                panic!("completed nested parallel history must replay");
18664            };
18665            assert_eq!(
18666                results,
18667                vec![
18668                    ParallelResult::Activity(json!("one")),
18669                    ParallelResult::Group(vec![
18670                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
18671                            parent: WorkflowIdentity {
18672                                workflow_id: None,
18673                                run_id: None,
18674                            },
18675                            child: WorkflowIdentity {
18676                                workflow_id: None,
18677                                run_id: None,
18678                            },
18679                            child_workflow_type: Some("second".to_string()),
18680                            result: json!("two"),
18681                        }),
18682                        ParallelResult::Activity(json!("three")),
18683                    ]),
18684                ]
18685            );
18686            assert!(ctx.take_commands().expect("commands").is_empty());
18687            ctx.ensure_history_consumed().expect("history consumed");
18688        }
18689    }
18690
18691    #[test]
18692    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
18693        let paths = nested_parallel_paths();
18694        let history = vec![
18695            parallel_history_event(
18696                "ActivityCompleted",
18697                1,
18698                "activity_type",
18699                "first",
18700                paths[0].clone(),
18701                Some(json!("one")),
18702            ),
18703            parallel_history_event(
18704                "ChildWorkflowScheduled",
18705                2,
18706                "child_workflow_type",
18707                "second",
18708                paths[1].clone(),
18709                None,
18710            ),
18711            parallel_history_event(
18712                "ChildRunFailed",
18713                2,
18714                "child_workflow_type",
18715                "second",
18716                paths[1].clone(),
18717                None,
18718            ),
18719            parallel_history_event(
18720                "ActivityCompleted",
18721                3,
18722                "activity_type",
18723                "third",
18724                paths[2].clone(),
18725                Some(json!("late")),
18726            ),
18727        ];
18728        let ctx = workflow_context(history);
18729        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18730        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18731        let outcome = call.as_mut().poll(&mut task_context);
18732        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
18733            panic!("one failed child must return a typed partial failure: {outcome:?}");
18734        };
18735        assert_eq!(failure.member_path, [1, 0]);
18736        assert_eq!(failure.group_id, "parallel-calls:1:3");
18737        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
18738        assert_eq!(
18739            failure
18740                .completed
18741                .iter()
18742                .map(|completion| completion.member_path.clone())
18743                .collect::<Vec<_>>(),
18744            [vec![0], vec![1, 1]]
18745        );
18746    }
18747
18748    #[test]
18749    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
18750        let paths = nested_parallel_paths();
18751        let history = vec![
18752            parallel_history_event(
18753                "ActivityScheduled",
18754                1,
18755                "activity_type",
18756                "first",
18757                paths[0].clone(),
18758                None,
18759            ),
18760            parallel_history_event(
18761                "ChildWorkflowScheduled",
18762                2,
18763                "child_workflow_type",
18764                "second",
18765                paths[1].clone(),
18766                None,
18767            ),
18768            parallel_history_event(
18769                "ActivityScheduled",
18770                3,
18771                "activity_type",
18772                "third",
18773                paths[2].clone(),
18774                None,
18775            ),
18776        ];
18777        for _restart in 0..2 {
18778            let ctx = workflow_context(history.clone());
18779            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18780            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18781            let outcome = call.as_mut().poll(&mut task_context);
18782            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
18783            assert!(ctx.take_commands().expect("commands").is_empty());
18784        }
18785    }
18786
18787    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
18788        vec![selection_group_entry(
18789            1,
18790            2,
18791            index,
18792            "activity",
18793            &SelectionMemberMetadata {
18794                key: SelectionKey::Name(key.to_string()),
18795                index,
18796                base_sequence: index as u64 + 1,
18797                size: 1,
18798                kind: "activity".to_string(),
18799            },
18800        )]
18801    }
18802
18803    fn selection_activity_event(
18804        event_type: &str,
18805        index: usize,
18806        key: &str,
18807        result: Option<Value>,
18808    ) -> HistoryEvent {
18809        let sequence = index as u64 + 1;
18810        let mut event = parallel_history_event(
18811            event_type,
18812            sequence,
18813            "activity_type",
18814            &format!("{key}-activity"),
18815            selection_path(index, key),
18816            result,
18817        );
18818        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
18819        event.raw.insert(
18820            "id".to_string(),
18821            json!(if event_type == "ActivityCompleted" {
18822                format!("event-{key}")
18823            } else {
18824                format!("{event_type}-{key}")
18825            }),
18826        );
18827        event
18828    }
18829
18830    fn selection_winner_marker() -> HistoryEvent {
18831        history_event(
18832            "SelectionResolved",
18833            json!({
18834                "selection_group_id": "select-calls:1:2",
18835                "selection_group_base_sequence": 1,
18836                "selection_group_size": 2,
18837                "member_key": "fast",
18838                "member_index": 1,
18839                "member_base_sequence": 2,
18840                "member_size": 1,
18841                "operation_kind": "activity",
18842                "operation_identity": "activity-fast",
18843                "outcome": "completed",
18844                "resolution_event_id": "event-fast",
18845                "resolution_event_type": "ActivityCompleted",
18846            }),
18847        )
18848    }
18849
18850    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
18851        ctx.select_keyed(vec![
18852            (
18853                "slow",
18854                ParallelOperation::activity_with_options(
18855                    "slow-activity",
18856                    ActivityOptions::new().task_queue("default"),
18857                    json!([]),
18858                ),
18859            ),
18860            (
18861                "fast",
18862                ParallelOperation::activity_with_options(
18863                    "fast-activity",
18864                    ActivityOptions::new().task_queue("default"),
18865                    json!([]),
18866                ),
18867            ),
18868        ])
18869    }
18870
18871    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
18872        let ctx = workflow_context(history);
18873        let mut call = Box::pin(keyed_activity_selection(&ctx));
18874        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18875        let selected = match call.as_mut().poll(&mut task_context) {
18876            Poll::Ready(Ok(selected)) => selected,
18877            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
18878            Poll::Pending => panic!("persisted selection winner must replay without pending"),
18879        };
18880        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
18881        assert_eq!(
18882            selected.value,
18883            Some(ParallelResult::Activity(json!("winner-value")))
18884        );
18885        let slow = selected
18886            .handle(&SelectionKey::Name("slow".to_string()))
18887            .expect("slow handle")
18888            .clone();
18889        let mut await_slow = Box::pin(slow.await_result());
18890        assert!(matches!(
18891            await_slow.as_mut().poll(&mut task_context),
18892            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
18893        ));
18894        assert!(ctx.take_commands().expect("commands").is_empty());
18895    }
18896
18897    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
18898
18899    fn canonical_selection_history() -> Vec<HistoryEvent> {
18900        const FIXTURE: &[u8] =
18901            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
18902        assert_eq!(
18903            format!("{:x}", Sha256::digest(FIXTURE)),
18904            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18905        );
18906        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
18907
18908        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
18909    }
18910
18911    #[test]
18912    fn selection_fresh_process_entrypoint() {
18913        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
18914            return;
18915        };
18916        let persisted = fs::read(path).expect("persisted selection history");
18917        assert_eq!(
18918            format!("{:x}", Sha256::digest(&persisted)),
18919            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18920        );
18921        let fixture: Value =
18922            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
18923        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
18924            .expect("valid persisted selection history");
18925
18926        assert_persisted_selection_replay(history);
18927    }
18928
18929    #[test]
18930    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
18931        let ctx = workflow_context(Vec::new());
18932        let mut call = Box::pin(keyed_activity_selection(&ctx));
18933        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18934
18935        assert!(matches!(
18936            call.as_mut().poll(&mut task_context),
18937            Poll::Pending
18938        ));
18939        let commands = ctx.take_commands().expect("selection commands");
18940        assert_eq!(commands.len(), 2);
18941        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
18942        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
18943        assert!(commands.iter().all(|command| {
18944            command["parallel_group_id"] == json!("select-calls:1:2")
18945                && command["parallel_group_mode"] == json!("select")
18946        }));
18947    }
18948
18949    #[test]
18950    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
18951        let ctx = workflow_context(Vec::new());
18952        let mut invalid = Box::pin(ctx.select_keyed(vec![(
18953            "",
18954            ParallelOperation::activity("invalid", json!([])),
18955        )]));
18956        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18957        assert!(matches!(
18958            invalid.as_mut().poll(&mut task_context),
18959            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
18960                reason: "selection_key_invalid",
18961                ..
18962            })))
18963        ));
18964
18965        for invalid_key in [json!(""), json!(-1)] {
18966            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
18967            event.payload["selection_member_key"] = invalid_key.clone();
18968            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
18969            assert!(matches!(
18970                WorkflowState::new_with_identity(
18971                    vec![event],
18972                    None,
18973                    None,
18974                    "rust-workers".to_string(),
18975                    DEFAULT_CODEC.to_string(),
18976                    None,
18977                ),
18978                Err(Error::NonDeterministicReplay(_))
18979            ));
18980        }
18981    }
18982
18983    #[test]
18984    fn selection_preserves_valid_named_and_numeric_keys() {
18985        let ctx = workflow_context(Vec::new());
18986        let mut selection = Box::pin(ctx.select_keyed(vec![
18987            (
18988                SelectionKey::Index(0),
18989                ParallelOperation::activity("numeric", json!([])),
18990            ),
18991            (
18992                SelectionKey::Name("named".to_string()),
18993                ParallelOperation::timer(Duration::from_secs(1)),
18994            ),
18995        ]));
18996        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18997
18998        assert!(matches!(
18999            selection.as_mut().poll(&mut task_context),
19000            Poll::Pending
19001        ));
19002        let commands = ctx.take_commands().expect("selection commands");
19003        assert_eq!(commands[0]["selection_member_key"], json!(0));
19004        assert_eq!(commands[1]["selection_member_key"], json!("named"));
19005    }
19006
19007    #[test]
19008    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
19009        let history = canonical_selection_history();
19010        assert_persisted_selection_replay(history.clone());
19011
19012        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19013            .join("tests/fixtures/durable_selection_runtime_history.json");
19014        let output =
19015            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
19016                .args([
19017                    "--exact",
19018                    "tests::selection_fresh_process_entrypoint",
19019                    "--nocapture",
19020                ])
19021                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
19022                .output()
19023                .expect("run fresh selection replay process");
19024
19025        assert!(
19026            output.status.success(),
19027            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
19028            String::from_utf8_lossy(&output.stdout),
19029            String::from_utf8_lossy(&output.stderr),
19030        );
19031    }
19032
19033    #[test]
19034    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
19035        let mut history = canonical_selection_history();
19036        history.retain(|event| event.event_type != "SelectionResolved");
19037        let ctx = workflow_context(history);
19038        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19039        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19040
19041        assert!(matches!(
19042            selection.as_mut().poll(&mut task_context),
19043            Poll::Pending
19044        ));
19045        assert!(ctx.take_commands().expect("commands").is_empty());
19046        assert!(
19047            ctx.matched_recorded_pending()
19048                .expect("selection pending state"),
19049            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
19050        );
19051    }
19052
19053    #[test]
19054    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
19055        for (terminal_event, predicate_satisfied, timeout_seconds) in [
19056            ("ConditionWaitSatisfied", true, None),
19057            ("ConditionWaitTimedOut", false, Some(0)),
19058        ] {
19059            let member = SelectionMemberMetadata {
19060                key: SelectionKey::Name("condition".to_string()),
19061                index: 0,
19062                base_sequence: 1,
19063                size: 1,
19064                kind: "condition".to_string(),
19065            };
19066            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
19067            let mut payload = json!({
19068                "sequence": 1,
19069                "condition_wait_id": "condition-1",
19070                "condition_wait_occurrence_id": "rust:condition-wait:0",
19071                "condition_key": "ready",
19072                "condition_definition_fingerprint": "sha256:ready-v1",
19073                "parallel_group_path": path,
19074            });
19075            payload
19076                .as_object_mut()
19077                .expect("condition history payload")
19078                .extend(
19079                    serde_json::to_value(&path[0])
19080                        .expect("condition selection metadata")
19081                        .as_object()
19082                        .expect("condition selection metadata object")
19083                        .clone(),
19084                );
19085            if let Some(timeout_seconds) = timeout_seconds {
19086                payload["timeout_seconds"] = json!(timeout_seconds);
19087            }
19088            let history = vec![
19089                history_event("ConditionWaitOpened", payload.clone()),
19090                history_event(terminal_event, payload),
19091            ];
19092            let ctx = workflow_context(history);
19093            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
19094            if timeout_seconds.is_some() {
19095                options = options.timeout(Duration::ZERO);
19096            }
19097            let mut selection = Box::pin(ctx.select_keyed(vec![(
19098                "condition",
19099                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
19100            )]));
19101            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19102
19103            assert!(matches!(
19104                selection.as_mut().poll(&mut task_context),
19105                Poll::Pending
19106            ));
19107            assert!(ctx.take_commands().expect("commands").is_empty());
19108            assert!(
19109                ctx.matched_recorded_pending()
19110                    .expect("condition selection pending state"),
19111                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
19112            );
19113        }
19114    }
19115
19116    #[test]
19117    fn selection_immediate_condition_members_open_a_durable_wait() {
19118        for predicate_satisfied in [true, false] {
19119            let ctx = workflow_context(Vec::new());
19120            let mut selection = Box::pin(ctx.select_keyed(vec![(
19121                "condition",
19122                ParallelOperation::condition(
19123                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
19124                    move || Ok(predicate_satisfied),
19125                ),
19126            )]));
19127            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19128
19129            assert!(matches!(
19130                selection.as_mut().poll(&mut task_context),
19131                Poll::Pending
19132            ));
19133            let commands = ctx.take_commands().expect("condition selection command");
19134            assert_eq!(commands.len(), 1);
19135            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
19136            assert_eq!(commands[0]["timeout_seconds"], json!(0));
19137            assert_eq!(
19138                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
19139                json!("select")
19140            );
19141        }
19142    }
19143
19144    #[test]
19145    fn selection_loser_cancellation_is_explicit_and_idempotent() {
19146        let history = vec![
19147            selection_activity_event("ActivityScheduled", 0, "slow", None),
19148            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19149            selection_winner_marker(),
19150        ];
19151        let ctx = workflow_context(history.clone());
19152        let mut call = Box::pin(keyed_activity_selection(&ctx));
19153        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19154        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19155            panic!("winner must replay");
19156        };
19157        let slow = selected
19158            .handle(&SelectionKey::Name("slow".to_string()))
19159            .expect("slow handle")
19160            .clone();
19161        let mut cancel = Box::pin(slow.cancel());
19162        assert!(matches!(
19163            cancel.as_mut().poll(&mut task_context),
19164            Poll::Pending
19165        ));
19166        assert!(matches!(
19167            cancel.as_mut().poll(&mut task_context),
19168            Poll::Pending
19169        ));
19170        let commands = ctx.take_commands().expect("cancel command");
19171        assert_eq!(commands.len(), 1);
19172        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
19173        assert_eq!(commands[0]["member_key"], json!("slow"));
19174
19175        let mut cancelled_history = history;
19176        cancelled_history.push(history_event(
19177            "SelectionOperationCancelled",
19178            json!({
19179                "selection_group_id": "select-calls:1:2",
19180                "member_key": "slow",
19181                "member_index": 0,
19182                "member_base_sequence": 1,
19183                "member_size": 1,
19184                "operation_kind": "activity",
19185                "operation_identity": "activity-slow",
19186                "cancelled_at": "2026-08-27T00:00:00Z",
19187            }),
19188        ));
19189        let replayed = workflow_context(cancelled_history);
19190        let mut call = Box::pin(keyed_activity_selection(&replayed));
19191        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19192            panic!("winner must replay after cancellation");
19193        };
19194        let slow = selected
19195            .handle(&SelectionKey::Name("slow".to_string()))
19196            .expect("slow handle")
19197            .clone();
19198        let mut cancel = Box::pin(slow.cancel());
19199        assert!(matches!(
19200            cancel.as_mut().poll(&mut task_context),
19201            Poll::Ready(Ok(()))
19202        ));
19203        assert!(replayed.take_commands().expect("commands").is_empty());
19204    }
19205
19206    #[test]
19207    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
19208        let base_history = vec![
19209            selection_activity_event("ActivityScheduled", 0, "slow", None),
19210            selection_activity_event("ActivityScheduled", 1, "fast", None),
19211            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19212            selection_winner_marker(),
19213        ];
19214        for (field, corrupt) in [
19215            ("member_key", json!("fast")),
19216            ("member_index", json!(1)),
19217            ("member_base_sequence", json!(3)),
19218            ("member_size", json!(2)),
19219            ("operation_kind", json!("timer")),
19220            ("operation_identity", json!("forged")),
19221        ] {
19222            let mut cancellation = json!({
19223                "selection_group_id": "select-calls:1:2",
19224                "member_key": "slow",
19225                "member_index": 0,
19226                "member_base_sequence": 1,
19227                "member_size": 1,
19228                "operation_kind": "activity",
19229                "operation_identity": "activity-slow",
19230            });
19231            cancellation[field] = corrupt;
19232            let mut history = base_history.clone();
19233            history.push(history_event("SelectionOperationCancelled", cancellation));
19234            let ctx = workflow_context(history);
19235            let mut selection = Box::pin(keyed_activity_selection(&ctx));
19236            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19237
19238            assert!(matches!(
19239                selection.as_mut().poll(&mut task_context),
19240                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19241            ));
19242        }
19243    }
19244
19245    #[test]
19246    fn selection_child_identity_prefers_the_durable_run_id() {
19247        let ctx = workflow_context(vec![history_event(
19248            "ChildWorkflowScheduled",
19249            json!({
19250                "sequence": 1,
19251                "child_workflow_type": "child",
19252                "child_workflow_instance_id": "child-instance",
19253                "child_workflow_run_id": "child-run",
19254            }),
19255        )]);
19256        let state = ctx.state.lock().expect("workflow state");
19257
19258        assert_eq!(
19259            selection_operation_identity(&state, "child", 1, 1),
19260            "child-run"
19261        );
19262    }
19263
19264    #[test]
19265    fn selection_activity_identity_requires_canonical_execution_id() {
19266        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
19267        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
19268        let mut fast_completed =
19269            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
19270        for event in [&mut fast_open, &mut fast_completed] {
19271            event
19272                .payload
19273                .as_object_mut()
19274                .expect("activity payload")
19275                .remove("activity_execution_id");
19276            event.payload["activity_id"] = json!("forged-activity-id");
19277        }
19278        let mut marker = selection_winner_marker();
19279        marker.payload["operation_identity"] = json!("forged-activity-id");
19280        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
19281        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19282        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19283
19284        assert!(matches!(
19285            selection.as_mut().poll(&mut task_context),
19286            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19287        ));
19288    }
19289
19290    #[test]
19291    fn selection_completion_before_cancellation_remains_awaitable() {
19292        let history = vec![
19293            selection_activity_event("ActivityScheduled", 0, "slow", None),
19294            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19295            selection_winner_marker(),
19296            selection_activity_event(
19297                "ActivityCompleted",
19298                0,
19299                "slow",
19300                Some(json!("completed-first")),
19301            ),
19302        ];
19303        let ctx = workflow_context(history);
19304        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19305        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19306        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19307            panic!("winner must replay");
19308        };
19309        let slow = selected
19310            .handle(&SelectionKey::Name("slow".to_string()))
19311            .expect("slow handle")
19312            .clone();
19313        let mut cancel = Box::pin(slow.cancel());
19314        assert!(matches!(
19315            cancel.as_mut().poll(&mut task_context),
19316            Poll::Ready(Ok(()))
19317        ));
19318        let mut await_slow = Box::pin(slow.await_result());
19319        assert!(matches!(
19320            await_slow.as_mut().poll(&mut task_context),
19321            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
19322        ));
19323        let commands = ctx.take_commands().expect("commands");
19324        assert!(commands.is_empty());
19325    }
19326
19327    #[test]
19328    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
19329        let nested_member = SelectionMemberMetadata {
19330            key: SelectionKey::Name("nested".to_string()),
19331            index: 0,
19332            base_sequence: 1,
19333            size: 2,
19334            kind: "group".to_string(),
19335        };
19336        let deadline_member = SelectionMemberMetadata {
19337            key: SelectionKey::Name("deadline".to_string()),
19338            index: 1,
19339            base_sequence: 3,
19340            size: 1,
19341            kind: "timer".to_string(),
19342        };
19343        let nested_paths = [
19344            vec![
19345                selection_group_entry(1, 3, 0, "mixed", &nested_member),
19346                parallel_group_entry(1, 2, 0, "activity"),
19347            ],
19348            vec![
19349                selection_group_entry(1, 3, 1, "mixed", &nested_member),
19350                parallel_group_entry(1, 2, 1, "activity"),
19351            ],
19352        ];
19353        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
19354        let mut timer_fired = parallel_history_event(
19355            "TimerFired",
19356            3,
19357            "timer_id",
19358            "timer-3",
19359            deadline_path.clone(),
19360            None,
19361        );
19362        timer_fired.payload["delay_seconds"] = json!(0);
19363        timer_fired
19364            .raw
19365            .insert("id".to_string(), json!("timer-fired"));
19366        let mut timer_scheduled = parallel_history_event(
19367            "TimerScheduled",
19368            3,
19369            "timer_id",
19370            "timer-3",
19371            deadline_path,
19372            None,
19373        );
19374        timer_scheduled.payload["delay_seconds"] = json!(0);
19375        let history = vec![
19376            parallel_history_event(
19377                "ActivityScheduled",
19378                1,
19379                "activity_type",
19380                "nested-first",
19381                nested_paths[0].clone(),
19382                None,
19383            ),
19384            parallel_history_event(
19385                "ActivityScheduled",
19386                2,
19387                "activity_type",
19388                "nested-second",
19389                nested_paths[1].clone(),
19390                None,
19391            ),
19392            timer_scheduled,
19393            timer_fired,
19394            history_event(
19395                "SelectionResolved",
19396                json!({
19397                    "selection_group_id": "select-calls:1:3",
19398                    "selection_group_base_sequence": 1,
19399                    "selection_group_size": 3,
19400                    "member_key": "deadline",
19401                    "member_index": 1,
19402                    "member_base_sequence": 3,
19403                    "member_size": 1,
19404                    "operation_kind": "timer",
19405                    "operation_identity": "timer-3",
19406                    "outcome": "completed",
19407                    "resolution_event_id": "timer-fired",
19408                    "resolution_event_type": "TimerFired",
19409                }),
19410            ),
19411            parallel_history_event(
19412                "ActivityFailed",
19413                2,
19414                "activity_type",
19415                "nested-second",
19416                nested_paths[1].clone(),
19417                None,
19418            ),
19419        ];
19420        let ctx = workflow_context(history);
19421        let mut selection = Box::pin(ctx.select_keyed(vec![
19422            (
19423                "nested",
19424                ParallelOperation::group(vec![
19425                    ParallelOperation::activity("nested-first", json!([])),
19426                    ParallelOperation::activity("nested-second", json!([])),
19427                ]),
19428            ),
19429            ("deadline", ParallelOperation::timer(Duration::ZERO)),
19430        ]));
19431        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19432        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19433            panic!("deadline winner must replay");
19434        };
19435        let nested = selected
19436            .handle(&SelectionKey::Name("nested".to_string()))
19437            .expect("nested handle")
19438            .clone();
19439        let mut cancel = Box::pin(nested.cancel());
19440        assert!(matches!(
19441            cancel.as_mut().poll(&mut task_context),
19442            Poll::Ready(Ok(()))
19443        ));
19444        let mut await_nested = Box::pin(nested.await_result());
19445
19446        assert!(matches!(
19447            await_nested.as_mut().poll(&mut task_context),
19448            Poll::Ready(Err(Error::ActivityFailed(_)))
19449        ));
19450        assert!(ctx.take_commands().expect("commands").is_empty());
19451    }
19452
19453    #[test]
19454    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
19455        let ctx = workflow_context(Vec::new());
19456        let mut call = Box::pin(ctx.select(vec![
19457            ParallelOperation::child_workflow(
19458                "child",
19459                ChildWorkflowOptions::new("children"),
19460                json!([]),
19461            ),
19462            ParallelOperation::timer(Duration::from_secs(30)),
19463            ParallelOperation::signal("approval"),
19464            ParallelOperation::condition(
19465                ConditionWaitOptions::new("ready", "sha256:ready"),
19466                || Ok(false),
19467            ),
19468            ParallelOperation::group(vec![
19469                ParallelOperation::activity("nested-one", json!([])),
19470                ParallelOperation::activity("nested-two", json!([])),
19471            ]),
19472        ]));
19473        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19474        assert!(matches!(
19475            call.as_mut().poll(&mut task_context),
19476            Poll::Pending
19477        ));
19478        let commands = ctx.take_commands().expect("selection commands");
19479        assert_eq!(
19480            commands
19481                .iter()
19482                .map(|command| command["type"].as_str().unwrap_or_default())
19483                .collect::<Vec<_>>(),
19484            [
19485                "start_child_workflow",
19486                "start_timer",
19487                "open_signal_wait",
19488                "open_condition_wait",
19489                "schedule_activity",
19490                "schedule_activity",
19491            ]
19492        );
19493        assert!(commands.iter().all(|command| {
19494            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
19495        }));
19496        assert_eq!(
19497            commands[4]["parallel_group_path"].as_array().map(Vec::len),
19498            Some(2)
19499        );
19500        assert_eq!(
19501            commands[4]["parallel_group_path"][0]["selection_member_kind"],
19502            json!("group")
19503        );
19504        assert_eq!(
19505            commands[5]["parallel_group_path"][0]["selection_member_kind"],
19506            json!("group")
19507        );
19508
19509        let one_leaf_ctx = workflow_context(Vec::new());
19510        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
19511            ParallelOperation::activity("nested-only", json!([])),
19512        ])]));
19513        assert!(matches!(
19514            one_leaf.as_mut().poll(&mut task_context),
19515            Poll::Pending
19516        ));
19517        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
19518        assert_eq!(one_leaf_commands.len(), 1);
19519        assert_eq!(
19520            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
19521            json!("group")
19522        );
19523        assert_eq!(
19524            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
19525            json!(1)
19526        );
19527    }
19528
19529    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
19530        let mut saga = ctx.saga();
19531        let outcome = async {
19532            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19533            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19534            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
19535            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
19536            ctx.activity("trip.charge", json!([])).await?;
19537            Ok(json!({"status": "booked"}))
19538        }
19539        .await;
19540        saga.finish(outcome).await
19541    }
19542
19543    fn saga_activity(
19544        event_type: &str,
19545        sequence: u64,
19546        activity_type: &str,
19547        result: Option<Value>,
19548    ) -> HistoryEvent {
19549        let mut payload = json!({
19550            "sequence": sequence,
19551            "activity_type": activity_type,
19552            "message": format!("{activity_type} failed"),
19553            "exception_type": "PlannedFailure",
19554            "non_retryable": true,
19555        });
19556        if let Some(result) = result {
19557            payload["result"] = fixture_envelope(result);
19558        }
19559        history_event(event_type, payload)
19560    }
19561
19562    #[test]
19563    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
19564        let completed_hotel_compensation = saga_activity(
19565            "ActivityCompleted",
19566            4,
19567            "trip.cancel-hotel",
19568            Some(Value::Null),
19569        );
19570        let history = vec![
19571            saga_activity(
19572                "ActivityCompleted",
19573                1,
19574                "trip.reserve-flight",
19575                Some(json!("flight-1")),
19576            ),
19577            saga_activity(
19578                "ActivityCompleted",
19579                2,
19580                "trip.reserve-hotel",
19581                Some(json!("hotel-1")),
19582            ),
19583            saga_activity("ActivityFailed", 3, "trip.charge", None),
19584            completed_hotel_compensation.clone(),
19585            completed_hotel_compensation,
19586        ];
19587
19588        for _restart in 0..2 {
19589            let ctx = workflow_context(history.clone());
19590            let mut future = Box::pin(trip_saga(ctx.clone()));
19591            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19592            assert!(matches!(
19593                future.as_mut().poll(&mut task_context),
19594                Poll::Pending
19595            ));
19596            let commands = ctx.take_commands().expect("compensation command");
19597            assert_eq!(commands.len(), 1);
19598            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19599        }
19600    }
19601
19602    #[test]
19603    fn saga_compensation_failure_preserves_both_typed_failures() {
19604        let history = vec![
19605            saga_activity(
19606                "ActivityCompleted",
19607                1,
19608                "trip.reserve-flight",
19609                Some(json!("flight-1")),
19610            ),
19611            saga_activity(
19612                "ActivityCompleted",
19613                2,
19614                "trip.reserve-hotel",
19615                Some(json!("hotel-1")),
19616            ),
19617            saga_activity("ActivityFailed", 3, "trip.charge", None),
19618            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
19619        ];
19620        let ctx = workflow_context(history);
19621        let mut future = Box::pin(trip_saga(ctx));
19622        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19623        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
19624            future.as_mut().poll(&mut task_context)
19625        else {
19626            panic!("compensation failure must remain structured");
19627        };
19628        assert!(matches!(
19629            *failure.initiating_failure,
19630            Error::ActivityFailed(_)
19631        ));
19632        assert!(matches!(
19633            *failure.compensation_failure,
19634            Error::ActivityFailed(_)
19635        ));
19636        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
19637        assert_eq!(failure.compensation_registration_order, 2);
19638    }
19639
19640    #[test]
19641    fn saga_compensates_cooperative_cancellation() {
19642        let ctx = workflow_context(vec![saga_activity(
19643            "ActivityCompleted",
19644            1,
19645            "trip.reserve-flight",
19646            Some(json!("flight-1")),
19647        )]);
19648        ctx.state.lock().expect("state").cancel_requested = true;
19649        let run = {
19650            let ctx = ctx.clone();
19651            async move {
19652                let mut saga = ctx.saga();
19653                let outcome = async {
19654                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19655                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19656                    ctx.throw_if_cancellation_requested()?;
19657                    Ok(json!("unexpected"))
19658                }
19659                .await;
19660                saga.finish(outcome).await
19661            }
19662        };
19663        let mut future = Box::pin(run);
19664        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19665        assert!(matches!(
19666            future.as_mut().poll(&mut task_context),
19667            Poll::Pending
19668        ));
19669        let commands = ctx.take_commands().expect("cancellation compensation");
19670        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19671    }
19672
19673    #[test]
19674    fn optional_task_observability_fields_round_trip_without_interpretation() {
19675        let context = json!({"schema": "unknown", "carrier": {"traceparent": "untrusted"}});
19676        let dispatch = json!({"task_id": "other-task"});
19677        let links = json!({"links": []});
19678        let mut value = json!({
19679            "task_id": "task", "query_task_id": "query", "workflow_type": "workflow",
19680            "activity_type": "activity", "query_name": "query", "payload_codec": "avro"
19681        });
19682        let workflow: WorkflowTask =
19683            serde_json::from_value(value.clone()).expect("legacy workflow task");
19684        let activity: ActivityTask =
19685            serde_json::from_value(value.clone()).expect("legacy activity task");
19686        let query: QueryTask = serde_json::from_value(value.clone()).expect("legacy query task");
19687        assert!(workflow.observability_context.is_none());
19688        assert!(activity.observability_context.is_none());
19689        assert!(query.observability_context.is_none());
19690        assert!(activity.workflow_id.is_none());
19691        assert!(activity.run_id.is_none());
19692        assert!(activity.activity_execution_id.is_none());
19693
19694        value["observability_context"] = context.clone();
19695        value["dispatch_observability_context"] = dispatch.clone();
19696        value["observability_links"] = links.clone();
19697        value["workflow_id"] = json!("workflow-id");
19698        value["run_id"] = json!("run-id");
19699        value["activity_execution_id"] = json!("activity-id");
19700        let workflow: WorkflowTask =
19701            serde_json::from_value(value.clone()).expect("workflow metadata");
19702        let activity: ActivityTask =
19703            serde_json::from_value(value.clone()).expect("activity metadata");
19704        let query: QueryTask = serde_json::from_value(value).expect("query metadata");
19705        for fields in [
19706            (
19707                workflow.observability_context,
19708                workflow.dispatch_observability_context,
19709                workflow.observability_links,
19710            ),
19711            (
19712                activity.observability_context,
19713                activity.dispatch_observability_context,
19714                activity.observability_links,
19715            ),
19716            (
19717                query.observability_context,
19718                query.dispatch_observability_context,
19719                query.observability_links,
19720            ),
19721        ] {
19722            assert_eq!(
19723                fields,
19724                (
19725                    Some(context.clone()),
19726                    Some(dispatch.clone()),
19727                    Some(links.clone())
19728                )
19729            );
19730        }
19731        assert_eq!(activity.workflow_id.as_deref(), Some("workflow-id"));
19732        assert_eq!(activity.run_id.as_deref(), Some("run-id"));
19733        assert_eq!(
19734            activity.activity_execution_id.as_deref(),
19735            Some("activity-id")
19736        );
19737    }
19738
19739    fn workflow_task(
19740        workflow_type: &str,
19741        history_events: Vec<HistoryEvent>,
19742        payload_codec: &str,
19743    ) -> WorkflowTask {
19744        WorkflowTask {
19745            task_id: format!("wft-{workflow_type}"),
19746            observability_context: None,
19747            dispatch_observability_context: None,
19748            observability_links: None,
19749            workflow_command_id: None,
19750            workflow_id: Some(format!("wf-{workflow_type}")),
19751            run_id: Some(format!("run-{workflow_type}")),
19752            workflow_type: workflow_type.to_string(),
19753            cancel_requested: false,
19754            payload_codec: payload_codec.to_string(),
19755            arguments: Some(
19756                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
19757            ),
19758            total_history_events: Some(history_events.len() as u64),
19759            history_size_bytes: None,
19760            continue_as_new_recommended: None,
19761            history_budget_pressure: None,
19762            history_events,
19763            next_history_page_token: None,
19764            workflow_task_attempt: 1,
19765            workflow_signal_id: None,
19766            signal_name: None,
19767            signal_arguments: None,
19768            workflow_update_id: None,
19769            update_name: None,
19770            lease_owner: Some("rust-worker".to_string()),
19771        }
19772    }
19773
19774    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19775    struct SideEffectProbe {
19776        request_id: String,
19777        attempt: u32,
19778    }
19779
19780    #[test]
19781    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
19782        let calls = AtomicUsize::new(0);
19783        let ctx = workflow_context(Vec::new());
19784        let value = ctx
19785            .side_effect(|| {
19786                calls.fetch_add(1, Ordering::SeqCst);
19787                SideEffectProbe {
19788                    request_id: "request-42".to_string(),
19789                    attempt: 3,
19790                }
19791            })
19792            .expect("first side effect");
19793        assert_eq!(value.attempt, 3);
19794        assert_eq!(calls.load(Ordering::SeqCst), 1);
19795        let commands = ctx.take_commands().expect("commands");
19796        assert_eq!(commands.len(), 1);
19797        assert_eq!(commands[0]["type"], "record_side_effect");
19798        assert_eq!(
19799            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19800            serde_json::to_value(&value).expect("value")
19801        );
19802
19803        let replay = workflow_context(vec![history_event(
19804            "SideEffectRecorded",
19805            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19806        )]);
19807        let replayed: SideEffectProbe = replay
19808            .side_effect(|| {
19809                calls.fetch_add(1, Ordering::SeqCst);
19810                panic!("committed side-effect callbacks must not run during replay")
19811            })
19812            .expect("replayed side effect");
19813        assert_eq!(replayed, value);
19814        assert_eq!(calls.load(Ordering::SeqCst), 1);
19815        assert!(replay.take_commands().expect("commands").is_empty());
19816        replay.ensure_history_consumed().expect("history consumed");
19817    }
19818
19819    #[test]
19820    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
19821        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19822        let value = ctx
19823            .side_effect(|| SideEffectProbe {
19824                request_id: "avro-request".to_string(),
19825                attempt: 1,
19826            })
19827            .expect("Avro side effect");
19828        let uuid = ctx.uuid_v4().expect("deterministic UUID");
19829        let commands = ctx.take_commands().expect("commands");
19830        assert_eq!(commands.len(), 2);
19831        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
19832        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
19833        assert_eq!(
19834            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19835            serde_json::to_value(&value).expect("value")
19836        );
19837
19838        let replay = workflow_context_with_codec(
19839            vec![
19840                history_event(
19841                    "SideEffectRecorded",
19842                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19843                ),
19844                history_event(
19845                    "SideEffectRecorded",
19846                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
19847                ),
19848            ],
19849            DEFAULT_CODEC,
19850        );
19851        let replayed: SideEffectProbe = replay
19852            .side_effect(|| panic!("Avro callback must not run"))
19853            .expect("replayed Avro value");
19854        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
19855        assert_eq!(replayed, value);
19856        assert_eq!(replayed_uuid, uuid);
19857        assert!(replay.take_commands().expect("commands").is_empty());
19858    }
19859
19860    #[test]
19861    fn typed_side_effect_replay_preserves_bytes_and_maps() {
19862        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19863        let value = ctx
19864            .side_effect_avro_value(typed_fidelity_probe)
19865            .expect("typed side effect");
19866        let commands = ctx.take_commands().expect("side-effect command");
19867        assert_eq!(
19868            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19869                .expect("recorded side effect"),
19870            value
19871        );
19872
19873        let replay = workflow_context_with_codec(
19874            vec![history_event(
19875                "SideEffectRecorded",
19876                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19877            )],
19878            DEFAULT_CODEC,
19879        );
19880        assert_eq!(
19881            replay
19882                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
19883                .expect("replayed typed side effect"),
19884            value
19885        );
19886    }
19887
19888    #[test]
19889    fn ordered_side_effects_share_the_durable_command_stream() {
19890        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
19891        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
19892        let ctx = workflow_context(vec![
19893            history_event(
19894                "SideEffectRecorded",
19895                json!({"sequence": 1, "result": first}),
19896            ),
19897            history_event(
19898                "SideEffectRecorded",
19899                json!({"sequence": 2, "result": second}),
19900            ),
19901        ]);
19902        let first: String = ctx
19903            .side_effect(|| panic!("first callback must not run"))
19904            .expect("first replay");
19905        let second: i32 = ctx
19906            .side_effect(|| panic!("second callback must not run"))
19907            .expect("second replay");
19908        assert_eq!(first, "first");
19909        assert_eq!(second, 29);
19910        ctx.ensure_history_consumed().expect("ordered history");
19911
19912        let reordered = workflow_context(vec![history_event(
19913            "VersionMarkerRecorded",
19914            json!({
19915                "sequence": 1,
19916                "change_id": "before-side-effect",
19917                "version": 1,
19918                "min_supported": 1,
19919                "max_supported": 1,
19920            }),
19921        )]);
19922        let error = reordered
19923            .side_effect(|| "new".to_string())
19924            .expect_err("command reordering must fail");
19925        assert!(matches!(
19926            error,
19927            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19928                if reason == "recorded_command_mismatch"
19929        ));
19930    }
19931
19932    #[test]
19933    fn legacy_patch_preserves_pending_and_completed_activity_history() {
19934        for completed in [false, true] {
19935            let mut history = vec![history_event(
19936                "ActivityScheduled",
19937                json!({"sequence": 1, "activity_type": "old"}),
19938            )];
19939            if completed {
19940                history.push(history_event(
19941                    "ActivityCompleted",
19942                    json!({
19943                        "sequence": 1,
19944                        "activity_type": "old",
19945                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
19946                    }),
19947                ));
19948            }
19949            for _cold_replay in 0..2 {
19950                let ctx = workflow_context(history.clone());
19951                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
19952                assert!(!ctx.patched("added-step").expect("same frozen decision"));
19953                ctx.deprecate_patch("added-step")
19954                    .expect("retained boundary");
19955                let mut activity = Box::pin(ctx.activity("old", json!([])));
19956                let mut context = TaskContext::from_waker(noop_waker_ref());
19957                match activity.as_mut().poll(&mut context) {
19958                    Poll::Ready(result) => {
19959                        assert!(completed);
19960                        assert_eq!(result.expect("recorded result"), json!(41));
19961                        ctx.ensure_history_consumed().expect("old command retained");
19962                    }
19963                    Poll::Pending => assert!(!completed),
19964                }
19965                assert!(ctx.take_commands().expect("commands").is_empty());
19966            }
19967        }
19968    }
19969
19970    #[test]
19971    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
19972        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
19973        assert!(!ctx.patched("added-step").expect("legacy completed run"));
19974        ctx.deprecate_patch("added-step")
19975            .expect("same legacy decision");
19976        assert!(ctx.take_commands().expect("commands").is_empty());
19977        ctx.ensure_history_consumed().expect("completed history");
19978    }
19979
19980    #[test]
19981    fn legacy_patch_rejects_a_range_without_the_original_branch() {
19982        let ctx = workflow_context(vec![history_event(
19983            "ActivityScheduled",
19984            json!({"sequence": 1, "activity_type": "old"}),
19985        )]);
19986        let error = ctx
19987            .get_version("added-step", 0, 1)
19988            .expect_err("legacy is unsupported");
19989        assert!(matches!(
19990            error,
19991            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19992                if reason == "version_marker_incompatible_range"
19993        ));
19994        assert!(!ctx
19995            .patched("supported-step")
19996            .expect("failed check did not consume history"));
19997        assert!(ctx.take_commands().expect("commands").is_empty());
19998    }
19999
20000    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
20001        let mut event = history_event(
20002            "VersionMarkerRecorded",
20003            json!({
20004                "sequence": sequence,
20005                "change_id": "retained-patch",
20006                "version": version,
20007                "min_supported": -1,
20008                "max_supported": 1,
20009            }),
20010        );
20011        event.raw.insert("timestamp".into(), json!(time));
20012        event
20013    }
20014
20015    #[test]
20016    fn retained_patch_markers_preserve_each_original_boundary() {
20017        for completed in [false, true] {
20018            let mut history = vec![
20019                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20020                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20021                history_event(
20022                    "ActivityScheduled",
20023                    json!({"sequence": 3, "activity_type": "old"}),
20024                ),
20025            ];
20026            if completed {
20027                history.push(history_event(
20028                    "ActivityCompleted",
20029                    json!({
20030                        "sequence": 3,
20031                        "activity_type": "old",
20032                        "result": fixture_envelope(json!(41)),
20033                    }),
20034                ));
20035            }
20036            for _cold_replay in 0..2 {
20037                let ctx = workflow_context(history.clone());
20038                assert!(ctx.patched("retained-patch").unwrap());
20039                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20040                assert!(ctx.patched("retained-patch").unwrap());
20041                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20042                ctx.deprecate_patch("retained-patch").unwrap();
20043                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20044                let mut activity = Box::pin(ctx.activity("old", json!([])));
20045                let mut context = TaskContext::from_waker(noop_waker_ref());
20046                match activity.as_mut().poll(&mut context) {
20047                    Poll::Ready(result) => {
20048                        assert!(completed);
20049                        assert_eq!(result.unwrap(), json!(41));
20050                        ctx.ensure_history_consumed().unwrap();
20051                    }
20052                    Poll::Pending => assert!(!completed),
20053                }
20054                assert!(ctx.take_commands().unwrap().is_empty());
20055                let state = ctx.state.lock().unwrap();
20056                for (actual, original) in state.history_events.iter().zip(&history) {
20057                    assert_eq!(actual.payload, original.payload);
20058                    assert_eq!(actual.raw, original.raw);
20059                }
20060            }
20061        }
20062    }
20063
20064    #[test]
20065    fn retained_patch_aliases_do_not_skip_intervening_operations() {
20066        let ctx = workflow_context(vec![
20067            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20068            history_event(
20069                "SideEffectRecorded",
20070                json!({
20071                    "sequence": 2, "result": fixture_envelope(json!("between")),
20072                }),
20073            ),
20074            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
20075            history_event(
20076                "VersionMarkerRecorded",
20077                json!({
20078                    "sequence": 4, "change_id": "other-patch", "version": 1,
20079                    "min_supported": -1, "max_supported": 1,
20080                }),
20081            ),
20082        ]);
20083        assert!(ctx.patched("retained-patch").unwrap());
20084        assert!(ctx.patched("retained-patch").unwrap());
20085        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20086        assert_eq!(
20087            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20088            "between"
20089        );
20090        ctx.deprecate_patch("retained-patch").unwrap();
20091        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20092        ctx.deprecate_patch("retained-patch").unwrap();
20093        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20094        assert!(ctx.patched("other-patch").unwrap());
20095        ctx.ensure_history_consumed().unwrap();
20096        assert!(ctx.take_commands().unwrap().is_empty());
20097    }
20098
20099    #[test]
20100    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
20101        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20102        alias.payload["max_supported"] = json!(3);
20103        let ctx = workflow_context(vec![
20104            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20105            alias,
20106        ]);
20107        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
20108        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
20109        assert!(matches!(error,
20110            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20111                if reason == "version_marker_incompatible_range"));
20112        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20113        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
20114        ctx.ensure_history_consumed().unwrap();
20115        assert!(ctx.take_commands().unwrap().is_empty());
20116    }
20117
20118    #[test]
20119    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
20120        let ctx = workflow_context(Vec::new());
20121        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
20122        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
20123        assert!(ctx.patched("new-search").expect("patch"));
20124        ctx.deprecate_patch("new-search").expect("deprecate patch");
20125        let commands = ctx.take_commands().expect("commands");
20126        assert_eq!(commands.len(), 2);
20127        assert_eq!(commands[0]["type"], "record_version_marker");
20128        assert_eq!(commands[0]["version"], 2);
20129        assert_eq!(commands[1]["change_id"], "new-search");
20130
20131        let replay = workflow_context(vec![history_event(
20132            "VersionMarkerRecorded",
20133            json!({
20134                "sequence": 1,
20135                "change_id": "checkout-v2",
20136                "version": 2,
20137                "min_supported": 1,
20138                "max_supported": 2,
20139            }),
20140        )]);
20141        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
20142        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
20143        assert!(replay.take_commands().expect("commands").is_empty());
20144        replay.ensure_history_consumed().expect("history consumed");
20145    }
20146
20147    #[test]
20148    fn version_markers_reject_incompatible_or_malformed_history() {
20149        let incompatible = workflow_context(vec![history_event(
20150            "VersionMarkerRecorded",
20151            json!({
20152                "sequence": 1,
20153                "change_id": "checkout-v2",
20154                "version": 1,
20155                "min_supported": 1,
20156                "max_supported": 2,
20157            }),
20158        )]);
20159        let error = incompatible
20160            .get_version("checkout-v2", 2, 3)
20161            .expect_err("old version is unsupported");
20162        assert!(matches!(
20163            error,
20164            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20165                if reason == "version_marker_incompatible_range"
20166        ));
20167
20168        for (history, reason) in [
20169            (
20170                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
20171                "side_effect_result_missing",
20172            ),
20173            (
20174                vec![history_event(
20175                    "SideEffectRecorded",
20176                    json!({
20177                        "sequence": 1,
20178                        "result": {"codec": "avro", "blob": "not-base64"},
20179                    }),
20180                )],
20181                "side_effect_payload_incompatible",
20182            ),
20183            (
20184                vec![history_event(
20185                    "SideEffectRecorded",
20186                    json!({"sequence": 1, "result": {"unwrapped": true}}),
20187                )],
20188                "side_effect_payload_malformed",
20189            ),
20190            (
20191                vec![history_event(
20192                    "VersionMarkerRecorded",
20193                    json!({
20194                        "sequence": 1,
20195                        "change_id": "change",
20196                        "version": 1,
20197                        "min_supported": 2,
20198                        "max_supported": 1,
20199                    }),
20200                )],
20201                "version_marker_history_range_invalid",
20202            ),
20203        ] {
20204            let error = WorkflowState::new(
20205                history,
20206                "rust-workers".to_string(),
20207                DEFAULT_CODEC.to_string(),
20208                None,
20209            )
20210            .expect_err("malformed history must fail");
20211            assert!(matches!(
20212                error,
20213                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
20214                    if actual == reason
20215            ));
20216        }
20217    }
20218
20219    #[test]
20220    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
20221        let history = vec![history_event(
20222            "SearchAttributesUpserted",
20223            json!({
20224                "sequence": 1,
20225                "attributes": {"customer_tier": "gold"},
20226                "attribute_types": {"customer_tier": "keyword"},
20227                "merged": {"customer_tier": "gold"}
20228            }),
20229        )];
20230
20231        let matching = workflow_context(history.clone());
20232        matching
20233            .upsert_search_attributes(
20234                SearchAttributeUpdate::new()
20235                    .keyword("customer_tier", "gold")
20236                    .expect("keyword update"),
20237            )
20238            .expect("matching typed update must replay");
20239        matching
20240            .ensure_history_consumed()
20241            .expect("history consumed");
20242
20243        let changed_type = workflow_context(history.clone());
20244        let error = changed_type
20245            .upsert_search_attributes(
20246                SearchAttributeUpdate::new()
20247                    .string("customer_tier", "gold")
20248                    .expect("string update"),
20249            )
20250            .expect_err("same JSON value with a different declaration must be nondeterministic");
20251        let Error::NonDeterministicReplay(failure) = error else {
20252            panic!("typed identity drift must be a replay failure");
20253        };
20254        assert_eq!(failure.reason, "search_attribute_type_mismatch");
20255        assert_eq!(failure.sequence, Some(1));
20256
20257        let changed_value = workflow_context(history);
20258        let error = changed_value
20259            .upsert_search_attributes(
20260                SearchAttributeUpdate::new()
20261                    .keyword("customer_tier", "platinum")
20262                    .expect("keyword update"),
20263            )
20264            .expect_err("changed values must be nondeterministic");
20265        let Error::NonDeterministicReplay(failure) = error else {
20266            panic!("value drift must be a replay failure");
20267        };
20268        assert_eq!(failure.reason, "search_attribute_value_mismatch");
20269    }
20270
20271    #[test]
20272    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
20273        let history = vec![history_event(
20274            "SearchAttributesUpserted",
20275            json!({
20276                "sequence": 1,
20277                "attributes": {"customer_tier": "gold"},
20278                "merged": {"customer_tier": "gold"}
20279            }),
20280        )];
20281
20282        for update in [
20283            SearchAttributeUpdate::new()
20284                .keyword("customer_tier", "gold")
20285                .expect("keyword update"),
20286            SearchAttributeUpdate::new()
20287                .string("customer_tier", "gold")
20288                .expect("string update"),
20289        ] {
20290            let restarted = workflow_context(history.clone());
20291            restarted
20292                .upsert_search_attributes(update)
20293                .expect("legacy history constrains values but has unknown type identity");
20294            restarted
20295                .ensure_history_consumed()
20296                .expect("history consumed");
20297        }
20298    }
20299
20300    #[test]
20301    fn search_attribute_command_emits_canonical_types() {
20302        let ctx = workflow_context(Vec::new());
20303        ctx.upsert_search_attributes(
20304            SearchAttributeUpdate::new()
20305                .keyword("customer_tier", "gold")
20306                .expect("keyword update")
20307                .int("attempts", 3)
20308                .expect("int update")
20309                .delete("obsolete")
20310                .expect("delete update"),
20311        )
20312        .expect("valid search attributes");
20313
20314        assert_eq!(
20315            ctx.take_commands().expect("commands"),
20316            vec![json!({
20317                "type": "upsert_search_attributes",
20318                "attributes": {
20319                    "attempts": 3,
20320                    "customer_tier": "gold",
20321                    "obsolete": null
20322                },
20323                "attribute_types": {
20324                    "attempts": "int",
20325                    "customer_tier": "keyword"
20326                }
20327            })]
20328        );
20329    }
20330
20331    #[test]
20332    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
20333        let duplicate_side_effect = WorkflowState::new(
20334            vec![
20335                history_event(
20336                    "SideEffectRecorded",
20337                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
20338                ),
20339                history_event(
20340                    "SideEffectRecorded",
20341                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
20342                ),
20343            ],
20344            "rust-workers".to_string(),
20345            DEFAULT_CODEC.to_string(),
20346            None,
20347        )
20348        .expect_err("duplicate side effect");
20349        assert!(matches!(
20350            duplicate_side_effect,
20351            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20352                if reason == "duplicate_side_effect_record"
20353        ));
20354
20355        let marker = |sequence, version| {
20356            history_event(
20357                "VersionMarkerRecorded",
20358                json!({
20359                    "sequence": sequence,
20360                    "change_id": "same-change",
20361                    "version": version,
20362                    "min_supported": -1,
20363                    "max_supported": 1,
20364                }),
20365            )
20366        };
20367        let duplicate_marker = WorkflowState::new(
20368            vec![marker(1, 1), marker(3, -1)],
20369            "rust-workers".to_string(),
20370            DEFAULT_CODEC.to_string(),
20371            None,
20372        )
20373        .expect_err("conflicting marker");
20374        assert!(matches!(
20375            duplicate_marker,
20376            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20377                if reason == "version_marker_conflict"
20378        ));
20379    }
20380
20381    #[test]
20382    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
20383        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
20384        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20385        invalid_alias.payload["max_supported"] = json!(0);
20386        for (history, expected_reason) in [
20387            (
20388                vec![marker.clone(), marker.clone()],
20389                "duplicate_version_marker_record",
20390            ),
20391            (
20392                vec![marker, invalid_alias],
20393                "version_marker_history_range_invalid",
20394            ),
20395        ] {
20396            let error =
20397                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
20398                    .expect_err("invalid historical alias");
20399            assert!(matches!(error,
20400                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
20401                    if reason == expected_reason));
20402        }
20403    }
20404
20405    #[test]
20406    fn retained_patch_aliases_require_the_original_call_boundary() {
20407        let ctx = workflow_context(vec![
20408            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20409            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20410        ]);
20411        assert!(ctx.patched("retained-patch").unwrap());
20412        assert!(ctx.ensure_history_consumed().is_err());
20413        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20414        ctx.deprecate_patch("retained-patch").unwrap();
20415        ctx.ensure_history_consumed().unwrap();
20416        assert!(ctx.take_commands().unwrap().is_empty());
20417    }
20418
20419    #[test]
20420    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
20421        let ctx = workflow_context(vec![
20422            history_event(
20423                "SideEffectRecorded",
20424                json!({
20425                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
20426                }),
20427            ),
20428            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20429        ]);
20430        assert!(!ctx.patched("retained-patch").unwrap());
20431        assert_eq!(
20432            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20433            "old-operation"
20434        );
20435        let error = ctx.patched("retained-patch").unwrap_err();
20436        assert!(matches!(error,
20437            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20438                if reason == "version_marker_conflict"));
20439        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20440        assert!(ctx.take_commands().unwrap().is_empty());
20441    }
20442
20443    #[test]
20444    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
20445        let mut state = WorkflowState::new(
20446            Vec::new(),
20447            "rust-workers".to_string(),
20448            DEFAULT_CODEC.to_string(),
20449            None,
20450        )
20451        .expect("workflow state");
20452        state.workflow_command_identity = "command-7".to_string();
20453        let context = WorkflowContext {
20454            state: Arc::new(Mutex::new(state)),
20455            cancellation_scope_id: "root".into(),
20456        };
20457        let item =
20458            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
20459
20460        context
20461            .append_workflow_stream("output", &[item], Some(10))
20462            .expect("append command");
20463        context
20464            .error_workflow_stream("output", "producer failed", None)
20465            .expect("error command");
20466        let commands = context.take_commands().expect("commands");
20467
20468        assert_eq!(commands[0]["type"], "record_side_effect");
20469        assert_eq!(
20470            commands[0]["workflow_stream"]["command_identity"],
20471            "command-7"
20472        );
20473        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
20474        assert_eq!(
20475            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20476            "dw-stream:command-7:0:0"
20477        );
20478        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
20479
20480        let recorded = history_event(
20481            "SideEffectRecorded",
20482            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
20483        );
20484        let mut replay_state = WorkflowState::new(
20485            vec![recorded],
20486            "rust-workers".to_string(),
20487            DEFAULT_CODEC.to_string(),
20488            None,
20489        )
20490        .expect("replay state");
20491        replay_state.workflow_command_identity = "command-7".to_string();
20492        let replay_context = WorkflowContext {
20493            state: Arc::new(Mutex::new(replay_state)),
20494            cancellation_scope_id: "root".into(),
20495        };
20496        replay_context
20497            .append_workflow_stream(
20498                "output",
20499                &[WorkflowStreamAppendItem::from_reference(
20500                    "s3://bucket/item.avro",
20501                )],
20502                Some(10),
20503            )
20504            .expect("replayed append");
20505        assert!(replay_context
20506            .take_commands()
20507            .expect("replayed commands")
20508            .is_empty());
20509    }
20510
20511    #[test]
20512    fn workflow_stream_authoring_requires_server_durable_command_identity() {
20513        let context = workflow_context(Vec::new());
20514        let error = context
20515            .append_workflow_stream(
20516                "output",
20517                &[WorkflowStreamAppendItem::from_reference(
20518                    "s3://bucket/item.avro",
20519                )],
20520                None,
20521            )
20522            .expect_err("stream append without durable command identity must fail closed");
20523
20524        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
20525        assert!(context.take_commands().expect("commands").is_empty());
20526    }
20527
20528    #[test]
20529    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
20530        let client = Client::builder("http://localhost:8080").build().unwrap();
20531        let mut worker = Worker::new(client, "rust-workers");
20532        worker.register_workflow("streams.worker", |ctx, _| async move {
20533            ctx.append_workflow_stream(
20534                "output",
20535                &[WorkflowStreamAppendItem::new(json!("hello"))?],
20536                None,
20537            )?;
20538            ctx.close_workflow_stream("output", None)?;
20539            Ok(json!("done"))
20540        });
20541        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
20542            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20543            task.workflow_command_id = command_id.clone();
20544            let expected_identity = command_id
20545                .as_deref()
20546                .filter(|id| !id.is_empty())
20547                .unwrap_or(&task.task_id)
20548                .to_string();
20549            let commands = worker
20550                .execute_workflow_task(task)
20551                .expect("ordinary worker stream output");
20552            assert_eq!(commands.len(), 3);
20553            assert_eq!(
20554                commands[0]["workflow_stream"]["command_identity"],
20555                expected_identity
20556            );
20557            assert_eq!(
20558                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20559                format!("dw-stream:{expected_identity}:0:0")
20560            );
20561            assert_eq!(
20562                commands[1]["workflow_stream"]["command_identity"],
20563                expected_identity
20564            );
20565            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
20566            let history = commands[..2]
20567                .iter()
20568                .enumerate()
20569                .map(|(index, command)| {
20570                    history_event(
20571                        "SideEffectRecorded",
20572                        json!({"sequence":index + 1,"result":command["result"]}),
20573                    )
20574                })
20575                .collect();
20576            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
20577            replay.task_id = "replacement-task".to_string();
20578            let replayed = worker
20579                .execute_workflow_task(replay)
20580                .expect("replacement worker consumes recorded stream effects");
20581            assert_eq!(replayed.len(), 1);
20582            assert_eq!(replayed[0]["type"], "complete_workflow");
20583        }
20584        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20585        missing.task_id.clear();
20586        assert!(matches!(
20587            worker.execute_workflow_task(missing),
20588            Err(Error::MissingWorkflowCommandIdentity)
20589        ));
20590    }
20591
20592    #[test]
20593    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
20594        fn worker(calls: Arc<AtomicUsize>) -> Worker {
20595            let client = Client::new("http://127.0.0.1:8080").expect("client");
20596            let mut worker = Worker::new(client, "rust-workers");
20597            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
20598                let calls = Arc::clone(&calls);
20599                async move {
20600                    let captured = ctx.side_effect(|| {
20601                        calls.fetch_add(1, Ordering::SeqCst);
20602                        "captured-once".to_string()
20603                    })?;
20604                    let version = ctx.get_version("cold-restart", 1, 2)?;
20605                    Ok(json!({"captured": captured, "version": version}))
20606                }
20607            });
20608            worker
20609        }
20610
20611        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
20612            WorkflowTask {
20613                task_id: "wft-side-effect-version".to_string(),
20614                observability_context: None,
20615                dispatch_observability_context: None,
20616                observability_links: None,
20617                workflow_command_id: None,
20618                workflow_id: Some("wf-side-effect-version".to_string()),
20619                run_id: Some("run-side-effect-version".to_string()),
20620                workflow_type: "rust.side-effect-version".to_string(),
20621                cancel_requested: false,
20622                payload_codec: DEFAULT_CODEC.to_string(),
20623                arguments: Some(
20624                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
20625                ),
20626                history_events,
20627                total_history_events: None,
20628                history_size_bytes: None,
20629                continue_as_new_recommended: None,
20630                history_budget_pressure: None,
20631                next_history_page_token: None,
20632                workflow_task_attempt: 1,
20633                workflow_signal_id: None,
20634                signal_name: None,
20635                signal_arguments: None,
20636                workflow_update_id: None,
20637                update_name: None,
20638                lease_owner: Some("rust-worker".to_string()),
20639            }
20640        }
20641
20642        let calls = Arc::new(AtomicUsize::new(0));
20643        let initial = worker(Arc::clone(&calls))
20644            .execute_workflow_task(task(Vec::new()))
20645            .expect("initial execution");
20646        assert_eq!(
20647            initial
20648                .iter()
20649                .map(|command| &command["type"])
20650                .collect::<Vec<_>>(),
20651            vec![
20652                "record_side_effect",
20653                "record_version_marker",
20654                "complete_workflow"
20655            ]
20656        );
20657        assert_eq!(calls.load(Ordering::SeqCst), 1);
20658
20659        let restarted = worker(Arc::clone(&calls));
20660        let replayed = restarted
20661            .execute_workflow_task(task(vec![
20662                history_event(
20663                    "SideEffectRecorded",
20664                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
20665                ),
20666                history_event(
20667                    "VersionMarkerRecorded",
20668                    json!({
20669                        "sequence": 2,
20670                        "change_id": "cold-restart",
20671                        "version": 2,
20672                        "min_supported": 1,
20673                        "max_supported": 2,
20674                    }),
20675                ),
20676            ]))
20677            .expect("cold replay");
20678        assert_eq!(replayed.len(), 1);
20679        assert_eq!(replayed[0]["type"], "complete_workflow");
20680        assert_eq!(calls.load(Ordering::SeqCst), 1);
20681    }
20682
20683    #[test]
20684    fn side_effect_replay_rejects_changed_rust_value_type() {
20685        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
20686        let ctx = workflow_context(vec![history_event(
20687            "SideEffectRecorded",
20688            json!({"sequence": 1, "result": result}),
20689        )]);
20690        let error = ctx
20691            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
20692            .expect_err("changed type must fail replay");
20693        assert!(matches!(
20694            error,
20695            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20696                if reason == "side_effect_type_mismatch"
20697        ));
20698    }
20699
20700    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
20701        vec![
20702            history_event(
20703                "ActivityScheduled",
20704                json!({
20705                    "sequence": 1,
20706                    "activity_type": "flaky",
20707                    "activity_execution_id": "act-1",
20708                    "activity": {
20709                        "id": "act-1",
20710                        "sequence": 1,
20711                        "type": "flaky",
20712                        "queue": "critical-activities",
20713                        "execution_mode": null,
20714                        "retry_policy": {
20715                            "snapshot_version": 1,
20716                            "max_attempts": 3,
20717                            "backoff_seconds": [2, 4],
20718                            "start_to_close_timeout": 30,
20719                            "schedule_to_start_timeout": 5,
20720                            "schedule_to_close_timeout": 90,
20721                            "heartbeat_timeout": 10,
20722                            "non_retryable_error_types": ["PermanentError"]
20723                        }
20724                    }
20725                }),
20726            ),
20727            history_event(
20728                "ActivityStarted",
20729                json!({
20730                    "sequence": 1,
20731                    "activity_type": "flaky",
20732                    "activity_execution_id": "act-1",
20733                    "activity_attempt_id": "attempt-1",
20734                    "attempt_number": 1
20735                }),
20736            ),
20737            history_event(
20738                "ActivityRetryScheduled",
20739                json!({
20740                    "sequence": 1,
20741                    "activity_type": "flaky",
20742                    "activity_execution_id": "act-1",
20743                    "activity_attempt_id": "attempt-1",
20744                    "attempt_number": 1,
20745                    "retry_after_attempt": 1,
20746                    "retry_backoff_seconds": 2,
20747                    "failure_category": "activity",
20748                    "exception_type": "TransientError"
20749                }),
20750            ),
20751            history_event(
20752                "ActivityStarted",
20753                json!({
20754                    "sequence": 1,
20755                    "activity_type": "flaky",
20756                    "activity_execution_id": "act-1",
20757                    "activity_attempt_id": "attempt-2",
20758                    "attempt_number": 2
20759                }),
20760            ),
20761            history_event(
20762                "ActivityCompleted",
20763                json!({
20764                    "sequence": 1,
20765                    "activity_type": "flaky",
20766                    "activity_execution_id": "act-1",
20767                    "activity_attempt_id": "attempt-2",
20768                    "attempt_number": 2,
20769                    "payload_codec": DEFAULT_CODEC,
20770                    "result": fixture_envelope(json!({"status":"recovered"}))
20771                }),
20772            ),
20773        ]
20774    }
20775
20776    fn retry_activity_options() -> ActivityOptions {
20777        ActivityOptions::new()
20778            .task_queue("critical-activities")
20779            .retry_policy(
20780                ActivityRetryPolicy::new(3)
20781                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
20782                    .non_retryable_error_type("PermanentError"),
20783            )
20784            .start_to_close_timeout(Duration::from_secs(30))
20785            .schedule_to_start_timeout(Duration::from_secs(5))
20786            .schedule_to_close_timeout(Duration::from_secs(90))
20787            .heartbeat_timeout(Duration::from_secs(10))
20788    }
20789
20790    #[test]
20791    fn fixed_avro_value_round_trips_json_values() {
20792        let value = json!({"greeting": "hello", "count": 3, "ok": true});
20793        let envelope = PayloadEnvelope::avro(&value).expect("encode");
20794        assert_eq!(envelope.codec, DEFAULT_CODEC);
20795        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
20796    }
20797
20798    #[tokio::test]
20799    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
20800        let client = Client::new("http://127.0.0.1:8080").expect("client");
20801        let mut worker = Worker::new(client, "rust-workers");
20802        worker.register_typed_workflow(
20803            "typed.contract.workflow",
20804            |_ctx, input: TypedContract| async move { Ok(input) },
20805        );
20806        worker.register_typed_activity(
20807            "typed.contract.activity",
20808            |_ctx, input: TypedContract| async move { Ok(input) },
20809        );
20810
20811        let expected = typed_contract();
20812        let arguments = AvroValue::Array(vec![
20813            AvroValue::from_serialize(&expected).expect("typed request")
20814        ]);
20815        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
20816        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
20817        workflow.arguments = Some(envelope.clone());
20818        let commands = worker
20819            .execute_workflow_task(workflow)
20820            .expect("typed workflow task");
20821        let workflow_result: TypedContract =
20822            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20823                .expect("workflow result envelope")
20824                .deserialize()
20825                .expect("workflow result type");
20826        assert_eq!(workflow_result, expected);
20827
20828        let activity = ActivityTask {
20829            task_id: "typed-contract-activity".to_string(),
20830            workflow_id: None,
20831            run_id: None,
20832            activity_execution_id: None,
20833            observability_context: None,
20834            dispatch_observability_context: None,
20835            observability_links: None,
20836            activity_attempt_id: Some("typed-contract-attempt".to_string()),
20837            attempt_id: None,
20838            activity_type: "typed.contract.activity".to_string(),
20839            payload_codec: DEFAULT_CODEC.to_string(),
20840            arguments: Some(envelope),
20841            attempt_number: 1,
20842            lease_owner: Some("rust-worker".to_string()),
20843        };
20844        let activity_result: TypedContract = worker
20845            .execute_activity_task(activity)
20846            .await
20847            .expect("typed activity task")
20848            .deserialize()
20849            .expect("activity result type");
20850        assert_eq!(activity_result, expected);
20851    }
20852
20853    #[test]
20854    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
20855        let calls = Arc::new(AtomicUsize::new(0));
20856        let observed = Arc::clone(&calls);
20857        let client = Client::new("http://127.0.0.1:8080").expect("client");
20858        let mut worker = Worker::new(client.clone(), "rust-workers");
20859        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
20860            observed.fetch_add(1, Ordering::SeqCst);
20861            async move { Ok(input) }
20862        });
20863        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
20864        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
20865        let original = task.clone();
20866        let error = worker
20867            .execute_workflow_task(task)
20868            .expect_err("incompatible entry must refuse the task, not fail the run");
20869        assert_eq!(calls.load(Ordering::SeqCst), 0);
20870        assert!(error
20871            .to_string()
20872            .contains("workflow_entry_arguments_mismatch:"));
20873        assert!(!error.to_string().contains("private-original-value"));
20874
20875        let mut compatible = Worker::new(client, "rust-workers");
20876        compatible
20877            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
20878        let commands = compatible
20879            .execute_workflow_task(original)
20880            .expect("same recorded input");
20881        assert_eq!(commands[0]["type"], "complete_workflow");
20882        assert_eq!(
20883            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
20884            json!("private-original-value")
20885        );
20886    }
20887
20888    #[test]
20889    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
20890        let factories = Arc::new(AtomicUsize::new(0));
20891        let observed = Arc::clone(&factories);
20892        let client = Client::new("http://127.0.0.1:8080").expect("client");
20893        let mut worker = Worker::new(client, "rust-workers");
20894        worker.register_typed_replayed_workflow(
20895            "entry.replayed",
20896            move || {
20897                observed.fetch_add(1, Ordering::SeqCst);
20898                ()
20899            },
20900            |_ctx, _input: i64, _state| async move {
20901                panic!("body must not start");
20902                #[allow(unreachable_code)]
20903                Ok(0_i64)
20904            },
20905        );
20906        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
20907        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
20908        let error = worker
20909            .execute_workflow_task(task)
20910            .expect_err("entry refusal");
20911        assert_eq!(factories.load(Ordering::SeqCst), 0);
20912        assert!(error
20913            .to_string()
20914            .contains("workflow_entry_arguments_mismatch:"));
20915        assert!(!error.to_string().contains("private-replayed-value"));
20916
20917        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
20918        let Err(error) = replay(
20919            workflow_context(Vec::new()),
20920            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
20921        ) else {
20922            panic!("query replay must refuse before creating application state");
20923        };
20924        assert_eq!(factories.load(Ordering::SeqCst), 0);
20925        assert!(!error.to_string().contains("private-replayed-value"));
20926    }
20927
20928    #[test]
20929    fn typed_entry_deserializes_once_before_entering_application_code() {
20930        static DECODES: AtomicUsize = AtomicUsize::new(0);
20931        struct Counted(i64);
20932        impl<'de> Deserialize<'de> for Counted {
20933            fn deserialize<D: Deserializer<'de>>(
20934                deserializer: D,
20935            ) -> std::result::Result<Self, D::Error> {
20936                DECODES.fetch_add(1, Ordering::SeqCst);
20937                i64::deserialize(deserializer).map(Self)
20938            }
20939        }
20940        DECODES.store(0, Ordering::SeqCst);
20941        let client = Client::new("http://127.0.0.1:8080").expect("client");
20942        let mut worker = Worker::new(client, "rust-workers");
20943        worker.register_typed_workflow(
20944            "entry.once",
20945            |_ctx, input: Counted| async move { Ok(input.0) },
20946        );
20947        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
20948        task.arguments = Some(fixture_envelope(json!([7])));
20949        let commands = worker.execute_workflow_task(task).expect("typed result");
20950        assert_eq!(commands[0]["type"], "complete_workflow");
20951        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
20952    }
20953
20954    #[test]
20955    fn typed_entry_body_input_error_remains_a_business_failure() {
20956        let client = Client::new("http://127.0.0.1:8080").expect("client");
20957        let mut worker = Worker::new(client, "rust-workers");
20958        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
20959            Err::<i64, _>(handler_type_error::<i64>(
20960                HandlerKind::Workflow,
20961                "entry.body",
20962                HandlerValueKind::Input,
20963                "deliberate body error",
20964            ))
20965        });
20966        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
20967        task.arguments = Some(fixture_envelope(json!([7])));
20968        let commands = worker
20969            .execute_workflow_task(task)
20970            .expect("business failure command");
20971        assert_eq!(commands[0]["type"], "fail_workflow");
20972        assert!(commands[0]["message"]
20973            .as_str()
20974            .unwrap()
20975            .contains("deliberate body error"));
20976    }
20977
20978    #[test]
20979    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
20980        let client = Client::new("http://127.0.0.1:8080").expect("client");
20981        let mut worker = Worker::new(client, "rust-workers");
20982        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
20983            Err::<i64, _>(handler_type_error::<i64>(
20984                HandlerKind::Workflow,
20985                "entry.body.refusal",
20986                HandlerValueKind::Input,
20987                "workflow_entry_arguments_mismatch: deliberate body error",
20988            ))
20989        });
20990        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
20991        task.arguments = Some(fixture_envelope(json!([7])));
20992        let commands = worker
20993            .execute_workflow_task(task)
20994            .expect("business failure");
20995        assert_eq!(commands[0]["type"], "fail_workflow");
20996    }
20997
20998    #[tokio::test]
20999    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
21000        let client = Client::new("http://127.0.0.1:8080").expect("client");
21001        let mut worker = Worker::new(client, "rust-workers");
21002        worker.register_typed_workflow(
21003            "typed.shape.workflow",
21004            |_ctx, input: TypedContract| async move { Ok(input) },
21005        );
21006        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
21007            Ok(f64::NAN)
21008        });
21009
21010        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
21011        workflow.arguments = Some(
21012            encode_typed_envelope(
21013                &AvroValue::Array(vec![
21014                    AvroValue::String("first".to_string()),
21015                    AvroValue::String("second".to_string()),
21016                ]),
21017                DEFAULT_CODEC,
21018            )
21019            .expect("malformed typed arguments"),
21020        );
21021        let error = worker
21022            .execute_workflow_task(workflow)
21023            .expect_err("entry shape mismatch refuses the task");
21024        let message = error.to_string();
21025        assert!(message.contains("workflow_entry_arguments_mismatch:"));
21026        assert!(message.contains("typed.shape.workflow"));
21027        assert!(message.contains(type_name::<TypedContract>()));
21028
21029        let activity = ActivityTask {
21030            task_id: "typed-unsupported-activity".to_string(),
21031            workflow_id: None,
21032            run_id: None,
21033            activity_execution_id: None,
21034            observability_context: None,
21035            dispatch_observability_context: None,
21036            observability_links: None,
21037            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
21038            attempt_id: None,
21039            activity_type: "typed.unsupported.activity".to_string(),
21040            payload_codec: DEFAULT_CODEC.to_string(),
21041            arguments: Some(
21042                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21043                    .expect("unit arguments"),
21044            ),
21045            attempt_number: 1,
21046            lease_owner: Some("rust-worker".to_string()),
21047        };
21048        let Error::HandlerType {
21049            handler_kind,
21050            handler_name,
21051            value_kind,
21052            rust_type,
21053            message,
21054        } = worker
21055            .execute_activity_task(activity)
21056            .await
21057            .expect_err("non-finite handler output must fail")
21058        else {
21059            panic!("expected contextual handler type failure");
21060        };
21061        assert_eq!(handler_kind, HandlerKind::Activity);
21062        assert_eq!(handler_name, "typed.unsupported.activity");
21063        assert_eq!(value_kind, HandlerValueKind::Result);
21064        assert_eq!(rust_type, type_name::<f64>());
21065        assert!(message.contains("non_finite_float"));
21066    }
21067
21068    #[tokio::test]
21069    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
21070        #[derive(Clone, Default)]
21071        struct State {
21072            observed: Option<TypedContract>,
21073        }
21074
21075        let client = Client::new("http://127.0.0.1:8080").expect("client");
21076        let mut worker = Worker::new(client, "rust-workers");
21077        worker.register_typed_replayed_workflow(
21078            "typed.contract.replayed",
21079            State::default,
21080            |ctx, input: TypedContract, state| async move {
21081                let result: TypedContract =
21082                    ctx.activity_typed("typed.contract.activity", input).await?;
21083                state.update(|current| current.observed = Some(result.clone()))?;
21084                Ok(result)
21085            },
21086        );
21087        worker.register_replayed_query::<State, _, _>(
21088            "typed.contract.replayed",
21089            "observed",
21090            |_ctx, state, _args| async move {
21091                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
21092            },
21093        );
21094
21095        let expected = typed_contract();
21096        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
21097        let workflow_arguments =
21098            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
21099                .expect("workflow arguments");
21100        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
21101        let task = QueryTask {
21102            query_task_id: "typed-replay-query".to_string(),
21103            observability_context: None,
21104            dispatch_observability_context: None,
21105            observability_links: None,
21106            query_task_attempt: 1,
21107            lease_owner: Some("rust-worker".to_string()),
21108            workflow_id: Some("typed-replay".to_string()),
21109            run_id: Some("typed-replay-run".to_string()),
21110            workflow_type: "typed.contract.replayed".to_string(),
21111            query_name: "observed".to_string(),
21112            payload_codec: DEFAULT_CODEC.to_string(),
21113            workflow_arguments: Some(workflow_arguments),
21114            query_arguments: Some(
21115                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21116                    .expect("query arguments"),
21117            ),
21118            history_events: vec![
21119                history_event(
21120                    "ActivityScheduled",
21121                    json!({
21122                        "sequence": 1,
21123                        "activity_type": "typed.contract.activity"
21124                    }),
21125                ),
21126                history_event(
21127                    "ActivityCompleted",
21128                    json!({
21129                        "sequence": 1,
21130                        "activity_type": "typed.contract.activity",
21131                        "payload_codec": DEFAULT_CODEC,
21132                        "result": result
21133                    }),
21134                ),
21135            ],
21136            history_export: None,
21137            run_status: Some("completed".to_string()),
21138        };
21139
21140        assert_eq!(
21141            worker
21142                .execute_query_task(task)
21143                .await
21144                .expect("typed replay query")
21145                .deserialize::<i64>()
21146                .expect("query result"),
21147            expected.signed
21148        );
21149    }
21150
21151    #[tokio::test]
21152    async fn update_context_preserves_workflow_input_and_committed_signals() {
21153        let client = Client::new("http://127.0.0.1:8080").expect("client");
21154        let mut worker = Worker::new(client, "rust-workers");
21155        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21156        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
21157        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
21158        let expected_input = workflow_input.clone();
21159        let expected_signals = signal_arguments.clone();
21160        let handler = move |context: QueryContext, arguments: AvroValue| {
21161            let expected_input = expected_input.clone();
21162            let expected_signals = expected_signals.clone();
21163            async move {
21164                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
21165                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
21166                assert_eq!(context.workflow_input_avro_value(), &expected_input);
21167                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
21168                assert_eq!(
21169                    context.signals_avro_value("changed"),
21170                    vec![expected_signals.clone()]
21171                );
21172                assert_eq!(
21173                    context.signals("changed"),
21174                    vec![expected_signals
21175                        .into_iter()
21176                        .map(AvroValue::into_json)
21177                        .collect::<Result<Vec<_>>>()?]
21178                );
21179                assert_eq!(
21180                    context.signal_events()[0].id.as_deref(),
21181                    Some("signal-original")
21182                );
21183                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
21184                Ok(arguments)
21185            }
21186        };
21187        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
21188        worker.register_update_avro_value("snapshot", "inspect", handler);
21189        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
21190        let update_envelope =
21191            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
21192        let mut task = workflow_task(
21193            "snapshot",
21194            vec![
21195                history_event(
21196                    "SignalReceived",
21197                    json!({
21198                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
21199                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
21200                    }),
21201                ),
21202                history_event(
21203                    "UpdateAccepted",
21204                    json!({
21205                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
21206                    }),
21207                ),
21208            ],
21209            DEFAULT_CODEC,
21210        );
21211        task.arguments =
21212            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
21213        task.workflow_update_id = Some("update-original".into());
21214        task.update_name = Some("inspect".into());
21215        let query = QueryTask {
21216            query_task_id: "query-snapshot".into(),
21217            observability_context: None,
21218            dispatch_observability_context: None,
21219            observability_links: None,
21220            query_task_attempt: 1,
21221            lease_owner: None,
21222            workflow_id: task.workflow_id.clone(),
21223            run_id: task.run_id.clone(),
21224            workflow_type: task.workflow_type.clone(),
21225            query_name: "inspect".into(),
21226            payload_codec: DEFAULT_CODEC.into(),
21227            workflow_arguments: task.arguments.clone(),
21228            query_arguments: Some(update_envelope),
21229            history_events: task.history_events.clone(),
21230            history_export: None,
21231            run_status: Some("running".into()),
21232        };
21233        assert_eq!(
21234            worker
21235                .execute_query_task(query)
21236                .await
21237                .expect("query snapshot"),
21238            update_arguments
21239        );
21240        for _ in 0..2 {
21241            let commands = worker
21242                .execute_workflow_task(task.clone())
21243                .expect("cold update snapshot");
21244            assert_eq!(commands[0]["type"], "complete_update");
21245            assert_eq!(commands[0]["update_id"], "update-original");
21246            assert_eq!(
21247                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21248                    .expect("update result"),
21249                update_arguments
21250            );
21251        }
21252    }
21253
21254    #[test]
21255    fn committed_signal_snapshot_counts_identities_once() {
21256        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
21257        let received = history_event(
21258            "SignalReceived",
21259            json!({
21260                "signal_id": "signal-first", "workflow_command_id": "command-first",
21261                "signal_name": "changed", "arguments": arguments.clone(),
21262            }),
21263        );
21264        let applied = history_event(
21265            "SignalApplied",
21266            json!({
21267                "signal_id": "signal-first", "workflow_command_id": "command-first",
21268                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
21269            }),
21270        );
21271        let distinct = history_event(
21272            "SignalReceived",
21273            json!({
21274                "signal_id": "signal-second", "workflow_command_id": "command-second",
21275                "signal_name": "changed", "arguments": arguments,
21276            }),
21277        );
21278        let history = vec![received.clone(), applied.clone(), distinct];
21279        let signals =
21280            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
21281        assert_eq!(signals.len(), 2);
21282        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21283        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
21284        assert_eq!(signals[0].workflow_sequence, Some(1));
21285        assert_eq!(signals[0].arguments, signals[1].arguments);
21286        let mut command_only = received.clone();
21287        command_only
21288            .payload
21289            .as_object_mut()
21290            .expect("payload")
21291            .remove("signal_id");
21292        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
21293            .expect("command identity");
21294        assert_eq!(signals.len(), 1);
21295        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21296        let mut conflicting = applied;
21297        conflicting.payload["value"] =
21298            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
21299        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
21300    }
21301
21302    #[test]
21303    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
21304        for arguments in [
21305            vec![],
21306            vec![AvroValue::Array(vec![
21307                AvroValue::Long(1),
21308                AvroValue::Long(2),
21309            ])],
21310            vec![AvroValue::Bytes(vec![0, 255])],
21311            vec![AvroValue::Null],
21312            vec![AvroValue::Boolean(false)],
21313            vec![
21314                AvroValue::Long(1),
21315                AvroValue::Array(vec![AvroValue::Long(2)]),
21316            ],
21317        ] {
21318            let applied = match arguments.as_slice() {
21319                [] => AvroValue::Boolean(true),
21320                [value] => value.clone(),
21321                values => AvroValue::Array(values.to_vec()),
21322            };
21323            for applied in [applied, AvroValue::Array(arguments.clone())] {
21324                let events = vec![
21325                    history_event(
21326                        "SignalReceived",
21327                        json!({
21328                            "signal_id": "original", "signal_name": "changed",
21329                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
21330                        }),
21331                    ),
21332                    history_event(
21333                        "SignalApplied",
21334                        json!({
21335                            "signal_id": "original", "signal_name": "changed",
21336                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
21337                        }),
21338                    ),
21339                ];
21340                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
21341                    .expect("canonical signal snapshot");
21342                assert_eq!(signals.len(), 1);
21343                assert_eq!(signals[0].avro_arguments, arguments);
21344            }
21345        }
21346    }
21347
21348    #[tokio::test]
21349    async fn update_context_rejects_malformed_snapshot_before_handler() {
21350        let client = Client::new("http://127.0.0.1:8080").expect("client");
21351        let mut worker = Worker::new(client, "rust-workers");
21352        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21353        let calls = Arc::new(AtomicUsize::new(0));
21354        let observed = Arc::clone(&calls);
21355        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
21356            observed.fetch_add(1, Ordering::SeqCst);
21357            async { Ok(Value::Null) }
21358        });
21359        let mut task = workflow_task(
21360            "snapshot",
21361            vec![history_event(
21362                "UpdateAccepted",
21363                json!({
21364                    "update_id": "update-original", "update_name": "inspect",
21365                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
21366                }),
21367            )],
21368            DEFAULT_CODEC,
21369        );
21370        task.workflow_update_id = Some("update-original".into());
21371        task.update_name = Some("inspect".into());
21372        let mut bad_input = task.clone();
21373        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
21374        assert!(worker.execute_workflow_task(bad_input).is_err());
21375        task.history_events.insert(0, history_event("SignalReceived", json!({
21376            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
21377        })));
21378        assert!(worker.execute_workflow_task(task).is_err());
21379        assert_eq!(calls.load(Ordering::SeqCst), 0);
21380    }
21381
21382    #[tokio::test]
21383    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
21384        let client = Client::new("http://127.0.0.1:8080").expect("client");
21385        let mut worker = Worker::new(client, "rust-workers");
21386        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
21387        worker
21388            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
21389        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
21390            Ok(input)
21391        });
21392        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
21393            Ok(input)
21394        });
21395        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
21396            Ok(AvroValue::Array(
21397                ctx.wait_signal_avro_value("changed").await?,
21398            ))
21399        });
21400
21401        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
21402        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
21403
21404        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
21405        workflow.arguments = Some(envelope.clone());
21406        let commands = worker
21407            .execute_workflow_task(workflow)
21408            .expect("typed workflow task");
21409        assert_eq!(commands[0]["type"], "complete_workflow");
21410        assert_eq!(
21411            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21412                .expect("typed workflow result"),
21413            arguments
21414        );
21415
21416        let activity = ActivityTask {
21417            task_id: "activity-typed".to_string(),
21418            workflow_id: None,
21419            run_id: None,
21420            activity_execution_id: None,
21421            observability_context: None,
21422            dispatch_observability_context: None,
21423            observability_links: None,
21424            activity_attempt_id: Some("attempt-typed".to_string()),
21425            attempt_id: None,
21426            activity_type: "typed.activity".to_string(),
21427            payload_codec: DEFAULT_CODEC.to_string(),
21428            arguments: Some(envelope.clone()),
21429            attempt_number: 1,
21430            lease_owner: Some("rust-worker".to_string()),
21431        };
21432        assert_eq!(
21433            worker
21434                .execute_activity_task(activity)
21435                .await
21436                .expect("typed activity result"),
21437            arguments
21438        );
21439
21440        let query = QueryTask {
21441            query_task_id: "query-typed".to_string(),
21442            observability_context: None,
21443            dispatch_observability_context: None,
21444            observability_links: None,
21445            query_task_attempt: 1,
21446            lease_owner: Some("rust-worker".to_string()),
21447            workflow_id: Some("typed-1".to_string()),
21448            run_id: Some("run-typed".to_string()),
21449            workflow_type: "typed.echo".to_string(),
21450            query_name: "inspect".to_string(),
21451            payload_codec: DEFAULT_CODEC.to_string(),
21452            workflow_arguments: Some(
21453                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21454                    .expect("workflow input"),
21455            ),
21456            query_arguments: Some(envelope.clone()),
21457            history_events: Vec::new(),
21458            history_export: None,
21459            run_status: Some("running".to_string()),
21460        };
21461        assert_eq!(
21462            worker
21463                .execute_query_task(query)
21464                .await
21465                .expect("typed query result"),
21466            arguments
21467        );
21468
21469        let mut update = workflow_task(
21470            "typed.echo",
21471            vec![history_event(
21472                "UpdateAccepted",
21473                json!({
21474                    "update_id": "update-typed",
21475                    "update_name": "replace",
21476                    "arguments": envelope.clone(),
21477                }),
21478            )],
21479            DEFAULT_CODEC,
21480        );
21481        update.workflow_update_id = Some("update-typed".to_string());
21482        update.update_name = Some("replace".to_string());
21483        let commands = worker
21484            .execute_workflow_task(update)
21485            .expect("typed update task");
21486        assert_eq!(commands[0]["type"], "complete_update");
21487        assert_eq!(
21488            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21489                .expect("typed update result"),
21490            arguments
21491        );
21492
21493        let mut signal = workflow_task(
21494            "typed.signal",
21495            vec![history_event(
21496                "SignalReceived",
21497                json!({
21498                    "signal_id": "signal-typed",
21499                    "signal_name": "changed",
21500                    "arguments": envelope.clone(),
21501                }),
21502            )],
21503            DEFAULT_CODEC,
21504        );
21505        signal.workflow_signal_id = Some("signal-typed".to_string());
21506        signal.signal_name = Some("changed".to_string());
21507        signal.signal_arguments = Some(envelope);
21508        let commands = worker
21509            .execute_workflow_task(signal)
21510            .expect("typed signal resume");
21511        assert_eq!(
21512            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21513                .expect("typed signal result"),
21514            arguments
21515        );
21516    }
21517
21518    #[tokio::test]
21519    async fn typed_helpers_never_parse_json_inspection_projection() {
21520        let collision_values = projection_collision_probe();
21521        let expected = AvroValue::Array(collision_values.clone());
21522        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
21523
21524        let activity_context = workflow_context_with_codec(
21525            vec![history_event(
21526                "ActivityCompleted",
21527                json!({
21528                    "sequence": 1,
21529                    "activity_type": "collision.activity",
21530                    "payload_codec": DEFAULT_CODEC,
21531                    "result": envelope.clone(),
21532                }),
21533            )],
21534            DEFAULT_CODEC,
21535        );
21536        assert_eq!(
21537            activity_context
21538                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
21539                .await
21540                .expect("typed activity collision result"),
21541            expected
21542        );
21543
21544        let signal_context = workflow_context_with_codec(
21545            vec![
21546                history_event(
21547                    "SignalWaitOpened",
21548                    json!({"sequence": 1, "signal_name": "collision"}),
21549                ),
21550                history_event(
21551                    "SignalApplied",
21552                    json!({
21553                        "sequence": 1,
21554                        "signal_name": "collision",
21555                        "payload_codec": DEFAULT_CODEC,
21556                        "value": envelope.clone(),
21557                    }),
21558                ),
21559            ],
21560            DEFAULT_CODEC,
21561        );
21562        assert_eq!(
21563            signal_context
21564                .wait_signal_avro_value("collision")
21565                .await
21566                .expect("typed signal collision arguments"),
21567            collision_values
21568        );
21569
21570        let child_context = workflow_context_with_codec(
21571            vec![
21572                history_event(
21573                    "ChildWorkflowScheduled",
21574                    json!({
21575                        "sequence": 1,
21576                        "child_workflow_instance_id": "collision-child",
21577                        "child_workflow_run_id": "collision-run",
21578                        "child_workflow_type": "collision.child",
21579                    }),
21580                ),
21581                history_event(
21582                    "ChildRunCompleted",
21583                    json!({
21584                        "sequence": 1,
21585                        "child_workflow_instance_id": "collision-child",
21586                        "child_workflow_run_id": "collision-run",
21587                        "child_workflow_type": "collision.child",
21588                        "payload_codec": DEFAULT_CODEC,
21589                        "result": envelope,
21590                    }),
21591                ),
21592            ],
21593            DEFAULT_CODEC,
21594        );
21595        let child = child_context
21596            .start_child_workflow_avro_value(
21597                "collision.child",
21598                ChildWorkflowOptions::new("collision-workers"),
21599                AvroValue::Array(Vec::new()),
21600            )
21601            .await
21602            .expect("typed child collision result");
21603        assert_eq!(child.result, expected);
21604    }
21605
21606    #[tokio::test]
21607    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
21608        let client = Client::new("http://127.0.0.1:8080").expect("client");
21609        let mut worker = Worker::new(client, "rust-workers");
21610        worker.register_replayed_workflow_avro_value(
21611            "typed.replayed",
21612            || (),
21613            |_ctx, input, _state| async move { Ok(input) },
21614        );
21615        worker.register_replayed_query_avro_value::<(), _, _>(
21616            "typed.replayed",
21617            "inspect",
21618            |ctx, _state, args| async move {
21619                let mut signals = ctx.signals_avro_value("collision");
21620                let signal = signals
21621                    .pop()
21622                    .map(AvroValue::Array)
21623                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
21624                Ok(AvroValue::Array(vec![
21625                    ctx.workflow_input_avro_value().clone(),
21626                    signal,
21627                    args,
21628                ]))
21629            },
21630        );
21631        let arguments = AvroValue::Array(projection_collision_probe());
21632        let signal_arguments =
21633            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
21634        let task = QueryTask {
21635            query_task_id: "query-typed-replay".to_string(),
21636            observability_context: None,
21637            dispatch_observability_context: None,
21638            observability_links: None,
21639            query_task_attempt: 1,
21640            lease_owner: Some("rust-worker".to_string()),
21641            workflow_id: Some("typed-replay".to_string()),
21642            run_id: Some("run-typed-replay".to_string()),
21643            workflow_type: "typed.replayed".to_string(),
21644            query_name: "inspect".to_string(),
21645            payload_codec: DEFAULT_CODEC.to_string(),
21646            workflow_arguments: Some(
21647                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
21648            ),
21649            query_arguments: Some(
21650                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
21651            ),
21652            history_events: vec![history_event(
21653                "SignalReceived",
21654                json!({
21655                    "signal_id": "collision-signal",
21656                    "signal_name": "collision",
21657                    "workflow_sequence": 1,
21658                    "payload_codec": DEFAULT_CODEC,
21659                    "arguments": signal_arguments,
21660                }),
21661            )],
21662            history_export: None,
21663            run_status: Some("completed".to_string()),
21664        };
21665
21666        assert_eq!(
21667            worker
21668                .execute_query_task(task)
21669                .await
21670                .expect("typed replay query"),
21671            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
21672        );
21673    }
21674
21675    #[test]
21676    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
21677        let value = BTreeMap::from([(1_i32, "integer key")]);
21678        let error = PayloadEnvelope::avro(&value)
21679            .expect_err("integer map keys must fail")
21680            .to_string();
21681
21682        assert!(error.contains("invalid_map_key"));
21683    }
21684
21685    #[test]
21686    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
21687        let envelope = PayloadEnvelope {
21688            codec: "json".to_string(),
21689            blob: r#"{"greeting":"hello"}"#.to_string(),
21690        };
21691
21692        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
21693        let diagnostic = error.to_string();
21694        assert!(diagnostic.contains("unsupported_payload_codec"));
21695        assert!(diagnostic.contains("codec=\"avro\""));
21696        assert!(diagnostic.contains("HTTP document transport"));
21697    }
21698
21699    #[test]
21700    fn untagged_json_payload_value_fails_closed() {
21701        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
21702            .expect_err("untagged JSON payload values must fail");
21703        let diagnostic = error.to_string();
21704        assert!(diagnostic.contains("unsupported_payload_codec"));
21705        assert!(diagnostic.contains("untagged durable payload"));
21706        assert!(diagnostic.contains("HTTP document transport"));
21707    }
21708
21709    #[test]
21710    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
21711        let envelope = PayloadEnvelope {
21712            codec: DEFAULT_CODEC.to_string(),
21713            blob: BASE64.encode([0x01]),
21714        };
21715
21716        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
21717        assert!(error.to_string().contains("invalid_payload_framing"));
21718    }
21719
21720    #[tokio::test]
21721    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
21722        let server = MockWorkerServer::start();
21723        let client = Client::builder(server.base_url())
21724            .timeout(Duration::from_secs(2))
21725            .build()
21726            .expect("client");
21727        let invalid_commands = [
21728            json!({
21729                "type": "complete_workflow",
21730                "result": {"codec": "json", "blob": null}
21731            }),
21732            json!({
21733                "type": "schedule_activity",
21734                "arguments": {"codec": "yaml", "blob": "ignored"}
21735            }),
21736            json!({
21737                "type": "start_child_workflow",
21738                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
21739            }),
21740            json!({"type": "continue_as_new", "arguments": []}),
21741            json!({"type": "complete_update"}),
21742            json!({"type": "record_side_effect", "result": null}),
21743            json!({
21744                "type": "start_service_operation",
21745                "payload_codec": DEFAULT_CODEC,
21746                "request_payload": "raw-avro-bytes"
21747            }),
21748        ];
21749
21750        for command in invalid_commands {
21751            let error = client
21752                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
21753                .await
21754                .expect_err("invalid durable payload must fail locally");
21755            let diagnostic = error.to_string();
21756            assert!(
21757                diagnostic.contains("unsupported_payload_codec")
21758                    || diagnostic.contains("invalid_payload_envelope")
21759                    || diagnostic.contains("untagged durable payload"),
21760                "unexpected validation diagnostic: {diagnostic}"
21761            );
21762        }
21763
21764        assert_eq!(
21765            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
21766            0,
21767            "invalid command payloads must not reach HTTP transport"
21768        );
21769    }
21770
21771    #[test]
21772    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
21773        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
21774        let commands = [
21775            json!({"type": "complete_workflow", "result": envelope.clone()}),
21776            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
21777            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
21778            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
21779            json!({"type": "complete_update", "result": envelope.clone()}),
21780            json!({"type": "record_side_effect", "result": envelope.clone()}),
21781            json!({
21782                "type": "start_service_operation",
21783                "payload_codec": DEFAULT_CODEC,
21784                "request_payload": envelope.clone()
21785            }),
21786            json!({
21787                "type": "complete_workflow",
21788                "result": envelope,
21789                "metadata": {
21790                    "codec": "json",
21791                    "payload_codec": "customer-codec",
21792                    "result": {"codec": "yaml", "blob": null}
21793                }
21794            }),
21795        ];
21796
21797        validate_workflow_task_commands(&commands)
21798            .expect("customer metadata must not become a protocol codec declaration");
21799    }
21800
21801    #[test]
21802    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
21803        assert_eq!(
21804            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
21805            AvroValue::Array(Vec::new())
21806        );
21807        assert_eq!(
21808            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
21809            AvroValue::Array(Vec::new())
21810        );
21811
21812        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21813        signal.signal_name = Some("empty-signal".to_string());
21814        signal.signal_arguments = None;
21815        let decoded = decode_resume_signal(&signal)
21816            .expect("valid Avro signal")
21817            .expect("named signal resumes the workflow");
21818        assert!(decoded.arguments.is_empty());
21819    }
21820
21821    #[tokio::test]
21822    async fn malformed_task_level_codecs_become_pre_handler_failures() {
21823        let client = Client::new("http://127.0.0.1:8080").expect("client");
21824        let mut worker = Worker::new(client, "rust-workers");
21825        let handler_calls = Arc::new(AtomicUsize::new(0));
21826
21827        let calls = Arc::clone(&handler_calls);
21828        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21829            calls.fetch_add(1, Ordering::SeqCst);
21830            async move { Ok(Value::Null) }
21831        });
21832        let calls = Arc::clone(&handler_calls);
21833        worker.register_activity("codec.activity", move |_ctx, _args| {
21834            calls.fetch_add(1, Ordering::SeqCst);
21835            async move { Ok(Value::Null) }
21836        });
21837        let calls = Arc::clone(&handler_calls);
21838        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21839            calls.fetch_add(1, Ordering::SeqCst);
21840            async move { Ok(Value::Null) }
21841        });
21842
21843        let mut failures = Vec::new();
21844        for codec_case in [
21845            InvalidTaskPayloadCodec::Missing,
21846            InvalidTaskPayloadCodec::Null,
21847            InvalidTaskPayloadCodec::NonString,
21848        ] {
21849            let mut workflow = json!({
21850                "task_id": format!("workflow-{}", codec_case.label()),
21851                "workflow_type": "codec.workflow"
21852            });
21853            codec_case.apply(&mut workflow);
21854            match serde_json::from_value::<WorkflowTask>(workflow) {
21855                Ok(task) => match worker.execute_workflow_task(task) {
21856                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21857                    outcome => failures.push(format!(
21858                        "workflow {} codec returned {outcome:?}",
21859                        codec_case.label()
21860                    )),
21861                },
21862                Err(error) => failures.push(format!(
21863                    "workflow {} codec failed transport deserialization: {error}",
21864                    codec_case.label()
21865                )),
21866            }
21867
21868            let mut activity = json!({
21869                "task_id": format!("activity-{}", codec_case.label()),
21870                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
21871                "activity_type": "codec.activity",
21872                "attempt_number": 1
21873            });
21874            codec_case.apply(&mut activity);
21875            match serde_json::from_value::<ActivityTask>(activity) {
21876                Ok(task) => match worker.execute_activity_task(task).await {
21877                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21878                    outcome => failures.push(format!(
21879                        "activity {} codec returned {outcome:?}",
21880                        codec_case.label()
21881                    )),
21882                },
21883                Err(error) => failures.push(format!(
21884                    "activity {} codec failed transport deserialization: {error}",
21885                    codec_case.label()
21886                )),
21887            }
21888
21889            let mut query = json!({
21890                "query_task_id": format!("query-{}", codec_case.label()),
21891                "workflow_type": "codec.workflow",
21892                "query_name": "known"
21893            });
21894            codec_case.apply(&mut query);
21895            match serde_json::from_value::<QueryTask>(query) {
21896                Ok(task) => match worker.execute_query_task(task).await {
21897                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
21898                    outcome => failures.push(format!(
21899                        "query {} codec returned {outcome:?}",
21900                        codec_case.label()
21901                    )),
21902                },
21903                Err(error) => failures.push(format!(
21904                    "query {} codec failed transport deserialization: {error}",
21905                    codec_case.label()
21906                )),
21907            }
21908        }
21909
21910        assert!(failures.is_empty(), "{}", failures.join("\n"));
21911        assert_eq!(
21912            handler_calls.load(Ordering::SeqCst),
21913            0,
21914            "invalid task codecs must not invoke a handler"
21915        );
21916    }
21917
21918    #[tokio::test]
21919    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
21920        for codec_case in [
21921            InvalidTaskPayloadCodec::Missing,
21922            InvalidTaskPayloadCodec::Null,
21923            InvalidTaskPayloadCodec::NonString,
21924        ] {
21925            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
21926            let client = Client::builder(server.base_url())
21927                .timeout(Duration::from_secs(2))
21928                .build()
21929                .expect("client");
21930            let mut worker = Worker::new(client, "rust-workers")
21931                .worker_id("codec-worker")
21932                .poll_timeout(Duration::from_millis(10));
21933            let handler_calls = Arc::new(AtomicUsize::new(0));
21934
21935            let calls = Arc::clone(&handler_calls);
21936            worker.register_workflow("codec.workflow", move |_ctx, _args| {
21937                calls.fetch_add(1, Ordering::SeqCst);
21938                async move { Ok(Value::Null) }
21939            });
21940            let calls = Arc::clone(&handler_calls);
21941            worker.register_activity("codec.activity", move |_ctx, _args| {
21942                calls.fetch_add(1, Ordering::SeqCst);
21943                async move { Ok(Value::Null) }
21944            });
21945            let calls = Arc::clone(&handler_calls);
21946            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21947                calls.fetch_add(1, Ordering::SeqCst);
21948                async move { Ok(Value::Null) }
21949            });
21950
21951            assert_eq!(
21952                worker.run_once().await.expect("invalid tasks are settled"),
21953                3,
21954                "all {} codec tasks must be handled",
21955                codec_case.label()
21956            );
21957            assert_eq!(
21958                handler_calls.load(Ordering::SeqCst),
21959                0,
21960                "{} task codecs must fail before every handler",
21961                codec_case.label()
21962            );
21963
21964            for path in [
21965                "/api/worker/workflow-tasks/codec-workflow/fail",
21966                "/api/worker/activity-tasks/codec-activity/fail",
21967                "/api/worker/query-tasks/codec-query/fail",
21968            ] {
21969                let body = server.request_body(path);
21970                assert!(
21971                    body["failure"]["message"]
21972                        .as_str()
21973                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
21974                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
21975                    codec_case.label()
21976                );
21977            }
21978            assert_eq!(
21979                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
21980                    ["reason"],
21981                "query_payload_decode_failed"
21982            );
21983            for path in [
21984                "/api/worker/workflow-tasks/codec-workflow/complete",
21985                "/api/worker/activity-tasks/codec-activity/complete",
21986                "/api/worker/query-tasks/codec-query/complete",
21987            ] {
21988                assert_eq!(
21989                    server.request_count(path),
21990                    0,
21991                    "invalid {} codec task reached {path}",
21992                    codec_case.label()
21993                );
21994            }
21995        }
21996    }
21997
21998    #[tokio::test]
21999    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
22000        let client = Client::new("http://127.0.0.1:8080").expect("client");
22001        let mut worker = Worker::new(client, "rust-workers");
22002        let handler_calls = Arc::new(AtomicUsize::new(0));
22003
22004        let calls = Arc::clone(&handler_calls);
22005        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22006            calls.fetch_add(1, Ordering::SeqCst);
22007            async move { Ok(Value::Null) }
22008        });
22009        let calls = Arc::clone(&handler_calls);
22010        worker.register_activity("codec.activity", move |_ctx, _args| {
22011            calls.fetch_add(1, Ordering::SeqCst);
22012            async move { Ok(Value::Null) }
22013        });
22014        let calls = Arc::clone(&handler_calls);
22015        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
22016            calls.fetch_add(1, Ordering::SeqCst);
22017            async move { Ok(Value::Null) }
22018        });
22019        let calls = Arc::clone(&handler_calls);
22020        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22021            calls.fetch_add(1, Ordering::SeqCst);
22022            async move { Ok(Value::Null) }
22023        });
22024
22025        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22026        workflow.payload_codec = "json".to_string();
22027        workflow.arguments = None;
22028        let error = worker
22029            .execute_workflow_task(workflow)
22030            .expect_err("task codec must be checked before workflow invocation");
22031        assert!(error.to_string().contains("unsupported_payload_codec"));
22032
22033        let activity = ActivityTask {
22034            task_id: "activity-invalid-codec".to_string(),
22035            workflow_id: None,
22036            run_id: None,
22037            activity_execution_id: None,
22038            observability_context: None,
22039            dispatch_observability_context: None,
22040            observability_links: None,
22041            activity_attempt_id: None,
22042            attempt_id: None,
22043            activity_type: "codec.activity".to_string(),
22044            payload_codec: "unknown".to_string(),
22045            arguments: None,
22046            attempt_number: 1,
22047            lease_owner: None,
22048        };
22049        let error = worker
22050            .execute_activity_task(activity)
22051            .await
22052            .expect_err("task codec must be checked before activity invocation");
22053        assert!(error.to_string().contains("unsupported_payload_codec"));
22054
22055        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22056        update.workflow_update_id = Some("update-invalid-codec".to_string());
22057        update.update_name = Some("known".to_string());
22058        update.history_events.push(history_event(
22059            "UpdateAccepted",
22060            json!({
22061                "update_id": "update-invalid-codec",
22062                "update_name": "known",
22063                "arguments": {"codec": "json", "blob": null}
22064            }),
22065        ));
22066        let error = worker
22067            .execute_workflow_task(update)
22068            .expect_err("nested update codec must be checked before handler lookup");
22069        assert!(error.to_string().contains("unsupported_payload_codec"));
22070
22071        let query: QueryTask = serde_json::from_value(json!({
22072            "query_task_id": "query-invalid-codec",
22073            "workflow_type": "codec.workflow",
22074            "query_name": "known",
22075            "payload_codec": DEFAULT_CODEC,
22076            "workflow_arguments": null,
22077            "query_arguments": null,
22078            "history_export": {
22079                "payloads": {"codec": DEFAULT_CODEC},
22080                "signals": [{
22081                    "name": "empty",
22082                    "payload_codec": "json",
22083                    "arguments": null
22084                }]
22085            }
22086        }))
22087        .expect("query task");
22088        let failure = worker
22089            .execute_query_task(query)
22090            .await
22091            .expect_err("exported signal codec must be checked before query invocation");
22092        assert_eq!(failure.reason, "query_payload_decode_failed");
22093        assert!(failure.message.contains("unsupported_payload_codec"));
22094
22095        let exported_history: QueryTask = serde_json::from_value(json!({
22096            "query_task_id": "query-invalid-history-codec",
22097            "workflow_type": "codec.workflow",
22098            "query_name": "known",
22099            "payload_codec": DEFAULT_CODEC,
22100            "history_export": {
22101                "payloads": {"codec": DEFAULT_CODEC},
22102                "history_events": [{
22103                    "type": "ActivityCompleted",
22104                    "payload": {"payload_codec": "unknown", "result": null}
22105                }]
22106            }
22107        }))
22108        .expect("query task");
22109        let failure = worker
22110            .execute_query_task(exported_history)
22111            .await
22112            .expect_err("exported history codec must be checked before query invocation");
22113        assert_eq!(failure.reason, "query_payload_decode_failed");
22114        assert!(failure.message.contains("unsupported_payload_codec"));
22115        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
22116
22117        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22118        unknown_workflow.arguments = None;
22119        unknown_workflow.history_events.push(history_event(
22120            "SignalReceived",
22121            json!({
22122                "signal_name": "empty",
22123                "payload_codec": "json",
22124                "arguments": null
22125            }),
22126        ));
22127        let error = worker
22128            .execute_workflow_task(unknown_workflow)
22129            .expect_err("history codec must precede unknown workflow outcome");
22130        assert!(error.to_string().contains("unsupported_payload_codec"));
22131
22132        let unknown_activity = ActivityTask {
22133            task_id: "activity-unknown".to_string(),
22134            workflow_id: None,
22135            run_id: None,
22136            activity_execution_id: None,
22137            observability_context: None,
22138            dispatch_observability_context: None,
22139            observability_links: None,
22140            activity_attempt_id: None,
22141            attempt_id: None,
22142            activity_type: "missing".to_string(),
22143            payload_codec: "json".to_string(),
22144            arguments: None,
22145            attempt_number: 1,
22146            lease_owner: None,
22147        };
22148        let error = worker
22149            .execute_activity_task(unknown_activity)
22150            .await
22151            .expect_err("codec must precede unknown activity outcome");
22152        assert!(error.to_string().contains("unsupported_payload_codec"));
22153
22154        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22155        unknown_update.payload_codec = "json".to_string();
22156        unknown_update.arguments = None;
22157        unknown_update.workflow_update_id = Some("update-unknown".to_string());
22158        unknown_update.update_name = Some("missing".to_string());
22159        let error = worker
22160            .execute_workflow_task(unknown_update)
22161            .expect_err("codec must precede fail_update shortcut");
22162        assert!(error.to_string().contains("unsupported_payload_codec"));
22163
22164        let unknown_query: QueryTask = serde_json::from_value(json!({
22165            "query_task_id": "query-unknown",
22166            "workflow_type": "missing",
22167            "query_name": "missing",
22168            "payload_codec": "json",
22169            "workflow_arguments": null,
22170            "query_arguments": null
22171        }))
22172        .expect("query task");
22173        let failure = worker
22174            .execute_query_task(unknown_query)
22175            .await
22176            .expect_err("codec must precede unknown query outcome");
22177        assert_eq!(failure.reason, "query_payload_decode_failed");
22178        assert!(failure.message.contains("unsupported_payload_codec"));
22179    }
22180
22181    #[tokio::test]
22182    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
22183        let client = Client::new("http://127.0.0.1:8080").expect("client");
22184        let worker = Worker::new(client, "rust-workers");
22185
22186        for event_type in ["SignalReceived", "SignalApplied"] {
22187            for (payload_field, codec) in [
22188                ("value", "json"),
22189                ("input", "unknown"),
22190                ("arguments", "json"),
22191            ] {
22192                let payload = json!({
22193                    "signal_name": "empty",
22194                    payload_field: {"codec": codec, "blob": null}
22195                });
22196                let workflow = workflow_task(
22197                    "missing",
22198                    vec![history_event(event_type, payload.clone())],
22199                    DEFAULT_CODEC,
22200                );
22201                let error = worker
22202                    .execute_workflow_task(workflow)
22203                    .expect_err("signal payload codec must precede unknown workflow outcome");
22204                assert!(
22205                    error.to_string().contains("unsupported_payload_codec"),
22206                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
22207                );
22208
22209                let query: QueryTask = serde_json::from_value(json!({
22210                    "query_task_id": format!("query-{event_type}-{payload_field}"),
22211                    "workflow_type": "missing",
22212                    "query_name": "missing",
22213                    "payload_codec": DEFAULT_CODEC,
22214                    "workflow_arguments": null,
22215                    "query_arguments": null,
22216                    "history_events": [{
22217                        "event_type": event_type,
22218                        "payload": payload
22219                    }]
22220                }))
22221                .expect("query task");
22222                let failure = worker
22223                    .execute_query_task(query)
22224                    .await
22225                    .expect_err("signal payload codec must precede unknown query outcome");
22226                assert_eq!(
22227                    failure.reason, "query_payload_decode_failed",
22228                    "{event_type}.{payload_field} returned an unrelated query outcome"
22229                );
22230                assert!(
22231                    failure.message.contains("unsupported_payload_codec"),
22232                    "{event_type}.{payload_field} returned an unrelated query error: {}",
22233                    failure.message
22234                );
22235            }
22236        }
22237    }
22238
22239    #[test]
22240    fn workflow_context_schedules_activity_until_completion_is_in_history() {
22241        let ctx = WorkflowContext {
22242            cancellation_scope_id: "root".into(),
22243            state: Arc::new(Mutex::new(
22244                WorkflowState::new_with_identity(
22245                    Vec::new(),
22246                    Some("wf-parent".to_string()),
22247                    Some("run-parent".to_string()),
22248                    "rust-workers".to_string(),
22249                    DEFAULT_CODEC.to_string(),
22250                    None,
22251                )
22252                .expect("workflow state"),
22253            )),
22254        };
22255
22256        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
22257        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22258        assert!(matches!(
22259            call.as_mut().poll(&mut task_context),
22260            Poll::Pending
22261        ));
22262
22263        let commands = ctx.take_commands().expect("commands");
22264        assert_eq!(commands[0]["type"], "schedule_activity");
22265        assert_eq!(commands[0]["activity_type"], "hello.activity");
22266    }
22267
22268    #[test]
22269    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
22270        let ctx = workflow_context(Vec::new());
22271        let options = ActivityOptions::new()
22272            .task_queue("payments")
22273            .retry_policy(
22274                ActivityRetryPolicy::new(4)
22275                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
22276                    .non_retryable_error_type("ValidationError"),
22277            )
22278            .start_to_close_timeout(Duration::from_secs(120))
22279            .schedule_to_start_timeout(Duration::from_secs(10))
22280            .schedule_to_close_timeout(Duration::from_secs(300))
22281            .heartbeat_timeout(Duration::from_secs(15));
22282        let mut call = Box::pin(ctx.activity_with_options(
22283            "charge-card",
22284            options,
22285            json!([{"order_id": "o-1"}]),
22286        ));
22287        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22288
22289        assert!(matches!(
22290            call.as_mut().poll(&mut task_context),
22291            Poll::Pending
22292        ));
22293        assert!(matches!(
22294            call.as_mut().poll(&mut task_context),
22295            Poll::Pending
22296        ));
22297
22298        let commands = ctx.take_commands().expect("activity command");
22299        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
22300        assert_eq!(commands[0]["queue"], "payments");
22301        assert_eq!(
22302            commands[0]["retry_policy"],
22303            json!({
22304                "max_attempts": 4,
22305                "backoff_seconds": [1, 3, 9],
22306                "non_retryable_error_types": ["ValidationError"],
22307            })
22308        );
22309        assert_eq!(commands[0]["start_to_close_timeout"], 120);
22310        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
22311        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
22312        assert_eq!(commands[0]["heartbeat_timeout"], 15);
22313    }
22314
22315    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
22316        vec![
22317            history_event(
22318                "ActivityScheduled",
22319                json!({"sequence":1,"activity_type":"render",
22320                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
22321            ),
22322            history_event(
22323                "ActivityCompleted",
22324                json!({"sequence":1,"activity_type":"render",
22325                "payload_codec":DEFAULT_CODEC,
22326                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
22327            ),
22328        ]
22329    }
22330
22331    #[test]
22332    fn worker_session_activity_routes_to_session_queue_once() {
22333        let ctx = workflow_context(Vec::new());
22334        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22335        let mut call = Box::pin(
22336            ctx.activity("render", json!([]))
22337                .in_worker_session(session.clone()),
22338        );
22339        let mut cx = TaskContext::from_waker(noop_waker_ref());
22340        assert!(call.as_mut().poll(&mut cx).is_pending());
22341        assert!(call.as_mut().poll(&mut cx).is_pending());
22342        let commands = ctx.take_commands().unwrap();
22343        assert_eq!(commands.len(), 1);
22344        assert_eq!(commands[0]["queue"], "gpu-workers");
22345        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
22346    }
22347
22348    #[tokio::test]
22349    async fn worker_session_cold_replay_uses_recorded_avro_result() {
22350        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22351        for _replacement in 0..2 {
22352            let ctx = workflow_context(completed_worker_session_history(&session));
22353            let result: i64 = ctx
22354                .activity("render", json!([]))
22355                .in_worker_session(session.clone())
22356                .typed()
22357                .await
22358                .unwrap();
22359            assert_eq!(result, 42);
22360            assert!(ctx.take_commands().unwrap().is_empty());
22361        }
22362    }
22363
22364    #[test]
22365    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
22366        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22367        for changed in [
22368            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
22369            Some(original.clone().ttl_seconds(60)),
22370            Some(original.clone().requirements(["gpu:l4"])),
22371            None,
22372        ] {
22373            let ctx = workflow_context(completed_worker_session_history(&original));
22374            let mut call = ctx.activity_with_options(
22375                "render",
22376                ActivityOptions::new().task_queue("gpu-workers"),
22377                json!([]),
22378            );
22379            if let Some(changed) = changed {
22380                call = call.in_worker_session(changed);
22381            }
22382            let mut call = Box::pin(call);
22383            let mut cx = TaskContext::from_waker(noop_waker_ref());
22384            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22385                call.as_mut().poll(&mut cx)
22386            else {
22387                panic!("changed session must fail replay");
22388            };
22389            assert_eq!(failure.reason, "activity_worker_session_mismatch");
22390            assert!(ctx.take_commands().unwrap().is_empty());
22391        }
22392    }
22393
22394    #[test]
22395    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
22396        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
22397        let ctx = workflow_context(Vec::new());
22398        let mut local = Box::pin(
22399            ctx.local_activity("render", json!([]))
22400                .in_worker_session(session.clone()),
22401        );
22402        let mut cx = TaskContext::from_waker(noop_waker_ref());
22403        assert!(matches!(
22404            local.as_mut().poll(&mut cx),
22405            Poll::Ready(Err(Error::WorkerLoop(_)))
22406        ));
22407        assert!(ctx.take_commands().unwrap().is_empty());
22408        let mut remote = Box::pin(
22409            ctx.activity_with_options(
22410                "render",
22411                ActivityOptions::new().task_queue("other"),
22412                json!([]),
22413            )
22414            .in_worker_session(session),
22415        );
22416        assert!(matches!(
22417            remote.as_mut().poll(&mut cx),
22418            Poll::Ready(Err(Error::WorkerLoop(_)))
22419        ));
22420        assert!(ctx.take_commands().unwrap().is_empty());
22421    }
22422
22423    #[test]
22424    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
22425        let ctx = workflow_context(Vec::new());
22426        let options = ActivityOptions::new().retry_policy(
22427            ActivityRetryPolicy::new(3)
22428                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
22429        );
22430        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
22431        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22432
22433        assert!(matches!(
22434            call.as_mut().poll(&mut task_context),
22435            Poll::Pending
22436        ));
22437        assert_eq!(
22438            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
22439            json!([1, 2])
22440        );
22441    }
22442
22443    #[test]
22444    fn activity_options_preserve_unused_explicit_backoff_entries() {
22445        for max_attempts in [1, 2, 10] {
22446            let ctx = workflow_context(Vec::new());
22447            let options =
22448                ActivityOptions::new()
22449                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
22450                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
22451                    ));
22452            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
22453            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22454            assert!(matches!(
22455                call.as_mut().poll(&mut task_context),
22456                Poll::Pending
22457            ));
22458            let commands = ctx.take_commands().expect("command");
22459            assert_eq!(commands.len(), 1);
22460            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
22461            assert_eq!(
22462                commands[0]["retry_policy"]["backoff_seconds"],
22463                json!([1, 2, 5, 10, 15, 30, 60, 120])
22464            );
22465        }
22466        let default_options = ActivityOptions::new().validate().expect("default options");
22467        let default_policy = current_activity_retry_snapshot(&default_options);
22468        assert_eq!(
22469            default_policy.max_attempts,
22470            RecordedSnapshotValue::Known(Some(1))
22471        );
22472        assert_eq!(
22473            default_policy.backoff_seconds,
22474            RecordedSnapshotValue::Known(Vec::new())
22475        );
22476    }
22477
22478    #[test]
22479    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
22480        let fixture: Value = serde_json::from_str(include_str!(
22481            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
22482        ))
22483        .expect("published PHP fixture");
22484        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
22485            .expect("unchanged published history");
22486        let matching = ActivityOptions::new().task_queue("default").retry_policy(
22487            ActivityRetryPolicy::new(1)
22488                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
22489        );
22490        let mut changed_tail = matching.clone();
22491        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
22492            [1, 2, 5, 10, 15, 30, 60, 121]
22493                .map(Duration::from_secs)
22494                .to_vec(),
22495        ));
22496        let mut changed_first = matching.clone();
22497        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
22498            [2, 2, 5, 10, 15, 30, 60, 120]
22499                .map(Duration::from_secs)
22500                .to_vec(),
22501        ));
22502        let mut changed_attempts = matching.clone();
22503        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
22504        let mut changed_types = matching.clone();
22505        changed_types
22506            .retry_policy
22507            .as_mut()
22508            .unwrap()
22509            .non_retryable_error_types = vec!["ChangedError".into()];
22510        let mut changed_start = matching.clone();
22511        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
22512        let mut changed_schedule_start = matching.clone();
22513        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
22514        let mut changed_schedule_close = matching.clone();
22515        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
22516        let mut changed_heartbeat = matching;
22517        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
22518        let unchanged_defaults = ActivityOptions::new().task_queue("default");
22519        for options in [
22520            changed_tail,
22521            changed_first,
22522            changed_attempts,
22523            changed_types,
22524            changed_start,
22525            changed_schedule_start,
22526            changed_schedule_close,
22527            changed_heartbeat,
22528            unchanged_defaults,
22529        ] {
22530            let ctx = workflow_context(history.clone());
22531            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
22532            assert!(!ctx.patched("frozen-zero").unwrap());
22533            ctx.deprecate_patch("frozen-zero").unwrap();
22534            let mut call =
22535                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
22536            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22537            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22538                call.as_mut().poll(&mut task_context)
22539            else {
22540                panic!("changed explicit policy must fail replay")
22541            };
22542            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
22543            assert_eq!(failure.sequence, Some(2));
22544            assert!(ctx.take_commands().unwrap().is_empty());
22545        }
22546    }
22547
22548    #[test]
22549    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
22550        let cases = [
22551            (
22552                ActivityOptions::new().task_queue("  "),
22553                ActivityOptionsErrorKind::EmptyTaskQueue,
22554            ),
22555            (
22556                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
22557                ActivityOptionsErrorKind::EmptyRetryPolicy,
22558            ),
22559            (
22560                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
22561                ActivityOptionsErrorKind::InvalidMaxAttempts,
22562            ),
22563            (
22564                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
22565                    max_attempts: None,
22566                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
22567                    non_retryable_error_types: Vec::new(),
22568                }),
22569                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
22570            ),
22571            (
22572                ActivityOptions::new().retry_policy(
22573                    ActivityRetryPolicy::new(2).exponential_backoff(
22574                        Duration::from_secs(1),
22575                        0,
22576                        None,
22577                    ),
22578                ),
22579                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
22580            ),
22581            (
22582                ActivityOptions::new()
22583                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
22584                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
22585            ),
22586            (
22587                ActivityOptions::new().retry_policy(
22588                    ActivityRetryPolicy::new(10_002).exponential_backoff(
22589                        Duration::from_secs(1),
22590                        1,
22591                        None,
22592                    ),
22593                ),
22594                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
22595            ),
22596            (
22597                ActivityOptions::new().retry_policy(
22598                    ActivityRetryPolicy::new(2)
22599                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
22600                ),
22601                ActivityOptionsErrorKind::BackoffOverflow,
22602            ),
22603        ];
22604
22605        for (options, expected_kind) in cases {
22606            let ctx = workflow_context(Vec::new());
22607            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
22608            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22609            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
22610                call.as_mut().poll(&mut task_context)
22611            else {
22612                panic!("expected typed activity validation error");
22613            };
22614            assert_eq!(error.kind, expected_kind);
22615            assert!(ctx.take_commands().expect("commands").is_empty());
22616        }
22617    }
22618
22619    #[test]
22620    fn activity_options_validate_positive_and_ordered_timeouts() {
22621        let zero_timeout_cases = [
22622            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
22623            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
22624            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
22625            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
22626        ];
22627        for options in zero_timeout_cases {
22628            assert_eq!(
22629                options.validate().expect_err("zero timeout").kind,
22630                ActivityOptionsErrorKind::TimeoutNotPositive
22631            );
22632        }
22633
22634        let ordering_cases = [
22635            ActivityOptions::new()
22636                .heartbeat_timeout(Duration::from_secs(11))
22637                .start_to_close_timeout(Duration::from_secs(10)),
22638            ActivityOptions::new()
22639                .start_to_close_timeout(Duration::from_secs(31))
22640                .schedule_to_close_timeout(Duration::from_secs(30)),
22641            ActivityOptions::new()
22642                .schedule_to_start_timeout(Duration::from_secs(31))
22643                .schedule_to_close_timeout(Duration::from_secs(30)),
22644        ];
22645        for options in ordering_cases {
22646            assert_eq!(
22647                options.validate().expect_err("timeout order").kind,
22648                ActivityOptionsErrorKind::TimeoutOrder
22649            );
22650        }
22651
22652        assert_eq!(
22653            ActivityOptions::new()
22654                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
22655                .validate()
22656                .expect_err("protocol integer overflow")
22657                .kind,
22658            ActivityOptionsErrorKind::TimeoutOverflow
22659        );
22660    }
22661
22662    #[test]
22663    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
22664        let ctx = workflow_context(completed_retry_activity_history());
22665        let mut call =
22666            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22667        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22668
22669        assert!(matches!(
22670            call.as_mut().poll(&mut task_context),
22671            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22672        ));
22673        assert!(ctx.take_commands().expect("commands").is_empty());
22674        ctx.ensure_history_consumed().expect("history consumed");
22675    }
22676
22677    #[test]
22678    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
22679        let mut options = retry_activity_options();
22680        options
22681            .retry_policy
22682            .as_mut()
22683            .expect("retry policy")
22684            .non_retryable_error_types
22685            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
22686
22687        let new_ctx = workflow_context(Vec::new());
22688        let mut new_call =
22689            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
22690        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22691        assert!(matches!(
22692            new_call.as_mut().poll(&mut task_context),
22693            Poll::Pending
22694        ));
22695        let commands = new_ctx.take_commands().expect("commands");
22696        assert_eq!(commands.len(), 1);
22697        assert_eq!(
22698            commands[0]["retry_policy"]["non_retryable_error_types"],
22699            json!(["PermanentError"])
22700        );
22701
22702        let replay_ctx = workflow_context(completed_retry_activity_history());
22703        let mut replay_call =
22704            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
22705        assert!(matches!(
22706            replay_call.as_mut().poll(&mut task_context),
22707            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22708        ));
22709        assert!(replay_ctx.take_commands().expect("commands").is_empty());
22710        replay_ctx
22711            .ensure_history_consumed()
22712            .expect("history consumed");
22713    }
22714
22715    #[test]
22716    fn replayed_intermediate_retry_remains_pending_across_restarts() {
22717        let history = completed_retry_activity_history()
22718            .into_iter()
22719            .take(3)
22720            .collect::<Vec<_>>();
22721
22722        for _restart in 0..2 {
22723            let ctx = workflow_context(history.clone());
22724            let mut call =
22725                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22726            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22727            assert!(matches!(
22728                call.as_mut().poll(&mut task_context),
22729                Poll::Pending
22730            ));
22731            assert!(ctx.take_commands().expect("commands").is_empty());
22732        }
22733    }
22734
22735    #[test]
22736    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
22737        let mut changed_queue = retry_activity_options();
22738        changed_queue.task_queue = Some("different-queue".to_string());
22739
22740        let mut changed_max_attempts = retry_activity_options();
22741        let retry_policy = changed_max_attempts
22742            .retry_policy
22743            .as_mut()
22744            .expect("retry policy");
22745        retry_policy.max_attempts = Some(4);
22746
22747        let mut changed_backoff = retry_activity_options();
22748        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
22749        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
22750            Duration::from_secs(3),
22751            Duration::from_secs(4),
22752        ]));
22753
22754        let mut changed_non_retryable_types = retry_activity_options();
22755        let retry_policy = changed_non_retryable_types
22756            .retry_policy
22757            .as_mut()
22758            .expect("retry policy");
22759        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
22760
22761        let mut changed_start_to_close = retry_activity_options();
22762        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
22763        let mut changed_schedule_to_start = retry_activity_options();
22764        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
22765        let mut changed_schedule_to_close = retry_activity_options();
22766        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
22767        let mut changed_heartbeat = retry_activity_options();
22768        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
22769
22770        let cases = [
22771            (changed_queue, "activity_task_queue_mismatch"),
22772            (changed_max_attempts, "activity_retry_policy_mismatch"),
22773            (changed_backoff, "activity_retry_policy_mismatch"),
22774            (
22775                changed_non_retryable_types,
22776                "activity_retry_policy_mismatch",
22777            ),
22778            (changed_start_to_close, "activity_retry_policy_mismatch"),
22779            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
22780            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
22781            (changed_heartbeat, "activity_retry_policy_mismatch"),
22782        ];
22783
22784        for (options, expected_reason) in cases {
22785            let ctx = workflow_context(completed_retry_activity_history());
22786            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
22787            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22788            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22789                call.as_mut().poll(&mut task_context)
22790            else {
22791                panic!("changed activity options must fail replay");
22792            };
22793            assert_eq!(failure.reason, expected_reason);
22794            assert_eq!(failure.sequence, Some(1));
22795            assert!(ctx.take_commands().expect("commands").is_empty());
22796        }
22797    }
22798
22799    #[test]
22800    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
22801        let cases = [
22802            (
22803                "execution_mode",
22804                json!("local"),
22805                "activity_execution_mode_mismatch",
22806            ),
22807            (
22808                "snapshot_version",
22809                json!(2),
22810                "activity_retry_policy_mismatch",
22811            ),
22812        ];
22813
22814        for (field, value, expected_reason) in cases {
22815            let mut history = completed_retry_activity_history();
22816            let activity = history[0].payload["activity"]
22817                .as_object_mut()
22818                .expect("activity snapshot");
22819            if field == "execution_mode" {
22820                activity.insert(field.to_string(), value);
22821            } else {
22822                activity["retry_policy"]
22823                    .as_object_mut()
22824                    .expect("retry snapshot")
22825                    .insert(field.to_string(), value);
22826            }
22827
22828            let ctx = workflow_context(history);
22829            let mut call =
22830                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22831            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22832            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22833                call.as_mut().poll(&mut task_context)
22834            else {
22835                panic!("changed {field} must fail replay");
22836            };
22837            assert_eq!(failure.reason, expected_reason);
22838            assert_eq!(failure.sequence, Some(1));
22839            assert!(ctx.take_commands().expect("commands").is_empty());
22840        }
22841    }
22842
22843    #[test]
22844    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
22845        for (nested, field, value, terminal_only) in [
22846            (false, "execution_mode", json!("local"), false),
22847            (false, "local_activity", json!(true), false),
22848            (true, "local_activity", json!(true), false),
22849            (false, "local_activity", json!(true), true),
22850        ] {
22851            let mut history = completed_retry_activity_history();
22852            history[0]
22853                .payload
22854                .as_object_mut()
22855                .unwrap()
22856                .remove("activity");
22857            let event = if terminal_only {
22858                history.last_mut().unwrap()
22859            } else {
22860                &mut history[0]
22861            };
22862            if nested {
22863                event.payload["activity"] = json!({(field): value});
22864            } else {
22865                event.payload[field] = value;
22866            }
22867            let ctx = workflow_context(history);
22868            let mut call =
22869                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22870            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22871            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22872                call.as_mut().poll(&mut task_context)
22873            else {
22874                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
22875            };
22876            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
22877            assert_eq!(failure.sequence, Some(1));
22878            assert!(ctx.take_commands().expect("commands").is_empty());
22879        }
22880    }
22881
22882    #[test]
22883    fn activity_history_rejects_conflicting_local_execution_markers() {
22884        let mut history = completed_retry_activity_history();
22885        history.last_mut().unwrap().payload["local_activity"] = json!(true);
22886        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
22887            .expect_err("remote schedule cannot become a local completion");
22888        assert!(
22889            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
22890            if reason == "activity_execution_mode_conflict")
22891        );
22892    }
22893
22894    #[test]
22895    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
22896        let mut history = completed_retry_activity_history();
22897        let activity = history[0].payload["activity"]
22898            .as_object_mut()
22899            .expect("activity snapshot");
22900        activity.remove("execution_mode");
22901        activity.remove("retry_policy");
22902
22903        let mut current = retry_activity_options();
22904        current.start_to_close_timeout = Some(Duration::from_secs(45));
22905        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
22906        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
22907        current.heartbeat_timeout = Some(Duration::from_secs(12));
22908
22909        let ctx = workflow_context(history);
22910        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
22911        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22912        assert!(matches!(
22913            call.as_mut().poll(&mut task_context),
22914            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22915        ));
22916        assert!(ctx.take_commands().expect("commands").is_empty());
22917        ctx.ensure_history_consumed().expect("history consumed");
22918    }
22919
22920    #[test]
22921    fn terminal_activity_failed_after_start_returns_typed_failure() {
22922        let history = vec![
22923            history_event(
22924                "ActivityScheduled",
22925                json!({
22926                    "sequence": 1,
22927                    "activity_type": "flaky",
22928                    "activity_execution_id": "act-terminal",
22929                    "activity": {
22930                        "id": "act-terminal",
22931                        "sequence": 1,
22932                        "type": "flaky",
22933                        "queue": "critical-activities",
22934                        "retry_policy": {
22935                            "snapshot_version": 1,
22936                            "max_attempts": 3,
22937                            "backoff_seconds": [2, 4],
22938                            "non_retryable_error_types": ["PermanentError"]
22939                        }
22940                    }
22941                }),
22942            ),
22943            history_event(
22944                "ActivityStarted",
22945                json!({
22946                    "sequence": 1,
22947                    "activity_type": "flaky",
22948                    "activity_execution_id": "act-terminal",
22949                    "activity_attempt_id": "attempt-1",
22950                    "attempt_number": 1
22951                }),
22952            ),
22953            history_event(
22954                "ActivityFailed",
22955                json!({
22956                    "sequence": 1,
22957                    "activity_type": "flaky",
22958                    "activity_execution_id": "act-terminal",
22959                    "activity_attempt_id": "attempt-1",
22960                    "attempt_number": 1,
22961                    "failure_id": "failure-terminal",
22962                    "failure_category": "activity",
22963                    "exception_type": "PermanentError",
22964                    "message": "cannot retry",
22965                    "non_retryable": true
22966                }),
22967            ),
22968        ];
22969        let ctx = workflow_context(history);
22970        let mut call =
22971            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22972        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22973
22974        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22975            call.as_mut().poll(&mut task_context)
22976        else {
22977            panic!("terminal ActivityFailed must settle the activity future");
22978        };
22979        assert_eq!(failure.kind, ActivityFailureKind::Failed);
22980        assert_eq!(
22981            failure.activity_execution_id.as_deref(),
22982            Some("act-terminal")
22983        );
22984        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
22985        assert!(failure.non_retryable);
22986        assert!(ctx.take_commands().expect("commands").is_empty());
22987        ctx.ensure_history_consumed().expect("history consumed");
22988    }
22989
22990    #[test]
22991    fn activity_terminal_events_return_machine_readable_failures() {
22992        let cases = [
22993            (
22994                "ActivityFailed",
22995                json!({
22996                    "sequence": 1,
22997                    "activity_type": "charge-card",
22998                    "activity_execution_id": "act-1",
22999                    "activity_attempt_id": "attempt-2",
23000                    "attempt_number": 2,
23001                    "failure_id": "failure-1",
23002                    "failure_category": "activity",
23003                    "exception_type": "PaymentDeclined",
23004                    "exception_class": "payments.PaymentDeclined",
23005                    "message": "card declined",
23006                    "non_retryable": true
23007                }),
23008                ActivityFailureKind::Failed,
23009                "activity",
23010            ),
23011            (
23012                "ActivityCancelled",
23013                json!({
23014                    "sequence": 1,
23015                    "activity_type": "charge-card",
23016                    "activity_execution_id": "act-1",
23017                    "activity_attempt_id": "attempt-1"
23018                }),
23019                ActivityFailureKind::Cancelled,
23020                "cancelled",
23021            ),
23022        ];
23023
23024        for (event_type, payload, expected_kind, expected_reason) in cases {
23025            let ctx = workflow_context(vec![history_event(event_type, payload)]);
23026            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
23027            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23028            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23029                call.as_mut().poll(&mut task_context)
23030            else {
23031                panic!("expected terminal activity failure");
23032            };
23033            assert_eq!(failure.kind, expected_kind);
23034            assert_eq!(failure.reason, expected_reason);
23035            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
23036            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
23037        }
23038    }
23039
23040    #[test]
23041    fn every_activity_timeout_class_is_typed() {
23042        for timeout_kind in [
23043            "start_to_close",
23044            "schedule_to_start",
23045            "schedule_to_close",
23046            "heartbeat",
23047        ] {
23048            let ctx = workflow_context(vec![history_event(
23049                "ActivityTimedOut",
23050                json!({
23051                    "sequence": 1,
23052                    "activity_type": "slow",
23053                    "activity_execution_id": "act-timeout",
23054                    "activity_attempt_id": "attempt-timeout",
23055                    "failure_category": "timeout",
23056                    "timeout_kind": timeout_kind,
23057                    "message": "deadline expired"
23058                }),
23059            )]);
23060            let mut call = Box::pin(ctx.activity("slow", json!([])));
23061            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23062            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23063                call.as_mut().poll(&mut task_context)
23064            else {
23065                panic!("expected timeout failure");
23066            };
23067            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
23068            assert_eq!(failure.reason, timeout_kind);
23069            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
23070            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
23071        }
23072    }
23073
23074    #[test]
23075    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
23076        let ctx = workflow_context(Vec::new());
23077        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
23078        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23079
23080        assert!(matches!(
23081            sleep.as_mut().poll(&mut task_context),
23082            Poll::Pending
23083        ));
23084        assert!(matches!(
23085            sleep.as_mut().poll(&mut task_context),
23086            Poll::Pending
23087        ));
23088
23089        let commands = ctx.take_commands().expect("timer command");
23090        assert_eq!(
23091            commands,
23092            vec![json!({
23093                "type": "start_timer",
23094                "delay_seconds": 2,
23095            })]
23096        );
23097    }
23098
23099    #[test]
23100    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
23101        let history = vec![
23102            history_event(
23103                "TimerScheduled",
23104                json!({
23105                    "sequence": 1,
23106                    "timer_id": "timer-1",
23107                    "delay_seconds": 5,
23108                    "fire_at": "2026-07-11T12:00:05Z",
23109                }),
23110            ),
23111            history_event(
23112                "TimerFired",
23113                json!({
23114                    "sequence": 1,
23115                    "timer_id": "timer-1",
23116                    "delay_seconds": 5,
23117                    "fire_at": "2026-07-11T12:00:05Z",
23118                    "fired_at": "2026-07-11T12:00:05Z",
23119                }),
23120            ),
23121        ];
23122
23123        for _restart in 0..2 {
23124            let ctx = workflow_context(history.clone());
23125            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
23126            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23127            assert!(matches!(
23128                sleep.as_mut().poll(&mut task_context),
23129                Poll::Ready(Ok(()))
23130            ));
23131            assert!(ctx.take_commands().expect("commands").is_empty());
23132            ctx.ensure_history_consumed().expect("history consumed");
23133        }
23134    }
23135
23136    #[test]
23137    fn workflow_sleep_rejects_changed_delay_during_replay() {
23138        let ctx = workflow_context(vec![
23139            history_event(
23140                "TimerScheduled",
23141                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23142            ),
23143            history_event(
23144                "TimerFired",
23145                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23146            ),
23147        ]);
23148        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
23149        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23150
23151        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23152            sleep.as_mut().poll(&mut task_context)
23153        else {
23154            panic!("changed timer delay must be rejected");
23155        };
23156        assert_eq!(failure.reason, "timer_delay_mismatch");
23157        assert_eq!(failure.sequence, Some(1));
23158    }
23159
23160    #[test]
23161    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
23162        let ctx = workflow_context(Vec::new());
23163        let mut wait = Box::pin(
23164            ctx.wait_condition(
23165                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
23166                    .timeout(Duration::from_millis(60_001)),
23167                || Ok(false),
23168            ),
23169        );
23170        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23171
23172        assert!(matches!(
23173            wait.as_mut().poll(&mut task_context),
23174            Poll::Pending
23175        ));
23176        assert!(matches!(
23177            wait.as_mut().poll(&mut task_context),
23178            Poll::Pending
23179        ));
23180        assert_eq!(
23181            ctx.take_commands().expect("condition command"),
23182            vec![json!({
23183                "type": "open_condition_wait",
23184                "condition_wait_occurrence_id": "rust:condition-wait:0",
23185                "condition_key": "approval.ready",
23186                "condition_definition_fingerprint": "sha256:approval-v1",
23187                "timeout_seconds": 61,
23188            })]
23189        );
23190    }
23191
23192    #[test]
23193    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
23194        let ctx = workflow_context(Vec::new());
23195        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
23196        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23197        assert!(matches!(
23198            satisfied.as_mut().poll(&mut task_context),
23199            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23200        ));
23201
23202        let mut timed_out = Box::pin(wait_condition!(
23203            ctx,
23204            "no-wait",
23205            timeout: Duration::ZERO,
23206            || Ok(false),
23207        ));
23208        assert!(matches!(
23209            timed_out.as_mut().poll(&mut task_context),
23210            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
23211        ));
23212        assert!(ctx.take_commands().expect("commands").is_empty());
23213    }
23214
23215    #[test]
23216    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
23217        let signal_history = vec![
23218            history_event(
23219                "ConditionWaitOpened",
23220                json!({
23221                    "sequence": 4,
23222                    "condition_wait_id": "condition:4",
23223                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23224                    "condition_key": "approval",
23225                    "condition_definition_fingerprint": "sha256:approval-v1",
23226                    "timeout_seconds": 30,
23227                }),
23228            ),
23229            history_event(
23230                "SignalReceived",
23231                json!({
23232                    "workflow_sequence": 4,
23233                    "signal_name": "approve",
23234                    "arguments": fixture_envelope(json!(["Ada"])),
23235                }),
23236            ),
23237        ];
23238        for _worker_before_or_after_restart in 0..2 {
23239            let ctx = workflow_context(signal_history.clone());
23240            let predicate_ctx = ctx.clone();
23241            let mut wait = Box::pin(
23242                ctx.wait_condition(
23243                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
23244                        .timeout(Duration::from_secs(30)),
23245                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
23246                ),
23247            );
23248            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23249            assert!(matches!(
23250                wait.as_mut().poll(&mut task_context),
23251                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23252            ));
23253            assert!(ctx.take_commands().expect("commands").is_empty());
23254            ctx.ensure_history_consumed().expect("condition consumed");
23255        }
23256
23257        let update_history = vec![
23258            history_event(
23259                "ConditionWaitOpened",
23260                json!({
23261                    "sequence": 7,
23262                    "condition_wait_id": "condition:7",
23263                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23264                    "condition_key": "update-approval",
23265                    "condition_definition_fingerprint": "sha256:update-approval-v1",
23266                }),
23267            ),
23268            history_event(
23269                "UpdateApplied",
23270                json!({
23271                    "sequence": 7,
23272                    "update_id": "update-1",
23273                    "update_name": "approve",
23274                    "arguments": fixture_envelope(json!([true])),
23275                }),
23276            ),
23277        ];
23278        let ctx = workflow_context(update_history);
23279        let predicate_ctx = ctx.clone();
23280        let mut wait = Box::pin(ctx.wait_condition(
23281            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
23282            move || {
23283                Ok(predicate_ctx
23284                    .updates("approve")?
23285                    .first()
23286                    .and_then(|arguments| arguments.first())
23287                    .and_then(Value::as_bool)
23288                    == Some(true))
23289            },
23290        ));
23291        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23292        assert!(matches!(
23293            wait.as_mut().poll(&mut task_context),
23294            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23295        ));
23296        assert!(ctx.take_commands().expect("commands").is_empty());
23297        ctx.ensure_history_consumed().expect("condition consumed");
23298    }
23299
23300    #[test]
23301    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
23302        let open_history = vec![
23303            history_event(
23304                "ConditionWaitOpened",
23305                json!({
23306                    "sequence": 3,
23307                    "condition_wait_id": "condition:3",
23308                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23309                    "condition_key": "two-votes",
23310                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23311                    "timeout_seconds": 120,
23312                }),
23313            ),
23314            history_event(
23315                "SignalReceived",
23316                json!({
23317                    "workflow_sequence": 3,
23318                    "signal_name": "vote",
23319                    "arguments": fixture_envelope(json!(["first"])),
23320                }),
23321            ),
23322        ];
23323        for _worker_before_or_after_restart in 0..2 {
23324            let ctx = workflow_context(open_history.clone());
23325            let predicate_ctx = ctx.clone();
23326            let mut wait = Box::pin(
23327                ctx.wait_condition(
23328                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23329                        .timeout(Duration::from_secs(120)),
23330                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23331                ),
23332            );
23333            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23334            assert!(matches!(
23335                wait.as_mut().poll(&mut task_context),
23336                Poll::Pending
23337            ));
23338            assert_eq!(
23339                ctx.take_commands().expect("reopened condition"),
23340                vec![json!({
23341                    "type": "open_condition_wait",
23342                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23343                    "condition_key": "two-votes",
23344                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23345                    "timeout_seconds": 120,
23346                })]
23347            );
23348        }
23349
23350        let satisfied_ctx = workflow_context(vec![
23351            history_event(
23352                "ConditionWaitOpened",
23353                json!({
23354                    "sequence": 5,
23355                    "condition_wait_id": "condition:5",
23356                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23357                    "condition_key": "approval",
23358                    "condition_definition_fingerprint": "sha256:approval-v1",
23359                }),
23360            ),
23361            history_event(
23362                "ConditionWaitSatisfied",
23363                json!({
23364                    "sequence": 5,
23365                    "condition_wait_id": "condition:5",
23366                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23367                    "condition_key": "approval",
23368                    "condition_definition_fingerprint": "sha256:approval-v1",
23369                }),
23370            ),
23371        ]);
23372        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
23373            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
23374            || Ok(false),
23375        ));
23376        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23377        assert!(matches!(
23378            satisfied.as_mut().poll(&mut task_context),
23379            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23380        ));
23381
23382        let timed_out_ctx = workflow_context(vec![
23383            history_event(
23384                "ConditionWaitOpened",
23385                json!({
23386                    "sequence": 8,
23387                    "condition_wait_id": "condition:8",
23388                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23389                    "condition_key": "approval-timeout",
23390                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
23391                    "timeout_seconds": 5,
23392                }),
23393            ),
23394            history_event(
23395                "TimerScheduled",
23396                json!({
23397                    "sequence": 9,
23398                    "timer_id": "condition-timer:9",
23399                    "timer_kind": "condition_timeout",
23400                    "condition_wait_id": "condition:8",
23401                    "delay_seconds": 5,
23402                }),
23403            ),
23404            history_event(
23405                "TimerFired",
23406                json!({
23407                    "sequence": 9,
23408                    "timer_id": "condition-timer:9",
23409                    "timer_kind": "condition_timeout",
23410                    "condition_wait_id": "condition:8",
23411                    "delay_seconds": 5,
23412                }),
23413            ),
23414        ]);
23415        let mut timed_out = Box::pin(
23416            timed_out_ctx.wait_condition(
23417                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
23418                    .timeout(Duration::from_secs(5)),
23419                || Ok(true),
23420            ),
23421        );
23422        assert!(matches!(
23423            timed_out.as_mut().poll(&mut task_context),
23424            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
23425        ));
23426    }
23427
23428    #[test]
23429    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
23430        let ctx = workflow_context(reopened_selection_condition_history());
23431        {
23432            let state = ctx.state.lock().unwrap();
23433            assert!(matches!(
23434                selection_member_recorded_command(&state, 2),
23435                Some(RecordedCommand::ConditionWait {
23436                    sequence: 3,
23437                    result: None,
23438                    ..
23439                })
23440            ));
23441        }
23442        let mut selected = Box::pin(ctx.select_keyed(vec![
23443            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
23444            (
23445                "votes",
23446                ParallelOperation::condition(
23447                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
23448                    || Ok(true),
23449                ),
23450            ),
23451        ]));
23452        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23453        assert!(selected.as_mut().poll(&mut task_context).is_pending());
23454        assert!(
23455            ctx.take_commands().unwrap().is_empty(),
23456            "true predicate must not reopen the recorded wait"
23457        );
23458        ctx.ensure_history_consumed()
23459            .expect("physical reopens are consumed while canonical selection is pending");
23460    }
23461
23462    #[test]
23463    fn reopened_selection_condition_replays_its_latest_physical_winner() {
23464        for (terminal_type, acknowledge_timeout) in [
23465            ("ConditionWaitSatisfied", false),
23466            ("ConditionWaitTimedOut", false),
23467            ("TimerFired", false),
23468            ("TimerFired", true),
23469        ] {
23470            let mut history = reopened_selection_condition_history();
23471            let original_identity = history[1].payload["condition_wait_id"].clone();
23472            let uses_timer = terminal_type == "TimerFired";
23473            let mut resolution_payload = history[3].payload.clone();
23474            if uses_timer {
23475                for event in &mut history[1..] {
23476                    event.payload["timeout_seconds"] = json!(3);
23477                }
23478                resolution_payload = history[3].payload.clone();
23479                resolution_payload["timer_kind"] = json!("condition_timeout");
23480                resolution_payload["timer_id"] = json!("condition-timeout-3");
23481                resolution_payload["delay_seconds"] = json!(3);
23482                history.push(history_event("TimerScheduled", resolution_payload.clone()));
23483            }
23484            let mut resolution = history_event(terminal_type, resolution_payload.clone());
23485            resolution
23486                .raw
23487                .insert("id".into(), json!("latest-condition-resolution"));
23488            history.push(resolution);
23489            history.push(history_event(
23490                "SelectionResolved",
23491                json!({
23492                    "selection_group_id": "select-calls:1:2",
23493                    "selection_group_base_sequence": 1,
23494                    "selection_group_size": 2,
23495                    "member_key": "votes",
23496                    "member_index": 1,
23497                    "member_base_sequence": 2,
23498                    "member_size": 1,
23499                    "operation_kind": "condition",
23500                    "operation_identity": original_identity,
23501                    "outcome": "completed",
23502                    "resolution_event_id": "latest-condition-resolution",
23503                    "resolution_event_type": terminal_type,
23504                }),
23505            ));
23506            if acknowledge_timeout {
23507                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
23508            }
23509            let ctx = workflow_context(history);
23510            let mut selected = Box::pin(ctx.select_keyed(vec![
23511                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
23512                (
23513                    "votes",
23514                    ParallelOperation::condition(
23515                        if uses_timer {
23516                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23517                                .timeout(Duration::from_secs(3))
23518                        } else {
23519                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23520                        },
23521                        || Ok(true),
23522                    ),
23523                ),
23524            ]));
23525            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23526            match selected.as_mut().poll(&mut task_context) {
23527                Poll::Ready(Ok(result)) => {
23528                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
23529                    let expected = if terminal_type == "ConditionWaitSatisfied" {
23530                        ConditionWaitResult::Satisfied
23531                    } else {
23532                        ConditionWaitResult::TimedOut
23533                    };
23534                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
23535                }
23536                other => panic!("latest physical winner must replay: {other:?}"),
23537            }
23538            assert!(ctx.take_commands().unwrap().is_empty());
23539            ctx.ensure_history_consumed()
23540                .expect("winner history consumed");
23541        }
23542    }
23543
23544    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
23545        let fixture: Value = serde_json::from_str(include_str!(
23546            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
23547        ))
23548        .expect("grouped condition fixture");
23549        fixture["history"]
23550            .as_array()
23551            .unwrap()
23552            .iter()
23553            .map(|event| {
23554                let mut payload = event["payload"].clone();
23555                let index = payload["parallel_group_index"].as_u64().unwrap();
23556                payload["parallel_group_id"] = json!("select-calls:1:2");
23557                payload["parallel_group_mode"] = json!("select");
23558                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
23559                payload["selection_member_index"] = json!(index);
23560                payload["selection_member_base_sequence"] = json!(index + 1);
23561                payload["selection_member_size"] = json!(1);
23562                payload["selection_member_kind"] =
23563                    json!(if index == 0 { "timer" } else { "condition" });
23564                history_event(event["event_type"].as_str().unwrap(), payload)
23565            })
23566            .collect()
23567    }
23568
23569    #[test]
23570    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
23571        let fixture: Value = serde_json::from_str(include_str!(
23572            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
23573        ))
23574        .expect("grouped condition fixture");
23575        let original = fixture["history"].as_array().expect("fixture history");
23576        let decode = |events: &[Value]| {
23577            let history = events
23578                .iter()
23579                .map(|event| {
23580                    history_event(
23581                        event["event_type"].as_str().unwrap(),
23582                        event["payload"].clone(),
23583                    )
23584                })
23585                .collect::<Vec<_>>();
23586            recorded_commands(
23587                &history,
23588                DEFAULT_CODEC,
23589                WorkflowIdentity {
23590                    workflow_id: None,
23591                    run_id: None,
23592                },
23593            )
23594        };
23595        assert!(decode(original).is_ok());
23596        for field in [
23597            "condition_wait_occurrence_id",
23598            "condition_key",
23599            "condition_definition_fingerprint",
23600            "timeout_seconds",
23601            "parallel_group_id",
23602            "parallel_group_size",
23603            "parallel_group_index",
23604        ] {
23605            let mut changed = original.clone();
23606            changed[3]["payload"][field] = match field {
23607                "timeout_seconds" | "parallel_group_size" => json!(30),
23608                "parallel_group_index" => json!(0),
23609                _ => json!("changed"),
23610            };
23611            assert!(
23612                decode(&changed).is_err(),
23613                "reopen must reject changed {field}"
23614            );
23615        }
23616        let mut unsettled = original.clone();
23617        unsettled.remove(2);
23618        assert!(
23619            decode(&unsettled).is_err(),
23620            "physical predecessor must be resolved"
23621        );
23622        let mut timed_out = original.clone();
23623        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
23624        assert!(decode(&timed_out).is_err(), "timeout is terminal");
23625        let mut late_resolution = original.clone();
23626        late_resolution.swap(2, 3);
23627        assert!(
23628            decode(&late_resolution).is_err(),
23629            "later history cannot authorize a reopen"
23630        );
23631    }
23632
23633    #[test]
23634    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
23635        let history = vec![
23636            history_event(
23637                "ConditionWaitOpened",
23638                json!({
23639                    "sequence": 3,
23640                    "condition_wait_id": "condition:3",
23641                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23642                    "condition_key": "two-votes",
23643                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23644                }),
23645            ),
23646            history_event(
23647                "SignalReceived",
23648                json!({
23649                    "workflow_sequence": 3,
23650                    "signal_name": "vote",
23651                    "arguments": fixture_envelope(json!(["first"])),
23652                }),
23653            ),
23654            history_event(
23655                "ConditionWaitSatisfied",
23656                json!({
23657                    "sequence": 3,
23658                    "condition_wait_id": "condition:3",
23659                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23660                    "condition_key": "two-votes",
23661                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23662                }),
23663            ),
23664            history_event(
23665                "ConditionWaitOpened",
23666                json!({
23667                    "sequence": 5,
23668                    "condition_wait_id": "condition:5",
23669                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23670                    "condition_key": "two-votes",
23671                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23672                }),
23673            ),
23674            history_event(
23675                "SignalReceived",
23676                json!({
23677                    "workflow_sequence": 5,
23678                    "signal_name": "vote",
23679                    "arguments": fixture_envelope(json!(["second"])),
23680                }),
23681            ),
23682            history_event(
23683                "ConditionWaitSatisfied",
23684                json!({
23685                    "sequence": 5,
23686                    "condition_wait_id": "condition:5",
23687                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23688                    "condition_key": "two-votes",
23689                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23690                }),
23691            ),
23692        ];
23693        for _cold_worker_or_restart in 0..2 {
23694            let ctx = workflow_context(history.clone());
23695            let predicate_ctx = ctx.clone();
23696            let mut wait = Box::pin(ctx.wait_condition(
23697                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
23698                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23699            ));
23700            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23701
23702            assert!(matches!(
23703                wait.as_mut().poll(&mut task_context),
23704                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23705            ));
23706            assert!(ctx.take_commands().expect("commands").is_empty());
23707            ctx.ensure_history_consumed()
23708                .expect("every physical wait-open is consumed");
23709        }
23710    }
23711
23712    #[test]
23713    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
23714        let history = vec![
23715            history_event(
23716                "ConditionWaitOpened",
23717                json!({
23718                    "sequence": 3,
23719                    "condition_wait_id": "condition:3",
23720                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23721                    "condition_key": "approved",
23722                    "condition_definition_fingerprint": "sha256:approved-v1",
23723                }),
23724            ),
23725            history_event(
23726                "UpdateApplied",
23727                json!({
23728                    "sequence": 3,
23729                    "update_id": "update-1",
23730                    "update_name": "approve",
23731                    "arguments": fixture_envelope(json!([false])),
23732                }),
23733            ),
23734            history_event(
23735                "ConditionWaitOpened",
23736                json!({
23737                    "sequence": 5,
23738                    "condition_wait_id": "condition:5",
23739                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23740                    "condition_key": "approved",
23741                    "condition_definition_fingerprint": "sha256:approved-v1",
23742                }),
23743            ),
23744            history_event(
23745                "UpdateApplied",
23746                json!({
23747                    "sequence": 5,
23748                    "update_id": "update-2",
23749                    "update_name": "approve",
23750                    "arguments": fixture_envelope(json!([true])),
23751                }),
23752            ),
23753        ];
23754
23755        for _cold_worker_or_restart in 0..2 {
23756            let ctx = workflow_context(history.clone());
23757            let predicate_ctx = ctx.clone();
23758            let mut wait = Box::pin(ctx.wait_condition(
23759                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
23760                move || {
23761                    Ok(predicate_ctx
23762                        .updates("approve")?
23763                        .last()
23764                        .and_then(|arguments| arguments.first())
23765                        .and_then(Value::as_bool)
23766                        == Some(true))
23767                },
23768            ));
23769            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23770
23771            assert!(matches!(
23772                wait.as_mut().poll(&mut task_context),
23773                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23774            ));
23775            assert!(ctx.take_commands().expect("commands").is_empty());
23776            ctx.ensure_history_consumed()
23777                .expect("every update-driven reopen is consumed");
23778        }
23779    }
23780
23781    #[test]
23782    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
23783        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
23784            ("shared", "sha256:first", "shared", "sha256:second"),
23785            ("first", "sha256:shared", "second", "sha256:shared"),
23786            ("shared", "sha256:shared", "shared", "sha256:shared"),
23787            ("first", "sha256:first", "second", "sha256:second"),
23788        ] {
23789            let history = vec![
23790                history_event(
23791                    "ConditionWaitOpened",
23792                    json!({
23793                        "sequence": 3,
23794                        "condition_wait_id": "condition:3",
23795                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23796                        "condition_key": first_key,
23797                        "condition_definition_fingerprint": first_fingerprint,
23798                    }),
23799                ),
23800                history_event(
23801                    "ConditionWaitSatisfied",
23802                    json!({
23803                        "sequence": 3,
23804                        "condition_wait_id": "condition:3",
23805                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23806                        "condition_key": first_key,
23807                        "condition_definition_fingerprint": first_fingerprint,
23808                    }),
23809                ),
23810                history_event(
23811                    "ConditionWaitOpened",
23812                    json!({
23813                        "sequence": 4,
23814                        "condition_wait_id": "condition:4",
23815                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23816                        "condition_key": second_key,
23817                        "condition_definition_fingerprint": second_fingerprint,
23818                    }),
23819                ),
23820                history_event(
23821                    "ConditionWaitSatisfied",
23822                    json!({
23823                        "sequence": 4,
23824                        "condition_wait_id": "condition:4",
23825                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23826                        "condition_key": second_key,
23827                        "condition_definition_fingerprint": second_fingerprint,
23828                    }),
23829                ),
23830            ];
23831            for _cold_worker_or_restart in 0..2 {
23832                let ctx = workflow_context(history.clone());
23833                let mut task_context = TaskContext::from_waker(noop_waker_ref());
23834                let mut first = Box::pin(ctx.wait_condition(
23835                    ConditionWaitOptions::new(first_key, first_fingerprint),
23836                    || Ok(false),
23837                ));
23838                assert!(matches!(
23839                    first.as_mut().poll(&mut task_context),
23840                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23841                ));
23842
23843                let mut second = Box::pin(ctx.wait_condition(
23844                    ConditionWaitOptions::new(second_key, second_fingerprint),
23845                    || Ok(false),
23846                ));
23847                assert!(matches!(
23848                    second.as_mut().poll(&mut task_context),
23849                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23850                ));
23851                assert!(ctx.take_commands().expect("commands").is_empty());
23852                ctx.ensure_history_consumed()
23853                    .expect("each authored wait consumes one occurrence");
23854            }
23855        }
23856    }
23857
23858    #[test]
23859    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
23860        fn worker() -> Worker {
23861            let client = Client::new("http://127.0.0.1:8080").expect("client");
23862            let mut worker = Worker::new(client, "rust-workers");
23863            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
23864                let mut outcomes = Vec::new();
23865                for _ in 0..2 {
23866                    outcomes.push(
23867                        ctx.wait_condition(
23868                            ConditionWaitOptions::new("shared", "sha256:shared"),
23869                            || Ok(false),
23870                        )
23871                        .await?,
23872                    );
23873                }
23874                Ok(json!(outcomes))
23875            });
23876            worker
23877        }
23878
23879        let task = workflow_task(
23880            "rust.condition-loop",
23881            vec![
23882                history_event(
23883                    "ConditionWaitOpened",
23884                    json!({
23885                        "sequence": 1,
23886                        "condition_wait_id": "condition:1",
23887                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23888                        "condition_key": "shared",
23889                        "condition_definition_fingerprint": "sha256:shared",
23890                    }),
23891                ),
23892                history_event(
23893                    "ConditionWaitSatisfied",
23894                    json!({
23895                        "sequence": 1,
23896                        "condition_wait_id": "condition:1",
23897                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23898                        "condition_key": "shared",
23899                        "condition_definition_fingerprint": "sha256:shared",
23900                    }),
23901                ),
23902                history_event(
23903                    "ConditionWaitOpened",
23904                    json!({
23905                        "sequence": 2,
23906                        "condition_wait_id": "condition:2",
23907                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23908                        "condition_key": "shared",
23909                        "condition_definition_fingerprint": "sha256:shared",
23910                    }),
23911                ),
23912                history_event(
23913                    "ConditionWaitSatisfied",
23914                    json!({
23915                        "sequence": 2,
23916                        "condition_wait_id": "condition:2",
23917                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23918                        "condition_key": "shared",
23919                        "condition_definition_fingerprint": "sha256:shared",
23920                    }),
23921                ),
23922            ],
23923            DEFAULT_CODEC,
23924        );
23925
23926        for _cold_worker_or_restart in 0..2 {
23927            let commands = worker()
23928                .execute_workflow_task(task.clone())
23929                .expect("adjacent loop waits replay deterministically");
23930            assert_eq!(commands.len(), 1);
23931            assert_eq!(commands[0]["type"], "complete_workflow");
23932            assert_eq!(
23933                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23934                json!(["satisfied", "satisfied"])
23935            );
23936        }
23937    }
23938
23939    #[test]
23940    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
23941        let history = vec![history_event(
23942            "ConditionWaitOpened",
23943            json!({
23944                "sequence": 12,
23945                "condition_wait_id": "condition:12",
23946                "condition_wait_occurrence_id": "rust:condition-wait:0",
23947                "condition_key": "approval",
23948                "condition_definition_fingerprint": "sha256:approval-v1",
23949                "timeout_seconds": 30,
23950            }),
23951        )];
23952        for (options, expected_reason) in [
23953            (
23954                ConditionWaitOptions::new("changed", "sha256:approval-v1")
23955                    .timeout(Duration::from_secs(30)),
23956                "condition_wait_key_mismatch",
23957            ),
23958            (
23959                ConditionWaitOptions::new("approval", "sha256:approval-v2")
23960                    .timeout(Duration::from_secs(30)),
23961                "condition_wait_predicate_mismatch",
23962            ),
23963            (
23964                ConditionWaitOptions::new("approval", "sha256:approval-v1")
23965                    .timeout(Duration::from_secs(29)),
23966                "condition_wait_timeout_mismatch",
23967            ),
23968        ] {
23969            let ctx = workflow_context(history.clone());
23970            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
23971            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23972            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23973                wait.as_mut().poll(&mut task_context)
23974            else {
23975                panic!("changed condition definition must fail replay");
23976            };
23977            assert_eq!(failure.reason, expected_reason);
23978            assert_eq!(failure.sequence, Some(12));
23979        }
23980    }
23981
23982    #[test]
23983    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
23984        let error = WorkflowState::new(
23985            vec![history_event(
23986                "ConditionWaitOpened",
23987                json!({
23988                    "sequence": 12,
23989                    "condition_wait_id": "condition:12",
23990                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23991                    "condition_key": "approval",
23992                }),
23993            )],
23994            "rust-workers".to_string(),
23995            DEFAULT_CODEC.to_string(),
23996            None,
23997        )
23998        .expect_err("condition history without a predicate fingerprint must fail");
23999
24000        assert!(matches!(
24001            error,
24002            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24003                if reason == "condition_wait_predicate_fingerprint_missing"
24004        ));
24005    }
24006
24007    #[test]
24008    fn condition_wait_history_requires_authored_occurrence_identity() {
24009        let error = WorkflowState::new(
24010            vec![history_event(
24011                "ConditionWaitOpened",
24012                json!({
24013                    "sequence": 12,
24014                    "condition_wait_id": "condition:12",
24015                    "condition_key": "approval",
24016                    "condition_definition_fingerprint": "sha256:approval-v1",
24017                }),
24018            )],
24019            "rust-workers".to_string(),
24020            DEFAULT_CODEC.to_string(),
24021            None,
24022        )
24023        .expect_err("condition history without occurrence identity must fail");
24024
24025        assert!(matches!(
24026            error,
24027            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24028                if reason == "condition_wait_occurrence_id_missing"
24029        ));
24030    }
24031
24032    #[test]
24033    fn typed_search_attribute_updates_validate_emit_and_replay() {
24034        let update = SearchAttributeUpdate::new()
24035            .keyword("OrderStatus", " waiting ")
24036            .expect("keyword")
24037            .int("Attempt", 3)
24038            .expect("int")
24039            .bool("Escalated", false)
24040            .expect("bool")
24041            .keyword_list("Regions", ["us-east", "eu-west"])
24042            .expect("list")
24043            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
24044            .expect("datetime")
24045            .delete("LegacyStatus")
24046            .expect("delete");
24047        let ctx = workflow_context(Vec::new());
24048        ctx.upsert_search_attributes(update.clone())
24049            .expect("typed update");
24050        assert_eq!(
24051            ctx.take_commands().expect("search-attribute command"),
24052            vec![json!({
24053                "type": "upsert_search_attributes",
24054                "attributes": {
24055                    "Attempt": 3,
24056                    "Escalated": false,
24057                    "LegacyStatus": null,
24058                    "OrderStatus": "waiting",
24059                    "Regions": ["us-east", "eu-west"],
24060                    "UpdatedAt": "2026-08-22T04:00:00Z",
24061                },
24062                "attribute_types": {
24063                    "Attempt": "int",
24064                    "Escalated": "bool",
24065                    "OrderStatus": "keyword",
24066                    "Regions": "keyword_list",
24067                    "UpdatedAt": "datetime",
24068                },
24069            })]
24070        );
24071
24072        let replay = workflow_context(vec![history_event(
24073            "SearchAttributesUpserted",
24074            json!({
24075                "sequence": 6,
24076                "attributes": {
24077                    "Attempt": 3,
24078                    "Escalated": false,
24079                    "LegacyStatus": null,
24080                    "OrderStatus": "waiting",
24081                    "Regions": ["us-east", "eu-west"],
24082                    "UpdatedAt": "2026-08-22T04:00:00Z",
24083                },
24084                "attribute_types": {
24085                    "Attempt": "int",
24086                    "Escalated": "bool",
24087                    "OrderStatus": "keyword",
24088                    "Regions": "keyword_list",
24089                    "UpdatedAt": "datetime",
24090                },
24091                "merged": {},
24092            }),
24093        )]);
24094        replay
24095            .upsert_search_attributes(update)
24096            .expect("matching update replays");
24097        assert!(replay.take_commands().expect("commands").is_empty());
24098        replay.ensure_history_consumed().expect("history consumed");
24099
24100        let type_drift = workflow_context(vec![history_event(
24101            "SearchAttributesUpserted",
24102            json!({
24103                "sequence": 7,
24104                "attributes": {"OrderStatus": "waiting"},
24105                "attribute_types": {"OrderStatus": "keyword"},
24106                "merged": {"OrderStatus": "waiting"},
24107            }),
24108        )]);
24109        let error = type_drift
24110            .upsert_search_attributes(
24111                SearchAttributeUpdate::new()
24112                    .string("OrderStatus", "waiting")
24113                    .expect("string update"),
24114            )
24115            .expect_err("same JSON value with a changed type must fail replay");
24116        assert!(matches!(
24117            error,
24118            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24119                if reason == "search_attribute_type_mismatch"
24120        ));
24121
24122        let malformed_types = WorkflowState::new(
24123            vec![history_event(
24124                "SearchAttributesUpserted",
24125                json!({
24126                    "sequence": 8,
24127                    "attributes": {"OrderStatus": "waiting"},
24128                    "attribute_types": {"OrderStatus": "unsupported"},
24129                    "merged": {"OrderStatus": "waiting"},
24130                }),
24131            )],
24132            "rust-workers".to_string(),
24133            DEFAULT_CODEC.to_string(),
24134            None,
24135        )
24136        .expect_err("unsupported search-attribute type metadata must fail");
24137        assert!(matches!(
24138            malformed_types,
24139            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24140                if reason == "search_attribute_types_malformed"
24141        ));
24142
24143        assert!(matches!(
24144            SearchAttributeUpdate::new().keyword("bad key", "value"),
24145            Err(SearchAttributeUpdateError::InvalidKey(_))
24146        ));
24147        assert!(matches!(
24148            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
24149            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
24150        ));
24151        assert!(matches!(
24152            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
24153            Err(SearchAttributeUpdateError::ValueTooLong { .. })
24154        ));
24155        assert!(matches!(
24156            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
24157            Err(SearchAttributeUpdateError::InvalidDateTime(_))
24158        ));
24159        assert!(matches!(
24160            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
24161            Err(Error::InvalidSearchAttributeUpdate(
24162                SearchAttributeUpdateError::Empty
24163            ))
24164        ));
24165    }
24166
24167    #[test]
24168    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
24169        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
24170        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
24171
24172        assert!(SearchAttributeUpdate::new()
24173            .string("AsciiDescription", ascii)
24174            .is_ok());
24175        assert!(SearchAttributeUpdate::new()
24176            .string("Utf8Description", utf8)
24177            .is_ok());
24178        assert!(matches!(
24179            SearchAttributeUpdate::new().string(
24180                "TooLongDescription",
24181                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
24182            ),
24183            Err(SearchAttributeUpdateError::ValueTooLong {
24184                kind: "string",
24185                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
24186                ..
24187            })
24188        ));
24189    }
24190
24191    #[test]
24192    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
24193        let lone_fire = WorkflowState::new(
24194            vec![history_event(
24195                "TimerFired",
24196                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24197            )],
24198            "rust-workers".to_string(),
24199            DEFAULT_CODEC.to_string(),
24200            None,
24201        )
24202        .expect_err("TimerFired requires TimerScheduled");
24203        assert!(matches!(
24204            lone_fire,
24205            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24206                if reason == "timer_schedule_missing_or_duplicate"
24207        ));
24208
24209        let wrong_identity = WorkflowState::new(
24210            vec![
24211                history_event(
24212                    "TimerScheduled",
24213                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24214                ),
24215                history_event(
24216                    "TimerFired",
24217                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24218                ),
24219            ],
24220            "rust-workers".to_string(),
24221            DEFAULT_CODEC.to_string(),
24222            None,
24223        )
24224        .expect_err("fire must match scheduled timer identity");
24225        assert!(matches!(
24226            wrong_identity,
24227            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24228                if reason == "timer_identity_mismatch"
24229        ));
24230
24231        let duplicate_fire = WorkflowState::new(
24232            vec![
24233                history_event(
24234                    "TimerScheduled",
24235                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24236                ),
24237                history_event(
24238                    "TimerFired",
24239                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24240                ),
24241                history_event(
24242                    "TimerFired",
24243                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24244                ),
24245            ],
24246            "rust-workers".to_string(),
24247            DEFAULT_CODEC.to_string(),
24248            None,
24249        )
24250        .expect_err("a durable timer cannot fire twice");
24251        assert!(matches!(
24252            duplicate_fire,
24253            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24254                if reason == "duplicate_timer_fire"
24255        ));
24256
24257        let wrong_fired_delay = WorkflowState::new(
24258            vec![
24259                history_event(
24260                    "TimerScheduled",
24261                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24262                ),
24263                history_event(
24264                    "TimerFired",
24265                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
24266                ),
24267            ],
24268            "rust-workers".to_string(),
24269            DEFAULT_CODEC.to_string(),
24270            None,
24271        )
24272        .expect_err("timer schedule and fire delays must agree");
24273        assert!(matches!(
24274            wrong_fired_delay,
24275            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24276                if reason == "timer_history_delay_mismatch"
24277        ));
24278    }
24279
24280    #[test]
24281    fn replay_rejects_activity_moved_before_recorded_timer() {
24282        let ctx = workflow_context(vec![
24283            history_event(
24284                "TimerScheduled",
24285                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24286            ),
24287            history_event(
24288                "TimerFired",
24289                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24290            ),
24291            history_event(
24292                "ActivityCompleted",
24293                json!({
24294                    "sequence": 2,
24295                    "activity_type": "after-timer",
24296                    "payload_codec": DEFAULT_CODEC,
24297                    "result": fixture_envelope(json!("done")),
24298                }),
24299            ),
24300        ]);
24301        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
24302        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24303
24304        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24305            activity.as_mut().poll(&mut task_context)
24306        else {
24307            panic!("reordered durable command must be rejected");
24308        };
24309        assert_eq!(failure.reason, "recorded_command_mismatch");
24310        assert_eq!(failure.sequence, Some(1));
24311        assert_eq!(failure.expected.as_deref(), Some("timer"));
24312        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
24313    }
24314
24315    #[test]
24316    fn workflow_context_emits_a_typed_named_signal_wait() {
24317        let ctx = workflow_context(Vec::new());
24318        let mut signal = Box::pin(ctx.wait_signal("finish"));
24319        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24320
24321        assert!(matches!(
24322            signal.as_mut().poll(&mut task_context),
24323            Poll::Pending
24324        ));
24325        assert_eq!(
24326            ctx.take_commands().expect("signal-wait command"),
24327            vec![json!({
24328                "type": "open_signal_wait",
24329                "signal_name": "finish",
24330            })]
24331        );
24332    }
24333
24334    #[test]
24335    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
24336        let ctx = workflow_context(Vec::new());
24337        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
24338        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24339
24340        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
24341        else {
24342            panic!("runtime-reserved signal should be rejected");
24343        };
24344        assert!(message.contains("reserved by the workflow runtime"));
24345        assert!(ctx.take_commands().expect("commands").is_empty());
24346    }
24347
24348    #[tokio::test]
24349    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
24350        let client = Client::builder("http://127.0.0.1:9")
24351            .build()
24352            .expect("client");
24353        let error = client
24354            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
24355            .await
24356            .expect_err("runtime-reserved signal should be rejected before transport");
24357
24358        assert!(
24359            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
24360        );
24361    }
24362
24363    #[test]
24364    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
24365        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24366            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24367                value.to_string(),
24368            )]))
24369            .expect("message payload");
24370            json!({
24371                "schema": MESSAGE_STREAM_SCHEMA,
24372                "stream_name": "orders",
24373                "message_id": message_id,
24374                "position": position,
24375                "payload_envelope": payload,
24376            })
24377        }
24378
24379        fn opened(sequence: u64) -> HistoryEvent {
24380            history_event(
24381                "SignalWaitOpened",
24382                json!({
24383                    "sequence": sequence,
24384                    "signal_name": MESSAGE_STREAM_SIGNAL,
24385                }),
24386            )
24387        }
24388
24389        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24390            history_event(
24391                "SignalApplied",
24392                json!({
24393                    "sequence": sequence,
24394                    "signal_name": MESSAGE_STREAM_SIGNAL,
24395                    "value": fixture_envelope(json!([delivery])),
24396                }),
24397            )
24398        }
24399
24400        fn received(delivery: Value) -> HistoryEvent {
24401            history_event(
24402                "SignalReceived",
24403                json!({
24404                    "signal_name": MESSAGE_STREAM_SIGNAL,
24405                    "arguments": fixture_envelope(json!([delivery])),
24406                    "payload_codec": DEFAULT_CODEC,
24407                }),
24408            )
24409        }
24410
24411        let client = Client::new("http://127.0.0.1:8080").expect("client");
24412        let mut worker = Worker::new(client, "rust-workers");
24413        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
24414            let messages = ctx.message_stream("orders")?.receive(2).await?;
24415            Ok(json!(messages
24416                .into_iter()
24417                .map(|message| message.message_id)
24418                .collect::<Vec<_>>()))
24419        });
24420
24421        let first = delivery("message-1", 1, "one");
24422        let second = delivery("message-2", 2, "two");
24423        let batch = worker
24424            .execute_workflow_task_decision(workflow_task(
24425                "rust.message-stream-batch",
24426                vec![
24427                    opened(1),
24428                    received(first.clone()),
24429                    applied(1, first.clone()),
24430                    received(first.clone()),
24431                    received(second),
24432                ],
24433                DEFAULT_CODEC,
24434            ))
24435            .expect("worker task consumes the available batch");
24436
24437        assert_eq!(batch.commands.len(), 1);
24438        assert_eq!(batch.commands[0]["type"], "complete_workflow");
24439        assert_eq!(
24440            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
24441                .expect("workflow result"),
24442            json!(["message-1", "message-2"])
24443        );
24444        assert_eq!(
24445            batch.message_stream_cursors,
24446            vec![json!({"stream_name": "orders", "through_position": 2})]
24447        );
24448        assert!(batch.message_stream_waits.is_empty());
24449
24450        let partial = worker
24451            .execute_workflow_task_decision(workflow_task(
24452                "rust.message-stream-batch",
24453                vec![opened(1), received(first.clone()), applied(1, first)],
24454                DEFAULT_CODEC,
24455            ))
24456            .expect("worker task returns without waiting for a missing second item");
24457        assert_eq!(partial.commands.len(), 1);
24458        assert_eq!(partial.commands[0]["type"], "complete_workflow");
24459        assert_eq!(
24460            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
24461                .expect("workflow result"),
24462            json!(["message-1"])
24463        );
24464        assert_eq!(
24465            partial.message_stream_cursors,
24466            vec![json!({"stream_name": "orders", "through_position": 1})]
24467        );
24468        assert!(partial.message_stream_waits.is_empty());
24469    }
24470
24471    #[test]
24472    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
24473        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24474            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24475                value.to_string(),
24476            )]))
24477            .expect("message payload");
24478            json!({
24479                "schema": MESSAGE_STREAM_SCHEMA,
24480                "stream_name": "orders",
24481                "message_id": message_id,
24482                "position": position,
24483                "payload_envelope": payload,
24484            })
24485        }
24486
24487        fn opened(sequence: u64) -> HistoryEvent {
24488            history_event(
24489                "SignalWaitOpened",
24490                json!({
24491                    "sequence": sequence,
24492                    "signal_name": MESSAGE_STREAM_SIGNAL,
24493                }),
24494            )
24495        }
24496
24497        fn received(delivery: Value) -> HistoryEvent {
24498            history_event(
24499                "SignalReceived",
24500                json!({
24501                    "signal_name": MESSAGE_STREAM_SIGNAL,
24502                    "arguments": fixture_envelope(json!([delivery])),
24503                    "payload_codec": DEFAULT_CODEC,
24504                }),
24505            )
24506        }
24507
24508        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24509            history_event(
24510                "SignalApplied",
24511                json!({
24512                    "sequence": sequence,
24513                    "signal_name": MESSAGE_STREAM_SIGNAL,
24514                    "value": fixture_envelope(json!([delivery])),
24515                }),
24516            )
24517        }
24518
24519        let client = Client::new("http://127.0.0.1:8080").expect("client");
24520        let mut worker = Worker::new(client, "rust-workers");
24521        worker.register_workflow(
24522            "rust.message-stream-partial-batches",
24523            |ctx, _input| async move {
24524                let stream = ctx.message_stream("orders")?;
24525                let first = stream.receive(10).await?;
24526                let second = stream.receive(10).await?;
24527                Ok(json!([
24528                    first
24529                        .into_iter()
24530                        .map(|message| message.message_id)
24531                        .collect::<Vec<_>>(),
24532                    second
24533                        .into_iter()
24534                        .map(|message| message.message_id)
24535                        .collect::<Vec<_>>(),
24536                ]))
24537            },
24538        );
24539
24540        let first = delivery("message-1", 1, "one");
24541        let second = delivery("message-2", 2, "two");
24542        let decision = worker
24543            .execute_workflow_task_decision(workflow_task(
24544                "rust.message-stream-partial-batches",
24545                vec![
24546                    opened(1),
24547                    received(first.clone()),
24548                    applied(1, first),
24549                    opened(2),
24550                    received(second.clone()),
24551                    applied(2, second),
24552                ],
24553                DEFAULT_CODEC,
24554            ))
24555            .expect("cold replay preserves both authored receive boundaries");
24556
24557        assert_eq!(decision.commands.len(), 1);
24558        assert_eq!(decision.commands[0]["type"], "complete_workflow");
24559        assert_eq!(
24560            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
24561                .expect("workflow result"),
24562            json!([["message-1"], ["message-2"]])
24563        );
24564        assert_eq!(
24565            decision.message_stream_cursors,
24566            vec![json!({"stream_name": "orders", "through_position": 2})]
24567        );
24568        assert!(decision.message_stream_waits.is_empty());
24569    }
24570
24571    #[test]
24572    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
24573        let ctx = workflow_context(Vec::new());
24574        let stream = ctx.message_stream("orders").expect("message stream");
24575        let mut receive = Box::pin(stream.receive(10));
24576        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24577
24578        assert!(matches!(
24579            receive.as_mut().poll(&mut task_context),
24580            Poll::Pending
24581        ));
24582        assert_eq!(
24583            ctx.take_commands().expect("message-stream wait command"),
24584            vec![json!({
24585                "type": "open_signal_wait",
24586                "signal_name": MESSAGE_STREAM_SIGNAL,
24587            })]
24588        );
24589        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
24590        assert!(cursors.is_empty());
24591        assert_eq!(
24592            waits,
24593            vec![json!({"stream_name": "orders", "after_position": 0})]
24594        );
24595    }
24596
24597    #[test]
24598    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
24599        let ctx = workflow_context(vec![history_event(
24600            "SignalReceived",
24601            json!({
24602                "signal_name": MESSAGE_STREAM_SIGNAL,
24603                "arguments": fixture_envelope(json!([{
24604                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
24605                    "stream_name": "orders",
24606                    "through_position": 2,
24607                }])),
24608                "payload_codec": DEFAULT_CODEC,
24609            }),
24610        )]);
24611        let stream = ctx.message_stream("orders").expect("message stream");
24612        let mut receive = Box::pin(stream.receive(10));
24613        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24614
24615        assert!(matches!(
24616            receive.as_mut().poll(&mut task_context),
24617            Poll::Pending
24618        ));
24619        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
24620        assert_eq!(
24621            cursors,
24622            vec![json!({"stream_name": "orders", "through_position": 2})]
24623        );
24624        assert_eq!(
24625            waits,
24626            vec![json!({"stream_name": "orders", "after_position": 2})]
24627        );
24628    }
24629
24630    #[test]
24631    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
24632        let mut empty_map = BTreeMap::new();
24633        let mut nested = BTreeMap::new();
24634        nested.insert(
24635            "value".to_string(),
24636            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
24637        );
24638        let values = vec![
24639            AvroValue::Bytes(vec![0, 255]),
24640            AvroValue::Long(1),
24641            AvroValue::Double(1.0),
24642            AvroValue::Array(Vec::new()),
24643            AvroValue::Map(std::mem::take(&mut empty_map)),
24644            AvroValue::Map(nested),
24645        ];
24646        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
24647        let transport = vec![json!({
24648            "schema": MESSAGE_STREAM_SCHEMA,
24649            "stream_name": "orders",
24650            "message_id": "message-1",
24651            "position": 1,
24652            "payload_envelope": payload,
24653        })];
24654
24655        for _ in 0..2 {
24656            let Some(MessageStreamDelivery::Message(message)) =
24657                decode_message_stream_delivery(transport.clone()).expect("delivery")
24658            else {
24659                panic!("message delivery expected");
24660            };
24661            assert_eq!(message.arguments, values);
24662            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
24663            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
24664        }
24665    }
24666
24667    #[test]
24668    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
24669        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24670            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24671                value.to_string(),
24672            )]))
24673            .expect("message payload");
24674            json!({
24675                "schema": MESSAGE_STREAM_SCHEMA,
24676                "stream_name": "orders",
24677                "message_id": message_id,
24678                "position": position,
24679                "payload_envelope": payload,
24680            })
24681        }
24682
24683        fn opened(sequence: u64) -> HistoryEvent {
24684            history_event(
24685                "SignalWaitOpened",
24686                json!({
24687                    "sequence": sequence,
24688                    "signal_name": MESSAGE_STREAM_SIGNAL,
24689                }),
24690            )
24691        }
24692
24693        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24694            history_event(
24695                "SignalApplied",
24696                json!({
24697                    "sequence": sequence,
24698                    "signal_name": MESSAGE_STREAM_SIGNAL,
24699                    "value": fixture_envelope(json!([delivery])),
24700                }),
24701            )
24702        }
24703
24704        fn worker() -> Worker {
24705            let client = Client::new("http://127.0.0.1:8080").expect("client");
24706            let mut worker = Worker::new(client, "rust-workers");
24707            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
24708                let stream = ctx.message_stream("orders")?;
24709                let first = stream.receive_one().await?;
24710                let second = stream.receive_one().await?;
24711                Ok(json!([first.message_id, second.message_id]))
24712            });
24713            worker
24714        }
24715
24716        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
24717            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
24718            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
24719            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
24720            task
24721        }
24722
24723        let waiting = worker()
24724            .execute_workflow_task_decision(workflow_task(
24725                "rust.message-stream",
24726                Vec::new(),
24727                DEFAULT_CODEC,
24728            ))
24729            .expect("first worker opens the stream wait");
24730        assert_eq!(
24731            waiting.commands,
24732            vec![json!({
24733                "type": "open_signal_wait",
24734                "signal_name": MESSAGE_STREAM_SIGNAL,
24735            })]
24736        );
24737        assert!(waiting.message_stream_cursors.is_empty());
24738        assert_eq!(
24739            waiting.message_stream_waits,
24740            vec![json!({"stream_name": "orders", "after_position": 0})]
24741        );
24742
24743        let first_delivery = delivery("message-1", 1, "one");
24744        let first_arrival = worker()
24745            .execute_workflow_task_decision(task_with_resume(
24746                vec![opened(1)],
24747                first_delivery.clone(),
24748            ))
24749            .expect("replacement worker consumes the first arrival");
24750        assert_eq!(
24751            first_arrival.commands,
24752            vec![json!({
24753                "type": "open_signal_wait",
24754                "signal_name": MESSAGE_STREAM_SIGNAL,
24755            })]
24756        );
24757        assert_eq!(
24758            first_arrival.message_stream_cursors,
24759            vec![json!({"stream_name": "orders", "through_position": 1})]
24760        );
24761        assert_eq!(
24762            first_arrival.message_stream_waits,
24763            vec![json!({"stream_name": "orders", "after_position": 1})]
24764        );
24765
24766        let second_delivery = delivery("message-2", 2, "two");
24767        let first_applied = applied(1, first_delivery);
24768        let completed = worker()
24769            .execute_workflow_task_decision(task_with_resume(
24770                vec![opened(1), first_applied.clone(), opened(2)],
24771                second_delivery.clone(),
24772            ))
24773            .expect("next replacement worker consumes the second arrival");
24774        assert_eq!(completed.commands.len(), 1);
24775        assert_eq!(completed.commands[0]["type"], "complete_workflow");
24776        assert_eq!(
24777            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
24778                .expect("workflow result"),
24779            json!(["message-1", "message-2"])
24780        );
24781        assert_eq!(
24782            completed.message_stream_cursors,
24783            vec![json!({"stream_name": "orders", "through_position": 2})]
24784        );
24785        assert!(completed.message_stream_waits.is_empty());
24786
24787        let replay_history = vec![
24788            opened(1),
24789            first_applied,
24790            opened(2),
24791            applied(2, second_delivery),
24792        ];
24793        for _cold_worker_or_restart in 0..2 {
24794            let replayed = worker()
24795                .execute_workflow_task_decision(workflow_task(
24796                    "rust.message-stream",
24797                    replay_history.clone(),
24798                    DEFAULT_CODEC,
24799                ))
24800                .expect("cold worker replays each logical message exactly once");
24801            assert_eq!(replayed.commands.len(), 1);
24802            assert_eq!(
24803                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
24804                    .expect("replayed workflow result"),
24805                json!(["message-1", "message-2"])
24806            );
24807            assert_eq!(
24808                replayed.message_stream_cursors,
24809                vec![json!({"stream_name": "orders", "through_position": 2})]
24810            );
24811            assert!(replayed.message_stream_waits.is_empty());
24812        }
24813    }
24814
24815    #[test]
24816    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
24817        assert!(!worker_protocol_supports_message_streams("1.14"));
24818        assert!(worker_protocol_supports_message_streams("1.15"));
24819        assert!(worker_protocol_supports_message_streams("1.16"));
24820        assert!(worker_protocol_supports_message_streams(
24821            WORKER_PROTOCOL_VERSION
24822        ));
24823        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
24824    }
24825
24826    #[test]
24827    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
24828        let ctx = workflow_context(vec![
24829            history_event(
24830                "ConditionWaitOpened",
24831                json!({
24832                    "sequence": 1,
24833                    "condition_wait_id": "condition:1",
24834                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24835                    "condition_key": "signal:finish",
24836                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24837                }),
24838            ),
24839            history_event(
24840                "ConditionWaitSatisfied",
24841                json!({
24842                    "sequence": 1,
24843                    "condition_wait_id": "condition:1",
24844                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24845                    "condition_key": "signal:finish",
24846                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24847                }),
24848            ),
24849            history_event(
24850                "SignalReceived",
24851                json!({"signal_name": "finish", "arguments": []}),
24852            ),
24853        ]);
24854        let mut signal = Box::pin(ctx.wait_signal("finish"));
24855        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24856
24857        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24858            signal.as_mut().poll(&mut task_context)
24859        else {
24860            panic!("condition history must not resolve as a typed signal wait");
24861        };
24862        assert_eq!(failure.reason, "recorded_command_mismatch");
24863        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
24864    }
24865
24866    #[test]
24867    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
24868        let signal_then_timer = vec![
24869            history_event(
24870                "SignalWaitOpened",
24871                json!({"sequence": 1, "signal_name": "go"}),
24872            ),
24873            history_event(
24874                "SignalApplied",
24875                json!({
24876                    "sequence": 1,
24877                    "signal_name": "go",
24878                    "value": fixture_envelope(json!(["now"])),
24879                }),
24880            ),
24881            history_event(
24882                "TimerScheduled",
24883                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24884            ),
24885            history_event(
24886                "TimerFired",
24887                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24888            ),
24889        ];
24890
24891        let ctx = workflow_context(signal_then_timer.clone());
24892        let mut signal = Box::pin(ctx.wait_signal("go"));
24893        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24894        assert!(matches!(
24895            signal.as_mut().poll(&mut task_context),
24896            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
24897        ));
24898        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
24899        assert!(matches!(
24900            timer.as_mut().poll(&mut task_context),
24901            Poll::Ready(Ok(()))
24902        ));
24903        ctx.ensure_history_consumed()
24904            .expect("signal and timer history consumed in order");
24905
24906        let reordered = workflow_context(signal_then_timer);
24907        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
24908        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24909            timer_first.as_mut().poll(&mut task_context)
24910        else {
24911            panic!("timer cannot consume signal-wait-first history");
24912        };
24913        assert_eq!(failure.reason, "recorded_command_mismatch");
24914        assert_eq!(failure.sequence, Some(1));
24915        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
24916
24917        let timer_then_signal = vec![
24918            history_event(
24919                "TimerScheduled",
24920                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24921            ),
24922            history_event(
24923                "TimerFired",
24924                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24925            ),
24926            history_event(
24927                "SignalWaitOpened",
24928                json!({"sequence": 2, "signal_name": "go"}),
24929            ),
24930            history_event(
24931                "SignalApplied",
24932                json!({
24933                    "sequence": 2,
24934                    "signal_name": "go",
24935                    "value": fixture_envelope(json!([])),
24936                }),
24937            ),
24938        ];
24939        let reordered = workflow_context(timer_then_signal);
24940        let mut signal_first = Box::pin(reordered.wait_signal("go"));
24941        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24942            signal_first.as_mut().poll(&mut task_context)
24943        else {
24944            panic!("signal wait cannot consume timer-first history");
24945        };
24946        assert_eq!(failure.reason, "recorded_command_mismatch");
24947        assert_eq!(failure.sequence, Some(1));
24948        assert_eq!(failure.expected.as_deref(), Some("timer"));
24949    }
24950
24951    #[test]
24952    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
24953        let duplicate_timer = WorkflowState::new(
24954            vec![
24955                history_event(
24956                    "TimerScheduled",
24957                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24958                ),
24959                history_event(
24960                    "TimerScheduled",
24961                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24962                ),
24963            ],
24964            "rust-workers".to_string(),
24965            DEFAULT_CODEC.to_string(),
24966            None,
24967        )
24968        .expect_err("one workflow sequence cannot schedule two timers");
24969        assert!(matches!(
24970            duplicate_timer,
24971            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24972                if reason == "timer_schedule_missing_or_duplicate"
24973        ));
24974
24975        let colliding_kinds = WorkflowState::new(
24976            vec![
24977                history_event(
24978                    "TimerScheduled",
24979                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24980                ),
24981                history_event(
24982                    "ActivityCompleted",
24983                    json!({"sequence": 1, "activity_type": "same-sequence"}),
24984                ),
24985            ],
24986            "rust-workers".to_string(),
24987            DEFAULT_CODEC.to_string(),
24988            None,
24989        )
24990        .expect_err("one workflow sequence cannot identify two command kinds");
24991        assert!(matches!(
24992            colliding_kinds,
24993            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24994                if reason == "durable_command_sequence_collision"
24995        ));
24996
24997        let duplicate_signal_wait = WorkflowState::new(
24998            vec![
24999                history_event(
25000                    "SignalWaitOpened",
25001                    json!({"sequence": 1, "signal_name": "go"}),
25002                ),
25003                history_event(
25004                    "SignalWaitOpened",
25005                    json!({"sequence": 1, "signal_name": "go"}),
25006                ),
25007            ],
25008            "rust-workers".to_string(),
25009            DEFAULT_CODEC.to_string(),
25010            None,
25011        )
25012        .expect_err("one workflow sequence cannot open two signal waits");
25013        assert!(matches!(
25014            duplicate_signal_wait,
25015            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25016                if reason == "signal_wait_open_missing_or_duplicate"
25017        ));
25018    }
25019
25020    #[test]
25021    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
25022        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
25023            .expect("side-effect result");
25024        let ctx = workflow_context(vec![history_event(
25025            "SideEffectRecorded",
25026            json!({"sequence": 99, "result": result}),
25027        )]);
25028
25029        let replayed: Value = ctx
25030            .side_effect(|| panic!("recorded side effect must not run"))
25031            .expect("positive global workflow sequence is valid");
25032        assert_eq!(replayed, json!({"captured": true}));
25033        ctx.ensure_history_consumed().expect("history consumed");
25034    }
25035
25036    #[test]
25037    fn workflow_history_rejects_zero_and_descending_command_sequences() {
25038        let result =
25039            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
25040        let zero = WorkflowState::new(
25041            vec![history_event(
25042                "SideEffectRecorded",
25043                json!({"sequence": 0, "result": result.clone()}),
25044            )],
25045            "rust-workers".to_string(),
25046            DEFAULT_CODEC.to_string(),
25047            None,
25048        )
25049        .expect_err("durable command sequences must be positive");
25050        assert!(matches!(
25051            zero,
25052            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25053                if reason == "durable_command_sequence_invalid"
25054        ));
25055
25056        let descending = WorkflowState::new(
25057            vec![
25058                history_event(
25059                    "SideEffectRecorded",
25060                    json!({"sequence": 3, "result": result}),
25061                ),
25062                history_event(
25063                    "VersionMarkerRecorded",
25064                    json!({
25065                        "sequence": 2,
25066                        "change_id": "descending-marker",
25067                        "version": 1,
25068                        "min_supported": 1,
25069                        "max_supported": 1,
25070                    }),
25071                ),
25072            ],
25073            "rust-workers".to_string(),
25074            DEFAULT_CODEC.to_string(),
25075            None,
25076        )
25077        .expect_err("new durable commands must remain strictly ordered");
25078        let Error::NonDeterministicReplay(failure) = descending else {
25079            panic!("expected typed replay failure");
25080        };
25081        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
25082        assert_eq!(failure.sequence, Some(2));
25083        assert_eq!(
25084            failure.expected.as_deref(),
25085            Some("workflow sequence greater than 3")
25086        );
25087        assert_eq!(failure.actual.as_deref(), Some("2"));
25088    }
25089
25090    #[test]
25091    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
25092        fn worker() -> Worker {
25093            let client = Client::new("http://127.0.0.1:8080").expect("client");
25094            let mut worker = Worker::new(client, "rust-workers");
25095            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
25096                ctx.wait_signal("finish").await?;
25097                let marker: String =
25098                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
25099                assert_eq!(marker, "after-finish");
25100                Ok(json!("finished"))
25101            });
25102            worker
25103        }
25104
25105        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
25106            .expect("side-effect result");
25107        let task = workflow_task(
25108            "rust.finish-after-gaps",
25109            vec![
25110                history_event(
25111                    "SignalWaitOpened",
25112                    json!({"sequence": 1, "signal_name": "finish"}),
25113                ),
25114                history_event(
25115                    "SignalReceived",
25116                    json!({
25117                        "signal_id": "increment-3",
25118                        "signal_name": "increment",
25119                        "workflow_sequence": 2,
25120                        "payload_codec": DEFAULT_CODEC,
25121                        "arguments": fixture_envelope(json!([3])),
25122                    }),
25123                ),
25124                history_event(
25125                    "SignalReceived",
25126                    json!({
25127                        "signal_id": "increment-5",
25128                        "signal_name": "increment",
25129                        "workflow_sequence": 3,
25130                        "payload_codec": DEFAULT_CODEC,
25131                        "arguments": fixture_envelope(json!([5])),
25132                    }),
25133                ),
25134                history_event(
25135                    "SignalReceived",
25136                    json!({
25137                        "signal_id": "finish",
25138                        "signal_name": "finish",
25139                        "workflow_sequence": 4,
25140                        "payload_codec": DEFAULT_CODEC,
25141                        "arguments": fixture_envelope(json!([])),
25142                    }),
25143                ),
25144                history_event(
25145                    "SignalApplied",
25146                    json!({
25147                        "sequence": 1,
25148                        "signal_id": "finish",
25149                        "signal_name": "finish",
25150                        "payload_codec": DEFAULT_CODEC,
25151                        "value": fixture_envelope(json!([])),
25152                    }),
25153                ),
25154                history_event(
25155                    "SideEffectRecorded",
25156                    json!({"sequence": 5, "result": marker}),
25157                ),
25158            ],
25159            DEFAULT_CODEC,
25160        );
25161
25162        for _original_or_cold_worker in 0..2 {
25163            let commands = worker()
25164                .execute_workflow_task(task.clone())
25165                .expect("signal gaps preserve deterministic replay");
25166            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
25167            assert_eq!(commands[0]["type"], "complete_workflow");
25168            assert_eq!(
25169                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
25170                json!("finished")
25171            );
25172        }
25173    }
25174
25175    #[test]
25176    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
25177        let ctx = workflow_context(Vec::new());
25178        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
25179        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25180        assert!(matches!(
25181            sleep.as_mut().poll(&mut task_context),
25182            Poll::Ready(Err(Error::TimerDurationOverflow))
25183        ));
25184        assert!(ctx.take_commands().expect("commands").is_empty());
25185    }
25186
25187    #[test]
25188    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
25189        let entries = AvroValue::Map(BTreeMap::from([
25190            ("text".to_string(), AvroValue::String("same".to_string())),
25191            (
25192                "nested".to_string(),
25193                AvroValue::Map(BTreeMap::from([
25194                    ("beta".to_string(), AvroValue::Long(2)),
25195                    ("alpha".to_string(), AvroValue::Long(1)),
25196                ])),
25197            ),
25198            ("long".to_string(), AvroValue::Long(7)),
25199            ("double".to_string(), AvroValue::Double(7.0)),
25200            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
25201        ]));
25202        let ctx = workflow_context(Vec::new());
25203        ctx.upsert_memo(entries.clone()).expect("valid memo update");
25204        let commands = ctx.take_commands().expect("commands");
25205
25206        assert_eq!(commands.len(), 1);
25207        assert_eq!(commands[0]["type"], "upsert_memo");
25208        let server_entries = json!({
25209            "codec": "avro",
25210            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
25211        });
25212        assert_eq!(
25213            commands[0]["entries"]
25214                .as_object()
25215                .expect("entries envelope")
25216                .keys()
25217                .collect::<Vec<_>>(),
25218            vec!["blob", "codec"]
25219        );
25220        assert_eq!(commands[0]["entries"], server_entries);
25221        let wire_entries =
25222            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
25223        assert_eq!(wire_entries, entries);
25224
25225        let history = vec![history_event(
25226            "MemoUpserted",
25227            json!({
25228                "sequence": 1,
25229                "entries": server_entries.clone(),
25230                "merged": server_entries,
25231            }),
25232        )];
25233        let replay = workflow_context(history.clone());
25234        replay
25235            .upsert_memo(entries.clone())
25236            .expect("matching replay identity");
25237        assert!(replay.take_commands().expect("replay commands").is_empty());
25238
25239        let changed_types = AvroValue::Map(BTreeMap::from([
25240            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
25241            (
25242                "nested".to_string(),
25243                AvroValue::Map(BTreeMap::from([
25244                    ("alpha".to_string(), AvroValue::Long(1)),
25245                    ("beta".to_string(), AvroValue::Long(2)),
25246                ])),
25247            ),
25248            ("long".to_string(), AvroValue::Double(7.0)),
25249            ("double".to_string(), AvroValue::Long(7)),
25250            ("binary".to_string(), AvroValue::String("same".to_string())),
25251        ]));
25252        let error = workflow_context(history)
25253            .upsert_memo(changed_types)
25254            .expect_err("memo replay identity must preserve Avro value types");
25255        assert!(matches!(
25256            error,
25257            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25258        ));
25259    }
25260
25261    #[test]
25262    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
25263        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
25264            .expect("memo envelope");
25265        let replay = workflow_context(vec![history_event(
25266            "MemoUpserted",
25267            json!({
25268                "sequence": 1,
25269                "entries": original.clone(),
25270                "merged": original
25271            }),
25272        )]);
25273        let error = replay
25274            .upsert_memo(json!({"stage": "changed"}))
25275            .expect_err("changed memo update must fail replay");
25276        assert!(matches!(
25277            error,
25278            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25279        ));
25280
25281        let invalid = workflow_context(Vec::new())
25282            .upsert_memo(
25283                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
25284            )
25285            .expect_err("oversized key");
25286        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
25287    }
25288
25289    #[test]
25290    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
25291        let negative_zero = AvroValue::Map(BTreeMap::from([(
25292            "reading".to_string(),
25293            AvroValue::Double(-0.0),
25294        )]));
25295        let negative_zero_envelope =
25296            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
25297        let history = vec![history_event(
25298            "MemoUpserted",
25299            json!({
25300                "sequence": 1,
25301                "entries": negative_zero_envelope.clone(),
25302                "merged": negative_zero_envelope,
25303            }),
25304        )];
25305
25306        workflow_context(history.clone())
25307            .upsert_memo(negative_zero)
25308            .expect("matching negative-zero history identity");
25309
25310        let error = workflow_context(history)
25311            .upsert_memo(AvroValue::Map(BTreeMap::from([(
25312                "reading".to_string(),
25313                AvroValue::Double(0.0),
25314            )])))
25315            .expect_err("positive zero must not consume negative-zero memo history");
25316        assert!(matches!(
25317            error,
25318            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25319        ));
25320    }
25321
25322    #[test]
25323    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
25324        let supported = json!({
25325            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
25326            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
25327        });
25328        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
25329        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
25330            "workflow_memo_updates": {"supported": false},
25331            "supported_workflow_task_commands": ["upsert_memo"]
25332        }))));
25333        assert!(commands_use_workflow_memo_updates(&[json!({
25334            "type": "upsert_memo",
25335            "entries": {"stage": "processing"}
25336        })]));
25337    }
25338
25339    #[test]
25340    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
25341        let client = Client::new("http://127.0.0.1:8080").expect("client");
25342        let mut worker = Worker::new(client, "rust-workers");
25343        worker.register_workflow("rust.timer", |ctx, _input| async move {
25344            ctx.sleep(Duration::from_secs(5)).await?;
25345            ctx.activity("after-timer", json!([])).await
25346        });
25347
25348        let task = |history_events| WorkflowTask {
25349            task_id: "wft-rust-timer-1".to_string(),
25350            observability_context: None,
25351            dispatch_observability_context: None,
25352            observability_links: None,
25353            workflow_command_id: None,
25354            workflow_id: Some("wf-rust-timer".to_string()),
25355            run_id: Some("run-rust-timer".to_string()),
25356            workflow_type: "rust.timer".to_string(),
25357            cancel_requested: false,
25358            payload_codec: DEFAULT_CODEC.to_string(),
25359            arguments: Some(
25360                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25361            ),
25362            history_events,
25363            total_history_events: None,
25364            history_size_bytes: None,
25365            continue_as_new_recommended: None,
25366            history_budget_pressure: None,
25367            next_history_page_token: None,
25368            workflow_task_attempt: 1,
25369            workflow_signal_id: None,
25370            signal_name: None,
25371            signal_arguments: None,
25372            workflow_update_id: None,
25373            update_name: None,
25374            lease_owner: Some("rust-worker".to_string()),
25375        };
25376
25377        let initial = worker
25378            .execute_workflow_task(task(Vec::new()))
25379            .expect("initial timer task");
25380        assert_eq!(
25381            initial,
25382            vec![json!({"type": "start_timer", "delay_seconds": 5})]
25383        );
25384
25385        let activity_result =
25386            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
25387        let replayed = worker
25388            .execute_workflow_task(task(vec![
25389                history_event(
25390                    "TimerScheduled",
25391                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25392                ),
25393                history_event(
25394                    "TimerFired",
25395                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25396                ),
25397                history_event(
25398                    "ActivityCompleted",
25399                    json!({
25400                        "sequence": 2,
25401                        "activity_type": "after-timer",
25402                        "payload_codec": DEFAULT_CODEC,
25403                        "result": activity_result,
25404                    }),
25405                ),
25406            ]))
25407            .expect("replayed workflow task");
25408        assert_eq!(replayed.len(), 1);
25409        assert_eq!(replayed[0]["type"], "complete_workflow");
25410        assert_eq!(
25411            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
25412            json!("done")
25413        );
25414    }
25415
25416    #[test]
25417    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
25418        let client = Client::new("http://127.0.0.1:8080").expect("client");
25419        let mut worker = Worker::new(client, "rust-workers");
25420        worker.register_workflow("rust.continue", |ctx, _input| async move {
25421            ctx.continue_as_new_with_options(
25422                ContinueAsNewOptions::new()
25423                    .workflow_type("rust.next")
25424                    .task_queue("next-workers"),
25425                json!([2, {"cursor": "next"}]),
25426            )
25427        });
25428
25429        let commands = worker
25430            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
25431            .expect("continue-as-new command");
25432
25433        assert_eq!(commands.len(), 1);
25434        assert_eq!(commands[0]["type"], "continue_as_new");
25435        assert_eq!(commands[0]["workflow_type"], "rust.next");
25436        assert_eq!(commands[0]["queue"], "next-workers");
25437        assert_eq!(
25438            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
25439                .expect("continue-as-new arguments"),
25440            json!([2, {"cursor": "next"}])
25441        );
25442    }
25443
25444    #[test]
25445    fn continue_as_new_preserves_typed_arguments() {
25446        let client = Client::new("http://127.0.0.1:8080").expect("client");
25447        let mut worker = Worker::new(client, "rust-workers");
25448        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
25449            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
25450            unreachable!("continue-as-new returns a control-flow error")
25451        });
25452
25453        let commands = worker
25454            .execute_workflow_task(workflow_task(
25455                "rust.typed-continue",
25456                Vec::new(),
25457                DEFAULT_CODEC,
25458            ))
25459            .expect("typed continue-as-new command");
25460
25461        assert_eq!(commands[0]["type"], "continue_as_new");
25462        assert_eq!(
25463            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
25464                .expect("typed continue arguments"),
25465            AvroValue::Array(vec![typed_fidelity_probe()])
25466        );
25467    }
25468
25469    #[test]
25470    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
25471        let client = Client::new("http://127.0.0.1:8080").expect("client");
25472        let mut worker = Worker::new(client, "rust-workers");
25473        worker.register_workflow("rust.continue", |ctx, _input| async move {
25474            ctx.continue_as_new(json!([2]))
25475        });
25476        let task = workflow_task(
25477            "rust.continue",
25478            vec![history_event(
25479                "WorkflowContinuedAsNew",
25480                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
25481            )],
25482            DEFAULT_CODEC,
25483        );
25484
25485        for _worker_restart_or_redelivery in 0..2 {
25486            let commands = worker
25487                .execute_workflow_task(task.clone())
25488                .expect("recorded transition replays");
25489            assert!(
25490                commands.is_empty(),
25491                "replay must not emit another successor"
25492            );
25493        }
25494    }
25495
25496    #[test]
25497    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
25498        let ctx = workflow_context(Vec::new());
25499        let error = ctx
25500            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
25501            .expect_err("blank queue must be rejected");
25502
25503        let Error::InvalidContinueAsNewOptions(error) = error else {
25504            panic!("expected typed continue-as-new validation error");
25505        };
25506        assert_eq!(error.field, "task_queue");
25507        assert!(ctx.take_commands().expect("commands").is_empty());
25508    }
25509
25510    #[test]
25511    fn workflow_context_exposes_server_history_budget() {
25512        let client = Client::new("http://127.0.0.1:8080").expect("client");
25513        let mut worker = Worker::new(client, "rust-workers");
25514        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
25515            let budget = ctx.history_budget()?;
25516            Ok(json!({
25517                "events": budget.event_count,
25518                "bytes": budget.size_bytes,
25519                "recommended": budget.continue_as_new_recommended,
25520                "pressure": budget.pressure,
25521            }))
25522        });
25523        let task: WorkflowTask = serde_json::from_value(json!({
25524            "task_id": "task-history-budget",
25525            "workflow_type": "rust.history-budget",
25526            "payload_codec": DEFAULT_CODEC,
25527            "history_events": [],
25528            "total_history_events": 480,
25529            "history_size_bytes": 1_048_576,
25530            "continue_as_new_recommended": true,
25531            "history_budget_pressure": "continue_as_new_recommended",
25532        }))
25533        .expect("published workflow task");
25534
25535        let commands = worker
25536            .execute_workflow_task(task)
25537            .expect("history-budget workflow");
25538        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
25539        assert_eq!(result["events"], 480);
25540        assert_eq!(result["bytes"], 1_048_576);
25541        assert_eq!(result["recommended"], true);
25542        assert_eq!(result["pressure"], "continue_as_new_recommended");
25543    }
25544
25545    #[test]
25546    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
25547        let client = Client::new("http://127.0.0.1:8080").expect("client");
25548        let mut worker = Worker::new(client, "rust-workers");
25549        worker.register_workflow("rust.failing", |_ctx, _input| async move {
25550            Err(Error::Codec("rust_conformance_failure".to_string()))
25551        });
25552        let task = WorkflowTask {
25553            task_id: "wft-rust-failing-1".to_string(),
25554            observability_context: None,
25555            dispatch_observability_context: None,
25556            observability_links: None,
25557            workflow_command_id: None,
25558            workflow_id: Some("wf-rust-failing".to_string()),
25559            run_id: Some("run-rust-failing".to_string()),
25560            workflow_type: "rust.failing".to_string(),
25561            cancel_requested: false,
25562            payload_codec: DEFAULT_CODEC.to_string(),
25563            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25564            history_events: Vec::new(),
25565            total_history_events: Some(0),
25566            history_size_bytes: None,
25567            continue_as_new_recommended: None,
25568            history_budget_pressure: None,
25569            next_history_page_token: None,
25570            workflow_task_attempt: 1,
25571            workflow_signal_id: None,
25572            signal_name: None,
25573            signal_arguments: None,
25574            workflow_update_id: None,
25575            update_name: None,
25576            lease_owner: Some("rust-worker".to_string()),
25577        };
25578
25579        let commands = worker
25580            .execute_workflow_task(task)
25581            .expect("handler failure becomes a workflow command");
25582
25583        assert_eq!(commands.len(), 1);
25584        assert_eq!(commands[0]["type"], "fail_workflow");
25585        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
25586        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
25587        assert_eq!(commands[0]["non_retryable"], false);
25588        assert_eq!(
25589            commands[0]["message"],
25590            "codec error: rust_conformance_failure"
25591        );
25592        assert_eq!(
25593            commands[0]["exception"]["message"],
25594            "codec error: rust_conformance_failure"
25595        );
25596    }
25597
25598    #[test]
25599    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
25600        let client = Client::new("http://127.0.0.1:8080").expect("client");
25601        let mut worker = Worker::new(client, "rust-workers");
25602        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
25603            let _: String = ctx.side_effect(|| "captured".to_string())?;
25604            Err(Error::WorkerLoop("application failure".to_string()))
25605        });
25606
25607        let commands = worker
25608            .execute_workflow_task(workflow_task(
25609                "rust.failing-after-side-effect",
25610                Vec::new(),
25611                DEFAULT_CODEC,
25612            ))
25613            .expect("ordinary failure remains a workflow decision");
25614
25615        assert_eq!(commands.len(), 2);
25616        assert_eq!(commands[0]["type"], "record_side_effect");
25617        assert_eq!(commands[1]["type"], "fail_workflow");
25618    }
25619
25620    #[test]
25621    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
25622        let client = Client::new("http://127.0.0.1:8080").expect("client");
25623        let mut worker = Worker::new(client, "rust-workers");
25624        worker.register_workflow("rust.redrive", |ctx, _input| async move {
25625            ctx.activity("greet", json!([])).await?;
25626            Ok(Value::Null)
25627        });
25628        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
25629            match ctx.activity("greet", json!([])).await {
25630                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
25631                result => result,
25632            }
25633        });
25634
25635        let failed = history_event(
25636            "ActivityFailed",
25637            json!({
25638                "sequence": 1,
25639                "activity_type": "greet",
25640                "activity_execution_id": "activity-1",
25641                "message": "failed"
25642            }),
25643        );
25644        let commands = worker
25645            .execute_workflow_task(workflow_task(
25646                "rust.redrive",
25647                vec![failed.clone()],
25648                DEFAULT_CODEC,
25649            ))
25650            .expect("recorded failure becomes a workflow command");
25651        assert_eq!(commands[0]["type"], "fail_workflow");
25652        assert_eq!(commands[0]["failed_step_sequence"], 1);
25653        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
25654
25655        let translated = worker
25656            .execute_workflow_task(workflow_task(
25657                "rust.redrive-translated",
25658                vec![failed],
25659                DEFAULT_CODEC,
25660            ))
25661            .expect("translated failure becomes a workflow command");
25662        assert_eq!(translated[0]["type"], "fail_workflow");
25663        assert!(translated[0].get("failed_step_sequence").is_none());
25664        assert!(translated[0].get("failed_activity_execution_id").is_none());
25665
25666        let without_identity = worker
25667            .execute_workflow_task(workflow_task(
25668                "rust.redrive",
25669                vec![history_event(
25670                    "ActivityFailed",
25671                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
25672                )],
25673                DEFAULT_CODEC,
25674            ))
25675            .expect("incomplete identity still fails the workflow");
25676        assert!(without_identity[0].get("failed_step_sequence").is_none());
25677
25678        let timed_out = worker
25679            .execute_workflow_task(workflow_task(
25680                "rust.redrive",
25681                vec![history_event(
25682                    "ActivityTimedOut",
25683                    json!({
25684                        "sequence": 1,
25685                        "activity_type": "greet",
25686                        "activity_execution_id": "activity-timeout",
25687                    }),
25688                )],
25689                DEFAULT_CODEC,
25690            ))
25691            .expect("timeout still fails the workflow");
25692        assert!(timed_out[0].get("failed_step_sequence").is_none());
25693    }
25694
25695    #[test]
25696    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
25697        let client = Client::new("http://127.0.0.1:8080").expect("client");
25698        let mut worker = Worker::new(client, "rust-workers");
25699        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
25700            let first = ctx.activity("first", json!([])).await?;
25701            let second = ctx.activity("second", json!([first.clone()])).await?;
25702            Ok(json!({"first": first, "second": second}))
25703        });
25704        let first = history_event(
25705            "ActivityCompleted",
25706            json!({
25707                "sequence": 1,
25708                "activity_type": "first",
25709                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
25710                "payload_codec": DEFAULT_CODEC,
25711                "reused_from_run_id": "failed-run",
25712                "reused_activity_execution_id": "original-first",
25713            }),
25714        );
25715
25716        let retry = worker
25717            .execute_workflow_task(workflow_task(
25718                "rust.redrive-successor",
25719                vec![first.clone()],
25720                DEFAULT_CODEC,
25721            ))
25722            .expect("reused result replays before failed step");
25723        assert_eq!(retry.len(), 1);
25724        assert_eq!(retry[0]["type"], "schedule_activity");
25725        assert_eq!(retry[0]["activity_type"], "second");
25726        assert_eq!(
25727            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
25728            json!(["recorded"]),
25729        );
25730
25731        let second = history_event(
25732            "ActivityCompleted",
25733            json!({
25734                "sequence": 2,
25735                "activity_type": "second",
25736                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
25737                "payload_codec": DEFAULT_CODEC,
25738            }),
25739        );
25740        let completed = worker
25741            .execute_workflow_task(workflow_task(
25742                "rust.redrive-successor",
25743                vec![first, second],
25744                DEFAULT_CODEC,
25745            ))
25746            .expect("retried step completes the successor");
25747        assert_eq!(completed.len(), 1);
25748        assert_eq!(completed[0]["type"], "complete_workflow");
25749        assert_eq!(
25750            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
25751            json!({"first": "recorded", "second": "retried"}),
25752        );
25753    }
25754
25755    #[test]
25756    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
25757        let client = Client::new("http://127.0.0.1:8080").expect("client");
25758        let mut worker = Worker::new(client, "rust-workers");
25759        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
25760            Err(Error::WorkerLoop("application failure".to_string()))
25761        });
25762        let result =
25763            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
25764
25765        let error = worker
25766            .execute_workflow_task(workflow_task(
25767                "rust.removed-side-effect",
25768                vec![history_event(
25769                    "SideEffectRecorded",
25770                    json!({"sequence": 1, "result": result}),
25771                )],
25772                DEFAULT_CODEC,
25773            ))
25774            .expect_err("removed committed history must not become fail_workflow");
25775
25776        let Error::NonDeterministicReplay(failure) = error else {
25777            panic!("expected typed replay failure");
25778        };
25779        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25780        assert_eq!(failure.sequence, Some(1));
25781        assert_eq!(failure.expected.as_deref(), Some("side effect"));
25782    }
25783
25784    #[test]
25785    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
25786        let client = Client::new("http://127.0.0.1:8080").expect("client");
25787        let mut worker = Worker::new(client, "rust-workers");
25788        worker.register_workflow(
25789            "rust.side-effect-before-marker-error",
25790            |ctx, _input| async move {
25791                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
25792                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
25793                ctx.get_version("restart-safe", 2, 2)?;
25794                Ok(Value::Null)
25795            },
25796        );
25797
25798        let error = worker
25799            .execute_workflow_task(workflow_task(
25800                "rust.side-effect-before-marker-error",
25801                vec![history_event(
25802                    "VersionMarkerRecorded",
25803                    json!({
25804                        "sequence": 1,
25805                        "change_id": "restart-safe",
25806                        "version": 1,
25807                        "min_supported": 1,
25808                        "max_supported": 1,
25809                    }),
25810                )],
25811                DEFAULT_CODEC,
25812            ))
25813            .expect_err("replay error must return no queued workflow commands");
25814
25815        let Error::NonDeterministicReplay(failure) = error else {
25816            panic!("expected typed replay failure");
25817        };
25818        assert_eq!(failure.reason, "version_marker_incompatible_range");
25819        assert_eq!(failure.sequence, Some(1));
25820    }
25821
25822    #[test]
25823    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
25824        let client = Client::new("http://127.0.0.1:8080").expect("client");
25825        let mut worker = Worker::new(client, "rust-workers");
25826        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
25827            ctx.sleep(Duration::from_secs(5)).await?;
25828            Ok(json!({"status": "timer fired"}))
25829        });
25830
25831        let task = WorkflowTask {
25832            task_id: "wft-rust-timer-pending".to_string(),
25833            observability_context: None,
25834            dispatch_observability_context: None,
25835            observability_links: None,
25836            workflow_command_id: None,
25837            workflow_id: Some("wf-rust-timer".to_string()),
25838            run_id: Some("run-rust-timer".to_string()),
25839            workflow_type: "rust.timer.pending".to_string(),
25840            cancel_requested: false,
25841            payload_codec: DEFAULT_CODEC.to_string(),
25842            arguments: Some(
25843                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25844            ),
25845            history_events: vec![history_event(
25846                "TimerScheduled",
25847                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25848            )],
25849            total_history_events: Some(1),
25850            history_size_bytes: None,
25851            continue_as_new_recommended: None,
25852            history_budget_pressure: None,
25853            next_history_page_token: None,
25854            workflow_task_attempt: 1,
25855            workflow_signal_id: None,
25856            signal_name: None,
25857            signal_arguments: None,
25858            workflow_update_id: None,
25859            update_name: None,
25860            lease_owner: Some("rust-worker".to_string()),
25861        };
25862
25863        for _redelivery_or_restart in 0..2 {
25864            let commands = worker
25865                .execute_workflow_task(task.clone())
25866                .expect("recorded timer remains pending");
25867            assert!(
25868                commands.is_empty(),
25869                "recorded timer must not be rescheduled"
25870            );
25871        }
25872    }
25873
25874    #[test]
25875    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
25876        let client = Client::new("http://127.0.0.1:8080").expect("client");
25877        let mut worker = Worker::new(client, "rust-workers");
25878        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
25879            Ok(json!({"status": "completed"}))
25880        });
25881        let task = WorkflowTask {
25882            task_id: "wft-rust-timer-removed".to_string(),
25883            observability_context: None,
25884            dispatch_observability_context: None,
25885            observability_links: None,
25886            workflow_command_id: None,
25887            workflow_id: Some("wf-rust-timer".to_string()),
25888            run_id: Some("run-rust-timer".to_string()),
25889            workflow_type: "rust.timer.removed".to_string(),
25890            cancel_requested: false,
25891            payload_codec: DEFAULT_CODEC.to_string(),
25892            arguments: Some(
25893                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25894            ),
25895            history_events: vec![
25896                history_event(
25897                    "TimerScheduled",
25898                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25899                ),
25900                history_event(
25901                    "TimerFired",
25902                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25903                ),
25904            ],
25905            total_history_events: Some(2),
25906            history_size_bytes: None,
25907            continue_as_new_recommended: None,
25908            history_budget_pressure: None,
25909            next_history_page_token: None,
25910            workflow_task_attempt: 1,
25911            workflow_signal_id: None,
25912            signal_name: None,
25913            signal_arguments: None,
25914            workflow_update_id: None,
25915            update_name: None,
25916            lease_owner: Some("rust-worker".to_string()),
25917        };
25918
25919        let Error::NonDeterministicReplay(failure) = worker
25920            .execute_workflow_task(task)
25921            .expect_err("removed timer must fail replay")
25922        else {
25923            panic!("expected typed replay failure");
25924        };
25925        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25926        assert_eq!(failure.sequence, Some(1));
25927    }
25928
25929    #[test]
25930    fn workflow_context_emits_explicit_child_workflow_contract() {
25931        let ctx = WorkflowContext {
25932            cancellation_scope_id: "root".into(),
25933            state: Arc::new(Mutex::new(
25934                WorkflowState::new_with_identity(
25935                    Vec::new(),
25936                    Some("wf-parent".to_string()),
25937                    Some("run-parent".to_string()),
25938                    "parent-workers".to_string(),
25939                    DEFAULT_CODEC.to_string(),
25940                    None,
25941                )
25942                .expect("workflow state"),
25943            )),
25944        };
25945        let options = ChildWorkflowOptions::new("python-workers")
25946            .parent_close_policy(ParentClosePolicy::RequestCancel)
25947            .retry_policy(ChildWorkflowRetryPolicy {
25948                max_attempts: Some(3),
25949                backoff_seconds: vec![1, 5],
25950                non_retryable_error_types: vec!["ValidationError".to_string()],
25951            })
25952            .execution_timeout_seconds(600)
25953            .run_timeout_seconds(120);
25954        let mut call = Box::pin(ctx.start_child_workflow(
25955            "python.fulfil-order",
25956            options,
25957            json!([{"order_id": "order-42"}]),
25958        ));
25959        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25960
25961        assert!(matches!(
25962            call.as_mut().poll(&mut task_context),
25963            Poll::Pending
25964        ));
25965        let commands = ctx.take_commands().expect("commands");
25966        assert_eq!(commands.len(), 1);
25967        let command = &commands[0];
25968        assert_eq!(command["type"], "start_child_workflow");
25969        assert_eq!(command["workflow_type"], "python.fulfil-order");
25970        assert_eq!(command["queue"], "python-workers");
25971        assert_eq!(command["parent_close_policy"], "request_cancel");
25972        assert_eq!(command["retry_policy"]["max_attempts"], 3);
25973        assert_eq!(command["execution_timeout_seconds"], 600);
25974        assert_eq!(command["run_timeout_seconds"], 120);
25975        assert_eq!(
25976            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
25977            json!([{"order_id": "order-42"}])
25978        );
25979    }
25980
25981    fn child_parent_worker() -> Worker {
25982        let client = Client::new("http://127.0.0.1:8080").expect("client");
25983        let mut worker = Worker::new(client, "rust-parent-workers");
25984        worker.register_workflow("rust.parent", |ctx, _input| async move {
25985            let child = ctx
25986                .start_child_workflow(
25987                    "python.child",
25988                    ChildWorkflowOptions::new("python-child-workers")
25989                        .parent_close_policy(ParentClosePolicy::Terminate),
25990                    json!([{"codec_probe": [1, true, "rust"]}]),
25991                )
25992                .await?;
25993            Ok(json!({
25994                "parent_workflow_id": child.parent.workflow_id,
25995                "parent_run_id": child.parent.run_id,
25996                "child_workflow_id": child.child.workflow_id,
25997                "child_run_id": child.child.run_id,
25998                "child_workflow_type": child.child_workflow_type,
25999                "result": child.result,
26000            }))
26001        });
26002        worker
26003    }
26004
26005    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
26006        WorkflowTask {
26007            task_id: "wft-child-parent".to_string(),
26008            observability_context: None,
26009            dispatch_observability_context: None,
26010            observability_links: None,
26011            workflow_command_id: None,
26012            workflow_id: Some("wf-parent".to_string()),
26013            run_id: Some("run-parent".to_string()),
26014            workflow_type: "rust.parent".to_string(),
26015            cancel_requested: false,
26016            payload_codec: DEFAULT_CODEC.to_string(),
26017            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26018            history_events: vec![
26019                HistoryEvent {
26020                    event_type: "ChildWorkflowScheduled".to_string(),
26021                    payload: json!({
26022                        "sequence": 1,
26023                        "child_call_id": "call-child",
26024                        "child_workflow_instance_id": "wf-child",
26025                        "child_workflow_run_id": "run-child",
26026                        "child_workflow_type": "python.child",
26027                        "parent_close_policy": "terminate",
26028                    }),
26029                    raw: HashMap::new(),
26030                },
26031                HistoryEvent {
26032                    event_type: event_type.to_string(),
26033                    payload,
26034                    raw: HashMap::new(),
26035                },
26036            ],
26037            total_history_events: Some(2),
26038            history_size_bytes: None,
26039            continue_as_new_recommended: None,
26040            history_budget_pressure: None,
26041            next_history_page_token: None,
26042            workflow_task_attempt: 1,
26043            workflow_signal_id: None,
26044            signal_name: None,
26045            signal_arguments: None,
26046            workflow_update_id: None,
26047            update_name: None,
26048            lease_owner: Some("rust-worker".to_string()),
26049        }
26050    }
26051
26052    #[test]
26053    fn committed_child_result_replays_without_starting_a_duplicate() {
26054        let worker = child_parent_worker();
26055        let task = child_parent_task(
26056            "ChildRunCompleted",
26057            json!({
26058                "sequence": 1,
26059                "child_call_id": "call-child",
26060                "child_workflow_instance_id": "wf-child",
26061                "child_workflow_run_id": "run-child",
26062                "child_workflow_type": "python.child",
26063                "payload_codec": DEFAULT_CODEC,
26064                "result": fixture_envelope(json!({"from":"python","ok":true})),
26065            }),
26066        );
26067
26068        for _restart in 0..2 {
26069            let commands = worker
26070                .execute_workflow_task(task.clone())
26071                .expect("replayed parent task");
26072            assert_eq!(commands.len(), 1);
26073            assert_eq!(commands[0]["type"], "complete_workflow");
26074            assert!(!commands
26075                .iter()
26076                .any(|command| command["type"] == "start_child_workflow"));
26077            let output =
26078                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26079            assert_eq!(output["parent_workflow_id"], "wf-parent");
26080            assert_eq!(output["parent_run_id"], "run-parent");
26081            assert_eq!(output["child_workflow_id"], "wf-child");
26082            assert_eq!(output["child_run_id"], "run-child");
26083            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
26084        }
26085    }
26086
26087    #[test]
26088    fn typed_child_arguments_and_results_survive_replay() {
26089        let client = Client::new("http://127.0.0.1:8080").expect("client");
26090        let mut worker = Worker::new(client, "rust-parent-workers");
26091        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
26092            let child = ctx
26093                .start_child_workflow_avro_value(
26094                    "python.typed-child",
26095                    ChildWorkflowOptions::new("python-workers"),
26096                    AvroValue::Array(vec![typed_fidelity_probe()]),
26097                )
26098                .await?;
26099            Ok(child.result)
26100        });
26101
26102        let initial = worker
26103            .execute_workflow_task(workflow_task(
26104                "rust.typed-parent",
26105                Vec::new(),
26106                DEFAULT_CODEC,
26107            ))
26108            .expect("typed child start");
26109        assert_eq!(initial[0]["type"], "start_child_workflow");
26110        assert_eq!(
26111            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
26112                .expect("typed child arguments"),
26113            AvroValue::Array(vec![typed_fidelity_probe()])
26114        );
26115
26116        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
26117            .expect("typed child result");
26118        let task = workflow_task(
26119            "rust.typed-parent",
26120            vec![
26121                history_event(
26122                    "ChildWorkflowScheduled",
26123                    json!({
26124                        "sequence": 1,
26125                        "child_call_id": "call-typed",
26126                        "child_workflow_instance_id": "wf-child",
26127                        "child_workflow_run_id": "run-child",
26128                        "child_workflow_type": "python.typed-child",
26129                    }),
26130                ),
26131                history_event(
26132                    "ChildRunCompleted",
26133                    json!({
26134                        "sequence": 1,
26135                        "child_call_id": "call-typed",
26136                        "child_workflow_instance_id": "wf-child",
26137                        "child_workflow_run_id": "run-child",
26138                        "child_workflow_type": "python.typed-child",
26139                        "payload_codec": DEFAULT_CODEC,
26140                        "result": result,
26141                    }),
26142                ),
26143            ],
26144            DEFAULT_CODEC,
26145        );
26146
26147        let commands = worker
26148            .execute_workflow_task(task)
26149            .expect("typed child replay");
26150        assert_eq!(commands[0]["type"], "complete_workflow");
26151        assert_eq!(
26152            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
26153                .expect("typed parent result"),
26154            typed_fidelity_probe()
26155        );
26156    }
26157
26158    #[test]
26159    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
26160        let worker = child_parent_worker();
26161        let mut task = child_parent_task("unused", Value::Null);
26162        task.history_events.truncate(1);
26163        task.total_history_events = Some(1);
26164
26165        for _redelivery_or_restart in 0..2 {
26166            let commands = worker
26167                .execute_workflow_task(task.clone())
26168                .expect("recorded child remains pending");
26169            assert!(
26170                commands.is_empty(),
26171                "recorded pending child must not be started again"
26172            );
26173        }
26174    }
26175
26176    #[test]
26177    fn child_cancellation_becomes_stable_parent_failure_command() {
26178        let worker = child_parent_worker();
26179        let task = child_parent_task(
26180            "ChildRunCancelled",
26181            json!({
26182                "sequence": 1,
26183                "child_workflow_instance_id": "wf-child",
26184                "child_workflow_run_id": "run-child",
26185                "child_workflow_type": "python.child",
26186                "failure_id": "failure-child",
26187                "failure_category": "cancelled",
26188                "message": "cancelled by parent-close policy",
26189            }),
26190        );
26191
26192        let commands = worker
26193            .execute_workflow_task(task)
26194            .expect("parent settlement");
26195        assert_eq!(commands.len(), 1);
26196        assert_eq!(commands[0]["type"], "fail_workflow");
26197        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
26198        assert_eq!(
26199            commands[0]["exception"]["properties"]["reason"],
26200            "cancelled"
26201        );
26202        assert_eq!(
26203            commands[0]["exception"]["properties"]["child_workflow_run_id"],
26204            "run-child"
26205        );
26206    }
26207
26208    #[test]
26209    fn workflow_can_handle_typed_child_failure() {
26210        let client = Client::new("http://127.0.0.1:8080").expect("client");
26211        let mut worker = Worker::new(client, "rust-parent-workers");
26212        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
26213            match ctx
26214                .start_child_workflow(
26215                    "python.child",
26216                    ChildWorkflowOptions::new("python-child-workers"),
26217                    json!([]),
26218                )
26219                .await
26220            {
26221                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
26222                    "reason": failure.reason,
26223                    "failure_id": failure.failure_id,
26224                    "exception_class": failure.exception_class,
26225                    "child_run_id": failure.child_workflow_run_id,
26226                })),
26227                Err(error) => Err(error),
26228                Ok(_) => Err(Error::WorkerLoop(
26229                    "child unexpectedly succeeded".to_string(),
26230                )),
26231            }
26232        });
26233        let mut task = child_parent_task(
26234            "ChildRunFailed",
26235            json!({
26236                "sequence": 1,
26237                "child_workflow_instance_id": "wf-child",
26238                "child_workflow_run_id": "run-child",
26239                "child_workflow_type": "python.child",
26240                "failure_id": "failure-child",
26241                "failure_category": "child_workflow",
26242                "message": "payment rejected",
26243                "exception": {
26244                    "type": "PaymentRejected",
26245                    "class": "payments.PaymentRejected",
26246                    "message": "payment rejected"
26247                }
26248            }),
26249        );
26250        task.workflow_type = "rust.handled-parent".to_string();
26251        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
26252
26253        let commands = worker.execute_workflow_task(task).expect("handled failure");
26254        assert_eq!(commands[0]["type"], "complete_workflow");
26255        let output =
26256            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26257        assert_eq!(output["reason"], "child_workflow");
26258        assert_eq!(output["failure_id"], "failure-child");
26259        assert_eq!(output["exception_class"], "payments.PaymentRejected");
26260        assert_eq!(output["child_run_id"], "run-child");
26261    }
26262
26263    #[test]
26264    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
26265        let client = Client::new("http://127.0.0.1:8080").expect("client");
26266        let mut worker = Worker::new(client, "rust-workers");
26267
26268        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
26269            let signal = ctx.wait_signal("start").await?;
26270            let name = signal
26271                .first()
26272                .and_then(|value| value.as_str())
26273                .unwrap_or("world");
26274            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
26275            Ok(json!({
26276                "greeting": greeting,
26277                "language": "rust"
26278            }))
26279        });
26280
26281        let signal_arguments =
26282            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
26283        let task = WorkflowTask {
26284            task_id: "wft-rust-signal-1".to_string(),
26285            observability_context: None,
26286            dispatch_observability_context: None,
26287            observability_links: None,
26288            workflow_command_id: None,
26289            workflow_id: Some("wf-rust-hello".to_string()),
26290            run_id: Some("run-rust-hello".to_string()),
26291            workflow_type: "rust.hello_workflow".to_string(),
26292            cancel_requested: false,
26293            payload_codec: DEFAULT_CODEC.to_string(),
26294            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26295            history_events: vec![HistoryEvent {
26296                event_type: "SignalReceived".to_string(),
26297                payload: json!({
26298                    "signal_id": "sig-rust-1",
26299                    "signal_name": "start"
26300                }),
26301                raw: HashMap::new(),
26302            }],
26303            total_history_events: Some(1),
26304            history_size_bytes: None,
26305            continue_as_new_recommended: None,
26306            history_budget_pressure: None,
26307            next_history_page_token: None,
26308            workflow_task_attempt: 1,
26309            workflow_signal_id: Some("sig-rust-1".to_string()),
26310            signal_name: Some("start".to_string()),
26311            signal_arguments: Some(signal_arguments),
26312            workflow_update_id: None,
26313            update_name: None,
26314            lease_owner: Some("rust-worker".to_string()),
26315        };
26316
26317        let commands = worker.execute_workflow_task(task).expect("workflow task");
26318
26319        assert_eq!(commands.len(), 1);
26320        assert_eq!(commands[0]["type"], "schedule_activity");
26321        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
26322        assert_eq!(
26323            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
26324            json!(["Rust"])
26325        );
26326    }
26327
26328    #[test]
26329    fn workflow_task_appends_paginated_history_events() {
26330        let mut task = WorkflowTask {
26331            task_id: "wft-rust-pages-1".to_string(),
26332            observability_context: None,
26333            dispatch_observability_context: None,
26334            observability_links: None,
26335            workflow_command_id: None,
26336            workflow_id: Some("wf-rust-pages".to_string()),
26337            run_id: Some("run-rust-pages".to_string()),
26338            workflow_type: "rust.hello_workflow".to_string(),
26339            cancel_requested: false,
26340            payload_codec: DEFAULT_CODEC.to_string(),
26341            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26342            history_events: vec![HistoryEvent {
26343                event_type: "WorkflowStarted".to_string(),
26344                payload: json!({}),
26345                raw: HashMap::new(),
26346            }],
26347            total_history_events: Some(3),
26348            history_size_bytes: None,
26349            continue_as_new_recommended: None,
26350            history_budget_pressure: None,
26351            next_history_page_token: Some("MQ==".to_string()),
26352            workflow_task_attempt: 1,
26353            workflow_signal_id: None,
26354            signal_name: None,
26355            signal_arguments: None,
26356            workflow_update_id: None,
26357            update_name: None,
26358            lease_owner: Some("rust-worker".to_string()),
26359        };
26360
26361        task.append_history_page(WorkflowTaskHistoryPage {
26362            history_events: vec![
26363                HistoryEvent {
26364                    event_type: "SignalReceived".to_string(),
26365                    payload: json!({
26366                        "signal_id": "sig-rust-1",
26367                        "signal_name": "start",
26368                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
26369                            .expect("signal arguments")
26370                    }),
26371                    raw: HashMap::new(),
26372                },
26373                HistoryEvent {
26374                    event_type: "MarkerRecorded".to_string(),
26375                    payload: json!({"sequence": 3}),
26376                    raw: HashMap::new(),
26377                },
26378            ],
26379            total_history_events: Some(3),
26380            next_history_page_token: None,
26381        });
26382
26383        assert_eq!(task.history_events.len(), 3);
26384        assert_eq!(task.total_history_events, Some(3));
26385        assert_eq!(task.next_history_page_token, None);
26386
26387        let signal = task
26388            .history_events
26389            .iter()
26390            .find(|event| event.event_type == "SignalReceived")
26391            .expect("signal event");
26392        assert_eq!(
26393            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
26394            vec![AvroValue::String("Rust".to_string())]
26395        );
26396    }
26397
26398    #[tokio::test]
26399    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
26400        let client = Client::new("http://127.0.0.1:8080").expect("client");
26401        let mut worker = Worker::new(client, "rust-workers");
26402        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26403        worker.register_query("counter", "current", |ctx, _args| async move {
26404            let mut count = 0_i64;
26405            for signal in ctx.signal_events() {
26406                let value = signal
26407                    .arguments
26408                    .first()
26409                    .and_then(Value::as_i64)
26410                    .unwrap_or_default();
26411                match signal.name.as_str() {
26412                    "increment" => count += value,
26413                    "set" => count = value,
26414                    _ => {}
26415                }
26416            }
26417            Ok(json!(count))
26418        });
26419
26420        let task = QueryTask {
26421            query_task_id: "query-rust-counter".to_string(),
26422            observability_context: None,
26423            dispatch_observability_context: None,
26424            observability_links: None,
26425            query_task_attempt: 1,
26426            lease_owner: Some("rust-worker".to_string()),
26427            workflow_id: Some("counter-1".to_string()),
26428            run_id: Some("run-counter-1".to_string()),
26429            workflow_type: "counter".to_string(),
26430            query_name: "current".to_string(),
26431            payload_codec: DEFAULT_CODEC.to_string(),
26432            workflow_arguments: Some(
26433                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26434            ),
26435            query_arguments: Some(
26436                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
26437            ),
26438            history_events: vec![
26439                HistoryEvent {
26440                    event_type: "SignalReceived".to_string(),
26441                    payload: json!({
26442                        "signal_id": "php-signal-1",
26443                        "signal_name": "increment",
26444                        "workflow_sequence": 1,
26445                        "payload_codec": DEFAULT_CODEC,
26446                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
26447                    }),
26448                    raw: HashMap::new(),
26449                },
26450                HistoryEvent {
26451                    event_type: "SignalReceived".to_string(),
26452                    payload: json!({
26453                        "signal_id": "python-signal-2",
26454                        "signal_name": "increment",
26455                        "workflow_sequence": 2,
26456                        "payload_codec": DEFAULT_CODEC,
26457                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
26458                    }),
26459                    raw: HashMap::new(),
26460                },
26461                HistoryEvent {
26462                    event_type: "SignalReceived".to_string(),
26463                    payload: json!({
26464                        "signal_id": "rust-signal-3",
26465                        "signal_name": "set",
26466                        "workflow_sequence": 3,
26467                        "payload_codec": DEFAULT_CODEC,
26468                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
26469                    }),
26470                    raw: HashMap::new(),
26471                },
26472            ],
26473            history_export: None,
26474            run_status: Some("completed".to_string()),
26475        };
26476
26477        let result = worker.execute_query_task(task).await.expect("query result");
26478        assert_eq!(result.into_json().expect("query projection"), json!(0));
26479    }
26480
26481    #[tokio::test]
26482    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
26483        let worker = replay_counter_worker();
26484        let running_history = json!([
26485            {
26486                "type": "ActivityCompleted",
26487                "payload": {
26488                    "sequence": 1,
26489                    "activity_type": "load-counter",
26490                    "payload_codec": DEFAULT_CODEC,
26491                    "result": fixture_envelope(json!("loaded"))
26492                }
26493            },
26494            {
26495                "type": "SignalWaitOpened",
26496                "payload": {
26497                    "sequence": 3,
26498                    "signal_name": "increment"
26499                }
26500            },
26501            {
26502                "type": "SignalReceived",
26503                "payload": {
26504                    "signal_id": "signal-3",
26505                    "signal_name": "increment",
26506                    "workflow_sequence": 2,
26507                    "payload_codec": DEFAULT_CODEC,
26508                    "arguments": fixture_envelope(json!([3]))
26509                }
26510            },
26511            {
26512                "type": "SignalApplied",
26513                "payload": {
26514                    "sequence": 3,
26515                    "signal_id": "signal-3",
26516                    "signal_name": "increment",
26517                    "payload_codec": DEFAULT_CODEC,
26518                    "value": fixture_envelope(json!([3]))
26519                }
26520            }
26521        ]);
26522
26523        let running = worker
26524            .execute_query_task(replay_counter_query(
26525                "current",
26526                running_history.clone(),
26527                "running",
26528            ))
26529            .await
26530            .expect("running replay query");
26531        assert_eq!(
26532            running.clone().into_json().expect("query projection"),
26533            json!({"loaded": "loaded", "count": 3, "finished": false})
26534        );
26535
26536        let detached = worker
26537            .execute_query_task(replay_counter_query(
26538                "detached-mutation",
26539                running_history.clone(),
26540                "running",
26541            ))
26542            .await
26543            .expect("query mutates only its detached state clone");
26544        assert_eq!(detached.into_json().expect("query projection"), json!(999));
26545        let failed = worker
26546            .execute_query_task(replay_counter_query(
26547                "failed-mutation",
26548                running_history.clone(),
26549                "running",
26550            ))
26551            .await
26552            .expect_err("failed query");
26553        assert_eq!(failed.reason, "query_rejected");
26554        let unchanged = worker
26555            .execute_query_task(replay_counter_query("current", running_history, "running"))
26556            .await
26557            .expect("later query reconstructs unchanged state");
26558        assert_eq!(unchanged, running);
26559
26560        let restarted_worker = replay_counter_worker();
26561        let empty_arguments = fixture_envelope(json!([]));
26562        let loaded_result = fixture_envelope(json!("loaded"));
26563        let signal_three = fixture_blob(json!([3]));
26564        let signal_five = fixture_blob(json!([5]));
26565        let restarted_task: QueryTask = serde_json::from_value(json!({
26566            "query_task_id": "query-after-restart",
26567            "workflow_id": "counter-1",
26568            "run_id": "run-counter-1",
26569            "workflow_type": "replay-counter",
26570            "query_name": "current",
26571            "payload_codec": DEFAULT_CODEC,
26572            "workflow_arguments": empty_arguments.clone(),
26573            "query_arguments": empty_arguments,
26574            "history_events": [],
26575            "history_export": {
26576                "payloads": {"codec": DEFAULT_CODEC},
26577                "history_events": [
26578                    {
26579                        "type": "ActivityCompleted",
26580                        "payload": {
26581                            "sequence": 1,
26582                            "activity_type": "load-counter",
26583                            "payload_codec": DEFAULT_CODEC,
26584                            "result": null
26585                        }
26586                    },
26587                    {
26588                        "type": "SignalWaitOpened",
26589                        "payload": {
26590                            "sequence": 3,
26591                            "signal_name": "increment"
26592                        }
26593                    },
26594                    {
26595                        "type": "SignalReceived",
26596                        "payload": {
26597                            "signal_id": "signal-3",
26598                            "signal_name": "increment",
26599                            "workflow_sequence": 2
26600                        }
26601                    },
26602                    {
26603                        "type": "SignalApplied",
26604                        "payload": {
26605                            "sequence": 3,
26606                            "signal_id": "signal-3",
26607                            "signal_name": "increment"
26608                        }
26609                    },
26610                    {
26611                        "type": "SignalWaitOpened",
26612                        "payload": {
26613                            "sequence": 5,
26614                            "signal_name": "increment"
26615                        }
26616                    },
26617                    {
26618                        "type": "SignalReceived",
26619                        "payload": {
26620                            "signal_id": "signal-5",
26621                            "signal_name": "increment",
26622                            "workflow_sequence": 4
26623                        }
26624                    },
26625                    {
26626                        "type": "SignalApplied",
26627                        "payload": {
26628                            "sequence": 5,
26629                            "signal_id": "signal-5",
26630                            "signal_name": "increment"
26631                        }
26632                    }
26633                ],
26634                "activities": [{
26635                    "sequence": 1,
26636                    "activity_type": "load-counter",
26637                    "payload_codec": DEFAULT_CODEC,
26638                    "result": loaded_result
26639                }],
26640                "signals": [
26641                    {
26642                        "id": "signal-3",
26643                        "name": "increment",
26644                        "workflow_sequence": 2,
26645                        "payload_codec": DEFAULT_CODEC,
26646                        "arguments": signal_three
26647                    },
26648                    {
26649                        "id": "signal-5",
26650                        "name": "increment",
26651                        "workflow_sequence": 4,
26652                        "payload_codec": DEFAULT_CODEC,
26653                        "arguments": signal_five
26654                    }
26655                ]
26656            },
26657            "run_status": "completed"
26658        }))
26659        .expect("cold replay query task");
26660        let completed = restarted_worker
26661            .execute_query_task(restarted_task)
26662            .await
26663            .expect("completed cold replay query");
26664        assert_eq!(
26665            completed.into_json().expect("query projection"),
26666            json!({"loaded": "loaded", "count": 8, "finished": true})
26667        );
26668    }
26669
26670    #[tokio::test]
26671    async fn replayed_query_replay_failures_are_machine_readable() {
26672        let worker = replay_counter_worker();
26673        let task = replay_counter_query(
26674            "current",
26675            json!([{
26676                "type": "ActivityCompleted",
26677                "payload": {
26678                    "sequence": 1,
26679                    "payload_codec": DEFAULT_CODEC,
26680                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
26681                }
26682            }]),
26683            "running",
26684        );
26685        let failure = worker
26686            .execute_query_task(task)
26687            .await
26688            .expect_err("invalid replay history payload");
26689        assert_eq!(failure.reason, "query_payload_decode_failed");
26690        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
26691        assert!(failure.message.contains("invalid_payload_framing"));
26692    }
26693
26694    #[tokio::test]
26695    async fn query_task_restores_compact_history_from_export() {
26696        let client = Client::new("http://127.0.0.1:8080").expect("client");
26697        let mut worker = Worker::new(client, "rust-workers");
26698        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26699        worker.register_query("counter", "current", |ctx, _args| async move {
26700            Ok(json!(ctx.signals("increment")[0][0]))
26701        });
26702        let empty_arguments = fixture_envelope(json!([]));
26703        let exported_signal = fixture_blob(json!([9]));
26704        let task: QueryTask = serde_json::from_value(json!({
26705            "query_task_id": "query-export",
26706            "workflow_type": "counter",
26707            "query_name": "current",
26708            "payload_codec": DEFAULT_CODEC,
26709            "workflow_arguments": empty_arguments.clone(),
26710            "query_arguments": empty_arguments,
26711            "history_events": [],
26712            "history_export": {
26713                "payloads": {"codec": DEFAULT_CODEC},
26714                "history_events": [{
26715                    "type": "SignalReceived",
26716                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
26717                }],
26718                "signals": [{
26719                    "id": "signal-export",
26720                    "name": "increment",
26721                    "status": "applied",
26722                    "workflow_sequence": 1,
26723                    "payload_codec": DEFAULT_CODEC,
26724                    "arguments": exported_signal
26725                }]
26726            }
26727        }))
26728        .expect("query task");
26729
26730        let result = worker.execute_query_task(task).await.expect("query result");
26731        assert_eq!(result.into_json().expect("query projection"), json!(9));
26732    }
26733
26734    #[tokio::test]
26735    async fn query_task_failures_have_stable_reasons() {
26736        let client = Client::new("http://127.0.0.1:8080").expect("client");
26737        let mut worker = Worker::new(client, "rust-workers");
26738        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26739        worker.register_query(
26740            "counter",
26741            "current",
26742            |_ctx, _args| async move { Ok(json!(0)) },
26743        );
26744
26745        let base_task = QueryTask {
26746            query_task_id: "query-errors".to_string(),
26747            observability_context: None,
26748            dispatch_observability_context: None,
26749            observability_links: None,
26750            query_task_attempt: 1,
26751            lease_owner: None,
26752            workflow_id: Some("counter-errors".to_string()),
26753            run_id: Some("run-errors".to_string()),
26754            workflow_type: "counter".to_string(),
26755            query_name: "missing".to_string(),
26756            payload_codec: DEFAULT_CODEC.to_string(),
26757            workflow_arguments: Some(fixture_envelope(json!([]))),
26758            query_arguments: Some(fixture_envelope(json!([]))),
26759            history_events: Vec::new(),
26760            history_export: None,
26761            run_status: Some("running".to_string()),
26762        };
26763
26764        let unknown = worker
26765            .execute_query_task(base_task.clone())
26766            .await
26767            .expect_err("unknown query");
26768        assert_eq!(unknown.reason, "rejected_unknown_query");
26769
26770        let mut malformed = base_task;
26771        malformed.query_name = "current".to_string();
26772        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
26773        let malformed = worker
26774            .execute_query_task(malformed)
26775            .await
26776            .expect_err("malformed payload");
26777        assert_eq!(malformed.reason, "query_payload_decode_failed");
26778
26779        let client = Client::new("http://127.0.0.1:8080").expect("client");
26780        let mut unavailable_worker = Worker::new(client, "rust-workers");
26781        unavailable_worker
26782            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26783        let empty_arguments = fixture_envelope(json!([]));
26784        let unavailable_task: QueryTask = serde_json::from_value(json!({
26785            "query_task_id": "query-unavailable",
26786            "workflow_type": "counter",
26787            "query_name": "current",
26788            "payload_codec": DEFAULT_CODEC,
26789            "workflow_arguments": empty_arguments.clone(),
26790            "query_arguments": empty_arguments
26791        }))
26792        .expect("query task");
26793        let unavailable = unavailable_worker
26794            .execute_query_task(unavailable_task)
26795            .await
26796            .expect_err("query handler unavailable");
26797        assert_eq!(unavailable.reason, "query_handler_unavailable");
26798    }
26799
26800    #[tokio::test]
26801    async fn client_query_decodes_result_and_typed_failure() {
26802        let server = MockWorkerServer::start();
26803        let client = Client::builder(server.base_url())
26804            .timeout(Duration::from_secs(2))
26805            .build()
26806            .expect("client");
26807
26808        let result = client
26809            .query_workflow("counter-1", "current", json!([]))
26810            .await
26811            .expect("query result");
26812        assert_eq!(result, json!({"count": 8}));
26813
26814        let error = client
26815            .query_workflow("counter-1", "missing", json!([]))
26816            .await
26817            .expect_err("unknown query");
26818        let Error::QueryFailed(failure) = error else {
26819            panic!("expected typed query failure");
26820        };
26821        assert_eq!(failure.status, 404);
26822        assert_eq!(failure.reason, "rejected_unknown_query");
26823    }
26824
26825    #[tokio::test]
26826    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
26827        let server = MockWorkerServer::start();
26828        let client = Client::builder(server.base_url())
26829            .timeout(Duration::from_secs(2))
26830            .build()
26831            .expect("client");
26832        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
26833
26834        client
26835            .start_workflow(
26836                "typed.echo",
26837                "rust-workers",
26838                "typed-start",
26839                arguments.clone(),
26840            )
26841            .await
26842            .expect("typed workflow start");
26843        assert_eq!(
26844            decode_wire_avro_value(
26845                &server.request_body("/api/workflows")["input"],
26846                DEFAULT_CODEC,
26847            )
26848            .expect("typed start input"),
26849            arguments
26850        );
26851
26852        client
26853            .signal_workflow("typed-1", "changed", arguments.clone())
26854            .await
26855            .expect("typed signal");
26856        assert_eq!(
26857            decode_wire_avro_value(
26858                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
26859                DEFAULT_CODEC,
26860            )
26861            .expect("typed signal input"),
26862            arguments
26863        );
26864
26865        assert_eq!(
26866            client
26867                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
26868                .await
26869                .expect("typed query"),
26870            typed_fidelity_probe()
26871        );
26872        assert_eq!(
26873            decode_wire_avro_value(
26874                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
26875                DEFAULT_CODEC,
26876            )
26877            .expect("typed query input"),
26878            arguments
26879        );
26880
26881        assert_eq!(
26882            client
26883                .update_workflow_avro_value(
26884                    "typed-1",
26885                    "replace",
26886                    arguments.clone(),
26887                    Some("typed-request"),
26888                )
26889                .await
26890                .expect("typed update"),
26891            typed_fidelity_probe()
26892        );
26893        let update = server.request_body("/api/workflows/typed-1/update/replace");
26894        assert_eq!(update["request_id"], "typed-request");
26895        assert_eq!(
26896            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
26897            arguments
26898        );
26899
26900        let handle = WorkflowHandle {
26901            client: client.clone(),
26902            workflow_id: "typed-1".to_string(),
26903            run_id: Some("run-typed-1".to_string()),
26904            workflow_type: "typed.echo".to_string(),
26905        };
26906        assert_eq!(
26907            handle
26908                .result_avro_value(WorkflowResultOptions::default())
26909                .await
26910                .expect("typed workflow result"),
26911            typed_fidelity_probe()
26912        );
26913
26914        client
26915            .complete_activity_task(
26916                "activity-typed",
26917                "attempt-typed",
26918                "rust-worker",
26919                typed_fidelity_probe(),
26920                DEFAULT_CODEC,
26921            )
26922            .await
26923            .expect("typed activity completion");
26924        assert_eq!(
26925            decode_wire_avro_value(
26926                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
26927                    ["result"],
26928                DEFAULT_CODEC,
26929            )
26930            .expect("typed activity result"),
26931            typed_fidelity_probe()
26932        );
26933        client
26934            .fail_activity_task(
26935                "activity-typed",
26936                "attempt-typed",
26937                "rust-worker",
26938                "typed failure",
26939                true,
26940            )
26941            .await
26942            .expect("activity failure");
26943    }
26944
26945    #[tokio::test]
26946    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
26947        let server = MockWorkerServer::start();
26948        let client = Client::builder(server.base_url())
26949            .timeout(Duration::from_secs(2))
26950            .build()
26951            .expect("client");
26952
26953        let options = WorkflowCommandOptions::new()
26954            .reason("cleanup requested")
26955            .request_id("cancel-17");
26956        let cancelled = client
26957            .cancel_workflow("wf-lifecycle", options)
26958            .await
26959            .expect("instance cancellation");
26960        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
26961        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
26962        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
26963        assert_eq!(
26964            server.request_body("/api/workflows/wf-lifecycle/cancel"),
26965            json!({"reason":"cleanup requested","request_id":"cancel-17"})
26966        );
26967
26968        let terminated = client
26969            .terminate_workflow(
26970                "wf-lifecycle",
26971                WorkflowCommandOptions::new().reason("forced stop"),
26972            )
26973            .await
26974            .expect("instance termination");
26975        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
26976        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
26977
26978        client
26979            .cancel_workflow_run(
26980                "wf-lifecycle",
26981                "run-current",
26982                WorkflowCommandOptions::default(),
26983            )
26984            .await
26985            .expect("selected run cancellation");
26986        client
26987            .terminate_workflow_run(
26988                "wf-lifecycle",
26989                "run-current",
26990                WorkflowCommandOptions::default(),
26991            )
26992            .await
26993            .expect("selected run termination");
26994
26995        for (command, error) in [
26996            (
26997                WorkflowCommandKind::Cancel,
26998                client
26999                    .cancel_workflow_run(
27000                        "wf-lifecycle",
27001                        "run-stale",
27002                        WorkflowCommandOptions::default(),
27003                    )
27004                    .await
27005                    .expect_err("stale cancellation must be rejected"),
27006            ),
27007            (
27008                WorkflowCommandKind::Terminate,
27009                client
27010                    .terminate_workflow_run(
27011                        "wf-lifecycle",
27012                        "run-stale",
27013                        WorkflowCommandOptions::default(),
27014                    )
27015                    .await
27016                    .expect_err("stale termination must be rejected"),
27017            ),
27018        ] {
27019            let Error::WorkflowCommandRejected(rejection) = error else {
27020                panic!("expected typed command rejection");
27021            };
27022            assert_eq!(rejection.command, command);
27023            assert_eq!(rejection.status, 409);
27024            assert_eq!(rejection.reason, "historical_run_command_rejected");
27025            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
27026            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
27027        }
27028    }
27029
27030    #[tokio::test]
27031    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
27032        let server = MockWorkerServer::start();
27033        let client = Client::builder(server.base_url())
27034            .timeout(Duration::from_secs(2))
27035            .build()
27036            .expect("client");
27037
27038        let result = client
27039            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
27040            .await
27041            .expect("redrive accepted");
27042        assert_eq!(result.workflow_id, "wf-lifecycle");
27043        assert_eq!(result.source_run_id, "run-failed");
27044        assert_eq!(result.run_id, "run-successor");
27045        assert_eq!(result.resume_step_sequence, 2);
27046        assert_eq!(
27047            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
27048            json!({"request_id":"retry-1"})
27049        );
27050
27051        let repeated = client
27052            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
27053            .await
27054            .expect("idempotent redrive response accepted");
27055        assert_eq!(repeated.run_id, "run-successor");
27056
27057        let error = client
27058            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
27059            .await
27060            .expect_err("completed run must be rejected");
27061        let Error::Http { status, body } = error else {
27062            panic!("expected HTTP redrive rejection");
27063        };
27064        assert_eq!(status.as_u16(), 409);
27065        assert!(body.contains("run_not_failed"));
27066        assert_eq!(
27067            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
27068            json!({})
27069        );
27070
27071        let handle = WorkflowHandle {
27072            client: client.clone(),
27073            workflow_id: "wf-lifecycle".to_string(),
27074            run_id: Some("run-failed".to_string()),
27075            workflow_type: "test".to_string(),
27076        };
27077        assert_eq!(
27078            handle.redrive(None).await.expect("handle redrive").run_id,
27079            "run-successor"
27080        );
27081        let missing_run = WorkflowHandle {
27082            run_id: None,
27083            ..handle
27084        };
27085        assert!(matches!(
27086            missing_run.redrive(None).await,
27087            Err(Error::Codec(_))
27088        ));
27089    }
27090
27091    #[tokio::test]
27092    async fn workflow_start_options_send_server_enforced_deadlines() {
27093        let server = MockWorkerServer::start();
27094        let client = Client::builder(server.base_url())
27095            .timeout(Duration::from_secs(2))
27096            .build()
27097            .expect("client");
27098
27099        let handle = client
27100            .start_workflow_with_options(
27101                "rust.timeout",
27102                "rust-timeouts",
27103                "wf-start-options",
27104                WorkflowStartOptions::new()
27105                    .execution_timeout_seconds(30)
27106                    .run_timeout_seconds(1),
27107                json!([]),
27108            )
27109            .await
27110            .expect("workflow start");
27111
27112        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
27113        let body = server.request_body("/api/workflows");
27114        assert_eq!(body["execution_timeout_seconds"], 30);
27115        assert_eq!(body["run_timeout_seconds"], 1);
27116
27117        let invalid = client
27118            .start_workflow_with_options(
27119                "rust.timeout",
27120                "rust-timeouts",
27121                "wf-invalid-options",
27122                WorkflowStartOptions::new()
27123                    .execution_timeout_seconds(1)
27124                    .run_timeout_seconds(2),
27125                json!([]),
27126            )
27127            .await
27128            .expect_err("invalid deadline ordering");
27129        assert!(invalid
27130            .to_string()
27131            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
27132    }
27133
27134    #[tokio::test]
27135    async fn workflow_result_returns_each_typed_terminal_outcome() {
27136        let server = MockWorkerServer::start();
27137        let client = Client::builder(server.base_url())
27138            .timeout(Duration::from_secs(2))
27139            .build()
27140            .expect("client");
27141        let options = WorkflowResultOptions {
27142            poll_interval: Duration::ZERO,
27143            timeout: Duration::from_secs(1),
27144        };
27145
27146        let failed = WorkflowHandle {
27147            client: client.clone(),
27148            workflow_id: "wf-failed".to_string(),
27149            run_id: Some("run-failed".to_string()),
27150            workflow_type: "failure".to_string(),
27151        }
27152        .result(options)
27153        .await
27154        .expect_err("failed outcome");
27155        let Error::WorkflowFailed(failure) = failed else {
27156            panic!("expected WorkflowFailed");
27157        };
27158        assert_eq!(failure.workflow_id, "wf-failed");
27159        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
27160        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
27161        assert_eq!(failure.failure_category.as_deref(), Some("application"));
27162        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
27163        assert_eq!(
27164            failure.exception_class.as_deref(),
27165            Some("billing::PaymentError")
27166        );
27167        assert_eq!(failure.non_retryable, Some(true));
27168
27169        for (workflow_id, expected_kind, expected_reason) in [
27170            (
27171                "wf-cancelled",
27172                WorkflowTerminalKind::Cancelled,
27173                "cleanup requested",
27174            ),
27175            (
27176                "wf-terminated",
27177                WorkflowTerminalKind::Terminated,
27178                "forced stop",
27179            ),
27180            (
27181                "wf-timed-out",
27182                WorkflowTerminalKind::TimedOut,
27183                "run_timeout",
27184            ),
27185        ] {
27186            let error = WorkflowHandle {
27187                client: client.clone(),
27188                workflow_id: workflow_id.to_string(),
27189                run_id: None,
27190                workflow_type: "terminal".to_string(),
27191            }
27192            .result(options)
27193            .await
27194            .expect_err("typed terminal outcome");
27195            let outcome = match error {
27196                Error::WorkflowCancelled(outcome) => outcome,
27197                Error::WorkflowTerminated(outcome) => outcome,
27198                Error::WorkflowTimedOut(outcome) => outcome,
27199                other => panic!("unexpected terminal error: {other}"),
27200            };
27201            assert_eq!(outcome.kind, expected_kind);
27202            assert_eq!(outcome.workflow_id, workflow_id);
27203            assert_eq!(outcome.reason, expected_reason);
27204        }
27205
27206        let wait_timeout = WorkflowHandle {
27207            client,
27208            workflow_id: "wf-waiting".to_string(),
27209            run_id: Some("run-waiting".to_string()),
27210            workflow_type: "waiting".to_string(),
27211        }
27212        .result(WorkflowResultOptions {
27213            poll_interval: Duration::ZERO,
27214            timeout: Duration::ZERO,
27215        })
27216        .await
27217        .expect_err("client wait timeout");
27218        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
27219            panic!("expected typed client timeout");
27220        };
27221        assert_eq!(timeout.reason, "result_wait_timeout");
27222        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
27223        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
27224    }
27225
27226    #[tokio::test]
27227    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
27228        let server = MockWorkerServer::start();
27229        let client = Client::builder(server.base_url())
27230            .timeout(Duration::from_secs(2))
27231            .build()
27232            .expect("client");
27233
27234        let handle = WorkflowHandle {
27235            client,
27236            workflow_id: "wf-selected".to_string(),
27237            run_id: Some("run-selected".to_string()),
27238            workflow_type: "selected".to_string(),
27239        };
27240        let options = WorkflowResultOptions {
27241            poll_interval: Duration::ZERO,
27242            timeout: Duration::from_secs(1),
27243        };
27244
27245        let current = handle
27246            .result(options)
27247            .await
27248            .expect("instance result follows the current run");
27249        assert_eq!(current, json!("current run output"));
27250
27251        let error = handle
27252            .result_selected_run(options)
27253            .await
27254            .expect_err("the selected run is cancelled even though the current run completed");
27255
27256        let Error::WorkflowCancelled(outcome) = error else {
27257            panic!("expected selected run cancellation");
27258        };
27259        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
27260        assert_eq!(outcome.reason, "selected run cancelled");
27261        assert_eq!(
27262            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
27263            1
27264        );
27265        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
27266    }
27267
27268    #[tokio::test]
27269    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
27270        let server = MockWorkerServer::draining_polls();
27271        let client = Client::builder(server.base_url())
27272            .timeout(Duration::from_secs(2))
27273            .build()
27274            .expect("client");
27275
27276        let workflow = client
27277            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
27278            .await
27279            .expect("workflow drain response");
27280        let activity = client
27281            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
27282            .await
27283            .expect("activity drain response");
27284        let query = client
27285            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
27286            .await
27287            .expect("query drain response");
27288
27289        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
27290            assert_eq!(
27291                outcome,
27292                WorkerPollOutcome::Stop {
27293                    poll_status: Some("draining".to_string()),
27294                    reason: Some("worker_draining".to_string()),
27295                }
27296            );
27297        }
27298
27299        assert!(client
27300            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
27301            .await
27302            .expect("compatibility poll")
27303            .is_none());
27304    }
27305
27306    #[tokio::test]
27307    async fn managed_worker_honors_drain_stop_for_every_task_family() {
27308        let server = MockWorkerServer::draining_polls();
27309        let client = Client::builder(server.base_url())
27310            .timeout(Duration::from_secs(2))
27311            .build()
27312            .expect("client");
27313
27314        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
27315            .worker_id("draining-workflow-worker")
27316            .poll_timeout(Duration::ZERO);
27317        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
27318        workflow_worker
27319            .run()
27320            .await
27321            .expect("workflow drain is a clean stop");
27322
27323        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
27324            .worker_id("draining-activity-worker")
27325            .poll_timeout(Duration::ZERO);
27326        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
27327        activity_worker
27328            .run()
27329            .await
27330            .expect("activity drain is a clean stop");
27331
27332        let mut query_worker = Worker::new(client, "rust-workers")
27333            .worker_id("draining-query-worker")
27334            .poll_timeout(Duration::ZERO);
27335        query_worker.register_query("counter", "current", |_ctx, _args| async {
27336            Ok(Value::Null)
27337        });
27338        query_worker
27339            .run()
27340            .await
27341            .expect("query drain is a clean stop");
27342    }
27343
27344    #[tokio::test]
27345    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
27346        let server = MockWorkerServer::start();
27347        let client = Client::builder(server.base_url())
27348            .timeout(Duration::from_secs(2))
27349            .build()
27350            .expect("client");
27351
27352        let details: Value = serde_json::from_str(include_str!(
27353            "../tests/fixtures/activity-heartbeat-progress.json"
27354        ))
27355        .expect("heartbeat progress fixture");
27356        // Every individual field fits Server's progress contract, while the
27357        // obsolete encoded envelope exceeded its 191-character string limit.
27358        assert!(
27359            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
27360                .unwrap()["blob"]
27361                .as_str()
27362                .unwrap()
27363                .len()
27364                > 191
27365        );
27366        let heartbeat = client
27367            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
27368            .await
27369            .expect("cancellation heartbeat");
27370        assert!(heartbeat.cancel_requested);
27371        assert!(heartbeat.should_stop());
27372        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
27373        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
27374        let heartbeat_body =
27375            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
27376        assert_eq!(heartbeat_body["details"], details);
27377        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
27378        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
27379
27380        let error = client
27381            .complete_activity_task(
27382                "activity-cancel",
27383                "attempt-cancel",
27384                "rust-worker",
27385                json!({"late":true}),
27386                DEFAULT_CODEC,
27387            )
27388            .await
27389            .expect_err("late completion must be refused");
27390        assert!(activity_task_rejection_is_final(&error));
27391        let Error::ActivityTaskRejected(rejection) = error else {
27392            panic!("expected typed activity rejection");
27393        };
27394        assert_eq!(rejection.status, 409);
27395        assert_eq!(rejection.reason, "run_cancelled");
27396        assert!(rejection.cancel_requested);
27397        assert_eq!(rejection.can_continue, Some(false));
27398    }
27399
27400    #[tokio::test]
27401    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
27402        let server = MockWorkerServer::cancelled_activity();
27403        let client = Client::builder(server.base_url())
27404            .timeout(Duration::from_secs(2))
27405            .build()
27406            .expect("client");
27407        let cancellation_observed = Arc::new(AtomicBool::new(false));
27408        let observed = Arc::clone(&cancellation_observed);
27409        let mut worker = Worker::new(client.clone(), "rust-workers")
27410            .worker_id("rust-cancel-worker")
27411            .poll_timeout(Duration::from_millis(10));
27412        worker.register_activity("cancel-aware", move |ctx, _args| {
27413            let observed = Arc::clone(&observed);
27414            async move {
27415                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
27416                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
27417                Ok(json!({"late":"completion"}))
27418            }
27419        });
27420
27421        assert_eq!(
27422            worker.run_once().await.expect("cancelled attempt handled"),
27423            1
27424        );
27425        assert!(cancellation_observed.load(Ordering::SeqCst));
27426        assert_eq!(
27427            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
27428            1
27429        );
27430
27431        let mut restarted = Worker::new(client, "rust-workers")
27432            .worker_id("rust-cancel-worker-restarted")
27433            .poll_timeout(Duration::from_millis(10));
27434        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
27435        assert_eq!(
27436            restarted
27437                .run_once()
27438                .await
27439                .expect("replacement worker continues polling"),
27440            0
27441        );
27442    }
27443
27444    #[tokio::test]
27445    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
27446        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"}"#;
27447        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
27448        let client = Client::builder(server.base_url())
27449            .timeout(Duration::from_secs(2))
27450            .build()
27451            .expect("client");
27452
27453        let direct_error = client
27454            .complete_workflow_task(
27455                "workflow-timeout-task",
27456                "timeout-worker",
27457                3,
27458                vec![json!({
27459                    "type": "complete_workflow",
27460                    "result": fixture_envelope(Value::Null)
27461                })],
27462            )
27463            .await
27464            .expect_err("the low-level client preserves the completion rejection");
27465        let Error::Http { status, body } = direct_error else {
27466            panic!("expected the original HTTP completion rejection");
27467        };
27468        assert_eq!(status, reqwest::StatusCode::CONFLICT);
27469        assert_eq!(
27470            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
27471            "run_timed_out"
27472        );
27473
27474        let mut worker = Worker::new(client, "rust-workers")
27475            .worker_id("timeout-worker")
27476            .poll_timeout(Duration::from_millis(10));
27477        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
27478            Ok(json!({"late": "result"}))
27479        });
27480
27481        assert_eq!(
27482            worker
27483                .run_once()
27484                .await
27485                .expect("authoritative selected-run timeout settles the tick"),
27486            1
27487        );
27488        assert_eq!(
27489            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
27490            2,
27491            "both the direct client proof and managed worker must see the rejection"
27492        );
27493    }
27494
27495    #[tokio::test]
27496    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
27497        for (name, status, response) in [
27498            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
27499            (
27500                "command was recorded",
27501                "409 Conflict",
27502                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27503            ),
27504            (
27505                "lease conflict",
27506                "409 Conflict",
27507                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
27508            ),
27509            (
27510                "nonterminal run",
27511                "409 Conflict",
27512                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
27513            ),
27514            (
27515                "different selected run",
27516                "409 Conflict",
27517                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"}"#,
27518            ),
27519            (
27520                "different task attempt",
27521                "409 Conflict",
27522                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27523            ),
27524            (
27525                "authentication failure",
27526                "401 Unauthorized",
27527                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27528            ),
27529            (
27530                "authorization failure",
27531                "403 Forbidden",
27532                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27533            ),
27534            (
27535                "protocol failure",
27536                "400 Bad Request",
27537                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
27538            ),
27539            (
27540                "malformed command",
27541                "422 Unprocessable Entity",
27542                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27543            ),
27544            (
27545                "transient server failure",
27546                "503 Service Unavailable",
27547                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
27548            ),
27549        ] {
27550            let server = MockWorkerServer::workflow_completion(status, response);
27551            let client = Client::builder(server.base_url())
27552                .timeout(Duration::from_secs(2))
27553                .build()
27554                .expect("client");
27555            let mut worker = Worker::new(client, "rust-workers")
27556                .worker_id("timeout-worker")
27557                .poll_timeout(Duration::from_millis(10));
27558            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
27559                Ok(json!({"late": "result"}))
27560            });
27561
27562            let error = worker
27563                .run_once()
27564                .await
27565                .expect_err(&format!("{name} must remain an error"));
27566            assert!(
27567                matches!(error, Error::Http { .. } | Error::Protocol(_)),
27568                "{name} returned an unexpected error variant: {error}"
27569            );
27570        }
27571    }
27572
27573    #[tokio::test]
27574    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
27575        let server = MockWorkerServer::start();
27576        let client = Client::builder(server.base_url())
27577            .worker_token(Some("worker-secret".to_string()))
27578            .namespace("orders")
27579            .timeout(Duration::from_secs(2))
27580            .build()
27581            .expect("client");
27582        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
27583
27584        let result = client
27585            .deregister_worker_registration("worker/α space")
27586            .await
27587            .expect("deregister worker registration");
27588
27589        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
27590        assert_eq!(
27591            server.worker_protocol_for(path).as_deref(),
27592            Some(WORKER_PROTOCOL_VERSION)
27593        );
27594        assert_eq!(server.control_protocol_for(path), None);
27595        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
27596        assert_eq!(
27597            server.authorization_for(path).as_deref(),
27598            Some("Bearer worker-secret")
27599        );
27600        assert_eq!(
27601            result,
27602            WorkerDeregistrationEnvelope {
27603                worker_id: "deregistered-worker".to_string(),
27604                outcome: "deregistered".to_string(),
27605                recovered_workflow_task_count: 2,
27606            }
27607        );
27608    }
27609
27610    #[tokio::test]
27611    async fn low_level_registration_rejects_update_validators_before_transport() {
27612        let server = MockWorkerServer::start();
27613        let client = Client::builder(server.base_url())
27614            .timeout(Duration::from_secs(2))
27615            .build()
27616            .expect("client");
27617
27618        for update_validators in [json!(["approve"]), json!("approve")] {
27619            let error = client
27620                .register_worker_with_command_contracts(
27621                    "validator-claiming-worker",
27622                    "rust-workers",
27623                    vec!["orders".to_string()],
27624                    vec![],
27625                    1,
27626                    1,
27627                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
27628                    json!({
27629                        "orders": {
27630                            "queries": ["current"],
27631                            "updates": ["approve"],
27632                            "update_validators": update_validators,
27633                        },
27634                    }),
27635                )
27636                .await
27637                .expect_err("unsupported validator claims must fail before registration");
27638
27639            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
27640                panic!("expected typed unsupported-validator failure");
27641            };
27642            assert_eq!(workflow_type, "orders");
27643        }
27644        assert_eq!(server.request_count("/api/worker/register"), 0);
27645    }
27646
27647    #[tokio::test]
27648    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
27649        let server = MockWorkerServer::start();
27650        let client = Client::builder(server.base_url())
27651            .timeout(Duration::from_secs(2))
27652            .build()
27653            .expect("client");
27654        let mut worker = Worker::new(client, "rust-workers");
27655        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
27656        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
27657        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
27658        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
27659        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
27660        worker
27661            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
27662            .expect("declare workflow signals");
27663
27664        worker.register().await.expect("register handler contracts");
27665
27666        let declaration =
27667            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
27668        let expected_contracts = json!([
27669            {
27670                "name": "a-avro",
27671                "parameters": [{
27672                    "name": "args", "position": 0, "required": false,
27673                    "variadic": true, "type": null, "allows_null": true,
27674                    "default_available": false, "default": null,
27675                }],
27676            },
27677            {
27678                "name": "z-json",
27679                "parameters": [{
27680                    "name": "args", "position": 0, "required": false,
27681                    "variadic": true, "type": null, "allows_null": true,
27682                    "default_available": false, "default": null,
27683                }],
27684            },
27685        ]);
27686        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
27687        assert_eq!(declaration["query_contracts"], expected_contracts);
27688        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
27689        assert_eq!(declaration["update_contracts"], expected_contracts);
27690        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
27691        assert_eq!(declaration["signal_contracts"], expected_contracts);
27692        assert_eq!(declaration["update_validators"], json!([]));
27693    }
27694
27695    #[tokio::test]
27696    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
27697        let server = MockWorkerServer::start();
27698        let client = Client::new(server.base_url()).expect("client");
27699        let mut worker = Worker::new(client, "rust-workers");
27700        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
27701        assert!(worker
27702            .declare_workflow_signals("missing", &["finish"])
27703            .is_err());
27704        worker
27705            .declare_workflow_signals("orders", &["finish"])
27706            .unwrap();
27707        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
27708            assert!(worker.declare_workflow_signals("orders", names).is_err());
27709        }
27710        worker.register().await.unwrap();
27711        assert_eq!(
27712            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
27713                ["signals"],
27714            json!(["finish"])
27715        );
27716        worker.declare_workflow_signals("orders", &[]).unwrap();
27717        worker.register().await.unwrap();
27718        let registrations = server.request_bodies("/api/worker/register");
27719        assert_eq!(
27720            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
27721            json!([])
27722        );
27723        assert_eq!(
27724            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
27725            json!([])
27726        );
27727    }
27728
27729    #[tokio::test]
27730    async fn low_level_registration_preserves_query_and_update_contracts() {
27731        let server = MockWorkerServer::start();
27732        let client = Client::builder(server.base_url())
27733            .timeout(Duration::from_secs(2))
27734            .build()
27735            .expect("client");
27736        let contracts = json!({
27737            "orders": {
27738                "queries": ["current"],
27739                "updates": ["approve"],
27740                "update_validators": [],
27741            },
27742            "payments": {
27743                "queries": ["status"],
27744                "updates": ["capture"],
27745            },
27746        });
27747
27748        client
27749            .register_worker_with_command_contracts(
27750                "command-worker",
27751                "rust-workers",
27752                vec!["orders".to_string(), "payments".to_string()],
27753                vec![],
27754                1,
27755                1,
27756                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
27757                contracts.clone(),
27758            )
27759            .await
27760            .expect("query and update contracts must remain supported");
27761
27762        assert_eq!(
27763            server.request_body("/api/worker/register")["workflow_command_contracts"],
27764            contracts
27765        );
27766        assert!(server
27767            .request_body("/api/worker/register")
27768            .get("workflow_definition_fingerprints")
27769            .is_none());
27770    }
27771
27772    #[tokio::test]
27773    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
27774        let server = MockWorkerServer::start();
27775        let client = Client::builder(server.base_url())
27776            .timeout(Duration::from_secs(2))
27777            .build()
27778            .expect("client");
27779        let mut worker = Worker::new(client.clone(), "rust-workers");
27780        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27781
27782        assert!(worker
27783            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
27784            .is_err());
27785        assert!(worker
27786            .set_workflow_definition_sources("orders", &[])
27787            .is_err());
27788        worker
27789            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
27790            .expect("embed workflow source");
27791        worker.register().await.expect("register worker");
27792        let first = server.request_bodies("/api/worker/register")[0]
27793            ["workflow_definition_fingerprints"]["orders"]
27794            .as_str()
27795            .expect("source-backed fingerprint")
27796            .to_string();
27797        assert!(first.starts_with("sha256:"));
27798
27799        worker
27800            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
27801            .expect("change embedded helper source");
27802        worker.register().await.expect("register changed source");
27803        let changed = server.request_bodies("/api/worker/register")[1]
27804            ["workflow_definition_fingerprints"]["orders"]
27805            .as_str()
27806            .expect("changed fingerprint")
27807            .to_string();
27808        assert_ne!(first, changed);
27809
27810        let mut replacement =
27811            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
27812        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27813        replacement
27814            .register()
27815            .await
27816            .expect("register replacement handler");
27817        assert_eq!(
27818            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
27819            json!({})
27820        );
27821    }
27822
27823    #[tokio::test]
27824    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
27825        let server = MockWorkerServer::start();
27826        let control_only = Client::builder(server.base_url())
27827            .control_token(Some("control-secret".to_string()))
27828            .build()
27829            .expect("control client");
27830
27831        let error = control_only
27832            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27833            .await
27834            .expect_err("control token must not authorize a worker request");
27835        assert!(matches!(
27836            error,
27837            Error::MissingRoleCredentials { role: "worker", .. }
27838        ));
27839        assert_eq!(server.request_count("/api/worker/register"), 0);
27840
27841        let worker_only = Client::builder(server.base_url())
27842            .worker_token(Some("worker-secret".to_string()))
27843            .build()
27844            .expect("worker client");
27845        let error = worker_only
27846            .health()
27847            .await
27848            .expect_err("worker token must not authorize a control request");
27849        assert!(matches!(
27850            error,
27851            Error::MissingRoleCredentials {
27852                role: "control",
27853                ..
27854            }
27855        ));
27856        assert_eq!(server.request_count("/api/health"), 0);
27857    }
27858
27859    #[tokio::test]
27860    async fn shared_token_supports_worker_and_control_planes() {
27861        let server = MockWorkerServer::start();
27862        let client = Client::builder(server.base_url())
27863            .token(Some("shared-secret".to_string()))
27864            .build()
27865            .expect("client");
27866
27867        client.health().await.expect("control request");
27868        client
27869            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27870            .await
27871            .expect("worker request");
27872
27873        assert_eq!(
27874            server.authorization_for("/api/health").as_deref(),
27875            Some("Bearer shared-secret")
27876        );
27877        assert_eq!(
27878            server.control_protocol_for("/api/health").as_deref(),
27879            Some(CONTROL_PLANE_VERSION)
27880        );
27881        assert_eq!(
27882            server.authorization_for("/api/worker/register").as_deref(),
27883            Some("Bearer shared-secret")
27884        );
27885        assert_eq!(
27886            server
27887                .worker_protocol_for("/api/worker/register")
27888                .as_deref(),
27889            Some(WORKER_PROTOCOL_VERSION)
27890        );
27891    }
27892
27893    #[tokio::test]
27894    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
27895        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
27896        let server = MockWorkerServer::start();
27897        let client = Client::builder(server.base_url())
27898            .timeout(Duration::from_secs(2))
27899            .build()
27900            .expect("client");
27901
27902        client
27903            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
27904            .await
27905            .expect("register");
27906        client
27907            .heartbeat_worker("capture-worker", 1, 1)
27908            .await
27909            .expect("heartbeat");
27910        client
27911            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27912            .await
27913            .expect("workflow poll");
27914        client
27915            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27916            .await
27917            .expect("activity poll");
27918
27919        for path in [
27920            "/api/worker/register",
27921            "/api/worker/heartbeat",
27922            "/api/worker/workflow-tasks/poll",
27923            "/api/worker/activity-tasks/poll",
27924        ] {
27925            assert_eq!(
27926                server.worker_protocol_for(path).as_deref(),
27927                Some(WORKER_PROTOCOL_VERSION),
27928                "unexpected protocol for {path}"
27929            );
27930        }
27931
27932        assert_eq!(
27933            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
27934            1
27935        );
27936        assert_eq!(
27937            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
27938            500
27939        );
27940        assert_eq!(
27941            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
27942            1
27943        );
27944        assert!(
27945            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
27946                .as_str()
27947                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
27948        );
27949        assert!(
27950            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
27951                .as_str()
27952                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
27953        );
27954        let registration = server.request_body("/api/worker/register");
27955        for optional in [
27956            "cooperative_cancellation",
27957            "local_activities",
27958            "worker_sessions",
27959            "sticky_execution",
27960        ] {
27961            assert!(!registration["capabilities"]
27962                .as_array()
27963                .is_some_and(|capabilities| capabilities
27964                    .iter()
27965                    .any(|capability| capability.as_str() == Some(optional))));
27966        }
27967    }
27968
27969    #[tokio::test]
27970    async fn explicit_previous_worker_protocol_preserves_headers() {
27971        let server = MockWorkerServer::start();
27972        let client = Client::builder(server.base_url())
27973            .worker_protocol_version(WorkerProtocolVersion::V119)
27974            .timeout(Duration::from_secs(2))
27975            .build()
27976            .expect("client");
27977        client
27978            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
27979            .await
27980            .expect("register");
27981        client
27982            .heartbeat_worker("legacy-worker", 1, 1)
27983            .await
27984            .expect("heartbeat");
27985        client
27986            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
27987            .await
27988            .expect("workflow poll");
27989        client
27990            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
27991            .await
27992            .expect("activity poll");
27993        client
27994            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
27995            .await
27996            .expect("query poll");
27997        client
27998            .deregister_worker_registration("legacy-worker")
27999            .await
28000            .expect("deregister");
28001        for path in [
28002            "/api/worker/register",
28003            "/api/worker/heartbeat",
28004            "/api/worker/workflow-tasks/poll",
28005            "/api/worker/activity-tasks/poll",
28006            "/api/worker/query-tasks/poll",
28007            "/api/worker/registrations/legacy-worker",
28008        ] {
28009            assert_eq!(
28010                server.worker_protocol_for(path).as_deref(),
28011                Some("1.19"),
28012                "{path}"
28013            );
28014            assert_eq!(server.control_protocol_for(path), None, "{path}");
28015        }
28016    }
28017
28018    #[tokio::test]
28019    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
28020        let server = MockWorkerServer::start();
28021        let client = Client::builder(server.base_url())
28022            .worker_protocol_version(WorkerProtocolVersion::V119)
28023            .timeout(Duration::from_secs(2))
28024            .build()
28025            .expect("client");
28026        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
28027        let error = worker
28028            .register()
28029            .await
28030            .expect_err("legacy cooperation must be refused");
28031        assert!(matches!(
28032            error,
28033            Error::CooperativeCancellationUnavailable(_)
28034        ));
28035        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
28036    }
28037
28038    #[tokio::test]
28039    async fn query_task_endpoints_send_the_selected_worker_protocol() {
28040        let server = MockWorkerServer::start();
28041        let client = Client::builder(server.base_url())
28042            .timeout(Duration::from_secs(2))
28043            .build()
28044            .expect("client");
28045
28046        client
28047            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
28048            .await
28049            .expect("query poll");
28050        client
28051            .complete_query_task(
28052                "query-capture",
28053                "capture-worker",
28054                1,
28055                json!(8),
28056                DEFAULT_CODEC,
28057            )
28058            .await
28059            .expect("query complete");
28060        client
28061            .fail_query_task(
28062                "query-capture",
28063                "capture-worker",
28064                1,
28065                "failed",
28066                "query_rejected",
28067                "QueryFailed",
28068            )
28069            .await
28070            .expect("query fail");
28071
28072        for path in [
28073            "/api/worker/query-tasks/poll",
28074            "/api/worker/query-tasks/query-capture/complete",
28075            "/api/worker/query-tasks/query-capture/fail",
28076        ] {
28077            assert_eq!(
28078                server.worker_protocol_for(path).as_deref(),
28079                Some(WORKER_PROTOCOL_VERSION),
28080                "unexpected protocol for {path}"
28081            );
28082        }
28083
28084        assert_eq!(
28085            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
28086            1
28087        );
28088        assert!(
28089            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
28090                .as_str()
28091                .is_some_and(|id| id.starts_with("rust-query-poll-"))
28092        );
28093    }
28094
28095    #[tokio::test]
28096    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
28097        let server = MockWorkerServer::transient_worker_failures();
28098        let client = Client::builder(server.base_url())
28099            .timeout(Duration::from_secs(2))
28100            .build()
28101            .expect("client");
28102
28103        client
28104            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
28105            .await
28106            .expect("workflow poll retry");
28107        client
28108            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
28109            .await
28110            .expect("activity poll retry");
28111        client
28112            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
28113            .await
28114            .expect("query poll retry");
28115
28116        for path in [
28117            "/api/worker/workflow-tasks/poll",
28118            "/api/worker/activity-tasks/poll",
28119            "/api/worker/query-tasks/poll",
28120        ] {
28121            let bodies = server.request_bodies(path);
28122            assert_eq!(bodies.len(), 2, "{path} must be retried once");
28123            assert_eq!(
28124                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
28125                "{path} must preserve the request binding across retry"
28126            );
28127        }
28128    }
28129
28130    #[tokio::test]
28131    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
28132        let server = MockWorkerServer::consecutive_poll_failures(2);
28133        let client = Client::builder(server.base_url())
28134            .timeout(Duration::from_secs(2))
28135            .build()
28136            .expect("client");
28137        let mut worker = Worker::new(client, "capture")
28138            .worker_id("capture-worker")
28139            .poll_timeout(Duration::from_millis(10))
28140            .retry_policy(WorkerRetryPolicy {
28141                max_retries: 2,
28142                initial_backoff: Duration::from_millis(1),
28143                max_backoff: Duration::from_millis(1),
28144            });
28145        worker.register_workflow(
28146            "capture.workflow",
28147            |_ctx, _input| async move { Ok(Value::Null) },
28148        );
28149        worker.register_activity(
28150            "capture.activity",
28151            |_ctx, _input| async move { Ok(Value::Null) },
28152        );
28153        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
28154            Ok(Value::Null)
28155        });
28156
28157        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
28158
28159        for path in [
28160            "/api/worker/workflow-tasks/poll",
28161            "/api/worker/activity-tasks/poll",
28162            "/api/worker/query-tasks/poll",
28163        ] {
28164            let bodies = server.request_bodies(path);
28165            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
28166            assert!(
28167                bodies
28168                    .iter()
28169                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
28170                "{path} must preserve one request binding across every retry"
28171            );
28172        }
28173    }
28174
28175    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
28176        let reason = if unavailable {
28177            "storage_admission_unavailable"
28178        } else {
28179            "storage_pressure"
28180        };
28181        let mut body = json!({
28182            "reason": reason,
28183            "storage_state": if unavailable { "fenced" } else { "draining" },
28184            "retryable": true,
28185            "retry_after_seconds": 1,
28186        });
28187        if !mid_poll {
28188            body["request_admitted"] = json!(false);
28189        }
28190        if let Some(id) = poll_id {
28191            body["task"] = Value::Null;
28192            body["poll_status"] = json!(reason);
28193            body["poll_request_id"] = json!(id);
28194            body["retry_same_poll_request_id"] = json!(true);
28195            body["claim_admitted"] = json!(false);
28196        }
28197        body
28198    }
28199
28200    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
28201        let operation = match path {
28202            "/api/worker/register" => "register_worker",
28203            "/api/worker/heartbeat" => "heartbeat_worker",
28204            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
28205            "/api/worker/activity-tasks/poll" => "poll_activity_task",
28206            "/api/worker/query-tasks/poll" => "poll_query_task",
28207            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
28208            _ => return None,
28209        };
28210        let request: Value = serde_json::from_str(request).ok()?;
28211        let mut response = json!({
28212            "reason": "backend_unavailable",
28213            "operation": operation,
28214            "outcome": "unknown",
28215            "retryable": true,
28216            "retry_after_seconds": 1,
28217            "worker_id": request["worker_id"],
28218            "task_queue": request.get("task_queue"),
28219        });
28220        if path.ends_with("/poll") {
28221            response["task"] = Value::Null;
28222            response["poll_status"] = json!("backend_unavailable");
28223            response["poll_request_id"] = request["poll_request_id"].clone();
28224            response["retry_same_poll_request_id"] = json!(true);
28225        }
28226        Some(response)
28227    }
28228
28229    fn backend_retry_override(
28230        path: &str,
28231        request: &str,
28232        number: usize,
28233    ) -> Option<(&'static str, String)> {
28234        if number > 8 {
28235            return None;
28236        }
28237        Some((
28238            "503 Service Unavailable",
28239            backend_refusal(path, request)?.to_string(),
28240        ))
28241    }
28242
28243    fn backend_unavailable_override(
28244        path: &str,
28245        request: &str,
28246        _number: usize,
28247    ) -> Option<(&'static str, String)> {
28248        Some((
28249            "503 Service Unavailable",
28250            backend_refusal(path, request)?.to_string(),
28251        ))
28252    }
28253
28254    fn storage_worker(server: &MockWorkerServer) -> Worker {
28255        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
28256            .worker_id("storage-worker")
28257            .retry_policy(WorkerRetryPolicy {
28258                max_retries: 1,
28259                initial_backoff: Duration::from_millis(1),
28260                max_backoff: Duration::from_millis(1),
28261            })
28262    }
28263
28264    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
28265        let requests = server.requests.lock().expect("requests");
28266        let bodies: Vec<_> = requests
28267            .iter()
28268            .filter(|request| request.path == path)
28269            .map(|request| &request.body)
28270            .collect();
28271        assert_eq!(bodies.len(), count, "{path}");
28272        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
28273    }
28274
28275    #[test]
28276    fn backend_recovery_requires_the_explicit_worker_contract() {
28277        for (path, operation) in [
28278            ("/worker/register", "register_worker"),
28279            ("/worker/heartbeat", "heartbeat_worker"),
28280            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
28281            ("/worker/activity-tasks/poll", "poll_activity_task"),
28282            ("/worker/query-tasks/poll", "poll_query_task"),
28283            (
28284                "/worker/update-validation-tasks/poll",
28285                "poll_update_validation_task",
28286            ),
28287        ] {
28288            let poll_id = path.ends_with("/poll").then_some("same-poll");
28289            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
28290            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
28291                .expect("worker operation");
28292            assert_eq!(body["operation"], operation);
28293            let error = Error::Http {
28294                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28295                body: body.to_string(),
28296            };
28297            assert_eq!(
28298                worker_backend_unavailable_retry_after(&error, path, poll_id),
28299                Some(Duration::from_secs(1))
28300            );
28301            assert!(!worker_operation_is_retryable(&error));
28302            for (field, value) in [
28303                ("operation", json!("wrong_operation")),
28304                ("outcome", json!("completed")),
28305                ("retryable", json!(false)),
28306                ("retry_after_seconds", json!(0)),
28307                ("worker_id", json!("")),
28308            ] {
28309                let mut invalid = body.clone();
28310                invalid[field] = value;
28311                let error = Error::Http {
28312                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28313                    body: invalid.to_string(),
28314                };
28315                assert!(
28316                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
28317                    "{path}: {field}"
28318                );
28319                assert!(!worker_operation_is_retryable(&error));
28320            }
28321            if let Some(poll_id) = poll_id {
28322                for (field, value) in [
28323                    ("poll_request_id", json!("wrong-poll")),
28324                    ("poll_status", json!("empty")),
28325                    ("task", json!({"task_id":"claimed"})),
28326                    ("retry_same_poll_request_id", json!(false)),
28327                ] {
28328                    let mut invalid = body.clone();
28329                    invalid[field] = value;
28330                    let error = Error::Http {
28331                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28332                        body: invalid.to_string(),
28333                    };
28334                    assert!(
28335                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
28336                            .is_none(),
28337                        "{path}: {field}"
28338                    );
28339                }
28340            }
28341            let error = Error::Http {
28342                status: reqwest::StatusCode::UNAUTHORIZED,
28343                body: body.to_string(),
28344            };
28345            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
28346            assert!(!worker_operation_is_retryable(&error));
28347        }
28348    }
28349
28350    #[tokio::test]
28351    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
28352        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28353            request_override: Some(backend_retry_override),
28354            ..MockWorkerBehavior::default()
28355        });
28356        let mut worker =
28357            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28358        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
28359        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
28360        worker.register_query("backend.workflow", "state", |_, _| async {
28361            Ok(Value::Null)
28362        });
28363        worker.register().await.expect("registration recovery");
28364        worker
28365            .client
28366            .heartbeat_worker("storage-worker", 1, 1)
28367            .await
28368            .expect("heartbeat recovery");
28369        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
28370        for path in [
28371            "/api/worker/register",
28372            "/api/worker/heartbeat",
28373            "/api/worker/workflow-tasks/poll",
28374            "/api/worker/activity-tasks/poll",
28375            "/api/worker/query-tasks/poll",
28376        ] {
28377            assert_identical_requests(&server, path, 9);
28378        }
28379    }
28380
28381    #[tokio::test]
28382    async fn backend_recovery_wait_stops_with_worker() {
28383        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28384            request_override: Some(backend_unavailable_override),
28385            ..MockWorkerBehavior::default()
28386        });
28387        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
28388            max_retries: 1,
28389            initial_backoff: Duration::from_secs(2),
28390            max_backoff: Duration::from_secs(2),
28391        });
28392        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
28393        let started = tokio::time::Instant::now();
28394        let _ = tokio::time::timeout(
28395            Duration::from_secs(1),
28396            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
28397        )
28398        .await
28399        .expect("shutdown interrupts backend wait");
28400        assert!(started.elapsed() < Duration::from_secs(1));
28401        assert!(server.request_count("/api/worker/register") >= 1);
28402    }
28403
28404    #[test]
28405    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
28406        for unavailable in [false, true] {
28407            for mid_poll in [false, true] {
28408                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
28409                let error = Error::Http {
28410                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28411                    body: body.to_string(),
28412                };
28413                assert_eq!(
28414                    worker_storage_admission_retry_after(&error, Some("same-poll")),
28415                    Some(Duration::from_secs(1))
28416                );
28417                assert!(
28418                    !worker_operation_is_retryable(&error),
28419                    "storage is not a bounded generic retry"
28420                );
28421                for (field, value) in [
28422                    ("poll_request_id", json!("wrong-poll")),
28423                    ("task", json!({"task_id":"claimed"})),
28424                    ("retryable", json!(false)),
28425                    ("retry_after_seconds", json!(0)),
28426                    ("retry_after_seconds", json!(true)),
28427                    ("retry_after_seconds", json!(1.0)),
28428                    ("storage_state", json!("normal")),
28429                    ("poll_status", json!("empty")),
28430                    ("claim_admitted", json!(true)),
28431                    ("retry_same_poll_request_id", json!(false)),
28432                    ("request_admitted", json!(true)),
28433                ] {
28434                    let mut invalid = body.clone();
28435                    invalid[field] = value;
28436                    let error = Error::Http {
28437                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28438                        body: invalid.to_string(),
28439                    };
28440                    assert!(
28441                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
28442                        "{field}"
28443                    );
28444                }
28445            }
28446        }
28447        let body = storage_refusal(None, false, false);
28448        let error = Error::Http {
28449            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28450            body: body.to_string(),
28451        };
28452        assert!(worker_storage_admission_retry_after(&error, None).is_some());
28453        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
28454        let error = Error::Http {
28455            status: reqwest::StatusCode::FORBIDDEN,
28456            body: body.to_string(),
28457        };
28458        assert!(worker_storage_admission_retry_after(&error, None).is_none());
28459        let body = storage_refusal(None, false, true);
28460        let error = Error::Http {
28461            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28462            body: body.to_string(),
28463        };
28464        assert!(worker_storage_admission_retry_after(&error, None).is_none());
28465    }
28466
28467    #[tokio::test]
28468    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
28469        for unavailable in [false, true] {
28470            for mid_poll in [false, true] {
28471                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28472                    poll_failures_per_path: 1,
28473                    storage_refusals: 7,
28474                    storage_path: Some("/poll"),
28475                    storage_unavailable: unavailable,
28476                    storage_mid_poll: mid_poll,
28477                    ..MockWorkerBehavior::default()
28478                });
28479                let mut worker = storage_worker(&server);
28480                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
28481                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
28482                for path in [
28483                    "/api/worker/workflow-tasks/poll",
28484                    "/api/worker/activity-tasks/poll",
28485                    "/api/worker/query-tasks/poll",
28486                ] {
28487                    assert_identical_requests(&server, path, 9);
28488                }
28489            }
28490        }
28491    }
28492
28493    #[tokio::test]
28494    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
28495        struct CountedBody(Arc<AtomicUsize>);
28496        impl Serialize for CountedBody {
28497            fn serialize<S: Serializer>(
28498                &self,
28499                serializer: S,
28500            ) -> std::result::Result<S::Ok, S::Error> {
28501                let count = self.0.fetch_add(1, Ordering::SeqCst);
28502                json!({"serialization":count,"lease_owner":"worker","attempt":7})
28503                    .serialize(serializer)
28504            }
28505        }
28506        for path in [
28507            "/api/worker/register",
28508            "/api/worker/heartbeat",
28509            "/api/worker/workflow-tasks/storage-task/complete",
28510            "/api/worker/workflow-tasks/storage-task/fail",
28511            "/api/worker/activity-tasks/storage-task/complete",
28512            "/api/worker/activity-tasks/storage-task/fail",
28513            "/api/worker/activity-tasks/storage-task/heartbeat",
28514            "/api/worker/query-tasks/storage-task/complete",
28515            "/api/worker/query-tasks/storage-task/fail",
28516        ] {
28517            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28518                storage_refusals: 7,
28519                storage_path: Some(path),
28520                ..MockWorkerBehavior::default()
28521            });
28522            let worker =
28523                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28524            let calls = Arc::new(AtomicUsize::new(0));
28525            let _: Value = worker
28526                .client
28527                .request_json(
28528                    reqwest::Method::POST,
28529                    &path[4..],
28530                    RequestProtocol::DefaultWorker,
28531                    Some(&CountedBody(Arc::clone(&calls))),
28532                )
28533                .await
28534                .expect("prepared request recovery");
28535            assert_eq!(calls.load(Ordering::SeqCst), 1);
28536            assert_identical_requests(&server, path, 8);
28537        }
28538        for worker_scope in [false, true] {
28539            let path = if worker_scope {
28540                "/api/health"
28541            } else {
28542                "/api/worker/register"
28543            };
28544            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28545                storage_refusals: usize::MAX,
28546                storage_path: Some(path),
28547                ..MockWorkerBehavior::default()
28548            });
28549            let worker = storage_worker(&server);
28550            let client = worker.client.clone();
28551            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
28552            let error = if worker_scope {
28553                worker
28554                    .client
28555                    .health()
28556                    .await
28557                    .expect_err("control plane is not retried")
28558            } else {
28559                client
28560                    .request_json::<Value, Value>(
28561                        reqwest::Method::POST,
28562                        "/worker/register",
28563                        RequestProtocol::DefaultWorker,
28564                        Some(&json!({})),
28565                    )
28566                    .await
28567                    .expect_err("direct client is not retried")
28568            };
28569            assert!(worker_storage_admission_body(&error).is_some());
28570            assert_eq!(server.request_count(path), 1);
28571        }
28572    }
28573
28574    #[tokio::test]
28575    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
28576        for fail in [false, true] {
28577            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28578                storage_activity: true,
28579                storage_refusals: 7,
28580                storage_path: Some("/storage-activity/"),
28581                ..MockWorkerBehavior::default()
28582            });
28583            let mut worker = storage_worker(&server);
28584            let calls = Arc::new(AtomicUsize::new(0));
28585            let observed = Arc::clone(&calls);
28586            worker.register_activity("storage.activity", move |ctx, _| {
28587                let calls = Arc::clone(&observed);
28588                async move {
28589                    calls.fetch_add(1, Ordering::SeqCst);
28590                    ctx.heartbeat(json!({"step":2})).await?;
28591                    if fail {
28592                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
28593                    } else {
28594                        Ok(json!({"receipt":true}))
28595                    }
28596                }
28597            });
28598            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
28599            assert_eq!(calls.load(Ordering::SeqCst), 1);
28600            assert_identical_requests(
28601                &server,
28602                "/api/worker/activity-tasks/storage-activity/heartbeat",
28603                8,
28604            );
28605            let suffix = if fail { "fail" } else { "complete" };
28606            assert_identical_requests(
28607                &server,
28608                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
28609                8,
28610            );
28611            let other = if fail { "complete" } else { "fail" };
28612            assert_eq!(
28613                server.request_count(&format!(
28614                    "/api/worker/activity-tasks/storage-activity/{other}"
28615                )),
28616                0
28617            );
28618        }
28619    }
28620
28621    #[tokio::test]
28622    async fn storage_waits_are_interruptible_without_false_activity_failure() {
28623        for path in [
28624            "/api/worker/register",
28625            "/api/worker/heartbeat",
28626            "/api/worker/activity-tasks/poll",
28627            "/api/worker/activity-tasks/storage-activity/heartbeat",
28628            "/api/worker/activity-tasks/storage-activity/complete",
28629        ] {
28630            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28631                storage_activity: true,
28632                storage_refusals: usize::MAX,
28633                storage_path: Some(path),
28634                ..MockWorkerBehavior::default()
28635            });
28636            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
28637            worker.register_activity("storage.activity", |ctx, _| async move {
28638                ctx.heartbeat(json!({"step":2})).await?;
28639                Ok(json!({"receipt":true}))
28640            });
28641            let shutdown = async {
28642                while server.request_count(path) == 0 {
28643                    tokio::time::sleep(Duration::from_millis(1)).await;
28644                }
28645            };
28646            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
28647                .await
28648                .expect("shutdown interrupts admission");
28649            assert!(
28650                result.is_err(),
28651                "a refused operation must not appear acknowledged: {path}, {result:?}"
28652            );
28653            assert_eq!(server.request_count(path), 1);
28654            assert_eq!(
28655                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
28656                0
28657            );
28658            assert_eq!(
28659                server.request_count("/api/worker/registrations/mock-worker"),
28660                usize::from(!path.ends_with("/register"))
28661            );
28662        }
28663    }
28664
28665    #[tokio::test]
28666    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
28667        for fail in [false, true] {
28668            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28669                storage_query: true,
28670                storage_refusals: 7,
28671                storage_path: Some("/storage-query/"),
28672                ..MockWorkerBehavior::default()
28673            });
28674            let mut worker = storage_worker(&server);
28675            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
28676            let calls = Arc::new(AtomicUsize::new(0));
28677            let observed = Arc::clone(&calls);
28678            worker.register_query("storage.workflow", "state", move |_, _| {
28679                let calls = Arc::clone(&observed);
28680                async move {
28681                    calls.fetch_add(1, Ordering::SeqCst);
28682                    if fail {
28683                        Err(Error::WorkerLoop("intentional query failure".to_string()))
28684                    } else {
28685                        Ok(json!({"state":"waiting"}))
28686                    }
28687                }
28688            });
28689            assert_eq!(worker.run_once().await.expect("query settled"), 1);
28690            assert_eq!(calls.load(Ordering::SeqCst), 1);
28691            let suffix = if fail { "fail" } else { "complete" };
28692            assert_identical_requests(
28693                &server,
28694                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
28695                8,
28696            );
28697            let other = if fail { "complete" } else { "fail" };
28698            assert_eq!(
28699                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
28700                0
28701            );
28702        }
28703    }
28704
28705    #[tokio::test]
28706    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
28707        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28708            storage_refusals: 7,
28709            storage_path: Some("/poll"),
28710            unauthorized_polls: true,
28711            ..MockWorkerBehavior::default()
28712        });
28713        let error = storage_worker(&server)
28714            .run_once()
28715            .await
28716            .expect_err("auth remains terminal");
28717        assert!(matches!(
28718            error,
28719            Error::Http {
28720                status: reqwest::StatusCode::UNAUTHORIZED,
28721                ..
28722            }
28723        ));
28724        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
28725
28726        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28727            storage_refusals: 7,
28728            storage_path: Some("/activity-cancel/complete"),
28729            ..MockWorkerBehavior::default()
28730        });
28731        let worker =
28732            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28733        let error = worker
28734            .client
28735            .complete_activity_task(
28736                "activity-cancel",
28737                "attempt-cancel",
28738                "worker",
28739                json!({}),
28740                DEFAULT_CODEC,
28741            )
28742            .await
28743            .expect_err("cancellation remains terminal");
28744        assert!(activity_task_rejection_is_final(&error));
28745        assert_identical_requests(
28746            &server,
28747            "/api/worker/activity-tasks/activity-cancel/complete",
28748            8,
28749        );
28750
28751        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28752            storage_refusals: usize::MAX,
28753            storage_path: Some("/poll"),
28754            storage_wrong_poll_id: true,
28755            ..MockWorkerBehavior::default()
28756        });
28757        assert!(storage_worker(&server).run_once().await.is_err());
28758        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28759    }
28760
28761    #[tokio::test]
28762    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
28763        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28764            storage_refusals: usize::MAX,
28765            storage_path: Some("/poll"),
28766            ..MockWorkerBehavior::default()
28767        });
28768        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
28769        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
28770        let run = tokio::spawn(async move { worker.run().await });
28771        tokio::time::timeout(Duration::from_secs(2), async {
28772            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
28773                tokio::time::sleep(Duration::from_millis(1)).await;
28774            }
28775        })
28776        .await
28777        .expect("poll started");
28778        run.abort();
28779        assert!(run.await.expect_err("cancelled run").is_cancelled());
28780        tokio::time::sleep(Duration::from_millis(250)).await;
28781        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
28782    }
28783
28784    #[tokio::test]
28785    async fn query_protocol_rejection_from_older_server_is_typed() {
28786        let server = MockWorkerServer::reject_query_protocol();
28787        let client = Client::builder(server.base_url())
28788            .timeout(Duration::from_secs(2))
28789            .build()
28790            .expect("client");
28791
28792        let error = client
28793            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
28794            .await
28795            .expect_err("server below query protocol floor must reject");
28796        let Error::Protocol(failure) = error else {
28797            panic!("expected typed protocol failure");
28798        };
28799
28800        assert_eq!(failure.status, 400);
28801        assert_eq!(failure.reason, "unsupported_protocol_version");
28802        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
28803        assert_eq!(
28804            failure.requested_version.as_deref(),
28805            Some(WORKER_PROTOCOL_VERSION)
28806        );
28807        assert_eq!(
28808            server
28809                .worker_protocol_for("/api/worker/query-tasks/poll")
28810                .as_deref(),
28811            Some(WORKER_PROTOCOL_VERSION)
28812        );
28813    }
28814
28815    #[tokio::test]
28816    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
28817        let server = MockWorkerServer::reject_query_protocol();
28818        let client = Client::builder(server.base_url())
28819            .timeout(Duration::from_secs(2))
28820            .build()
28821            .expect("client");
28822        let mut worker = Worker::new(client, "rust-workers")
28823            .worker_id("baseline-worker")
28824            .poll_timeout(Duration::from_millis(10));
28825
28826        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
28827            Ok(Value::Null)
28828        });
28829
28830        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
28831        assert_eq!(
28832            server
28833                .worker_protocol_for("/api/worker/workflow-tasks/poll")
28834                .as_deref(),
28835            Some(WORKER_PROTOCOL_VERSION)
28836        );
28837        assert_eq!(
28838            server.worker_protocol_for("/api/worker/query-tasks/poll"),
28839            None,
28840            "a worker without query handlers must not use the query-task endpoint"
28841        );
28842    }
28843
28844    #[tokio::test]
28845    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
28846        let server = MockWorkerServer::reject_query_completion();
28847        let client = Client::builder(server.base_url())
28848            .timeout(Duration::from_secs(2))
28849            .build()
28850            .expect("client");
28851
28852        let error = client
28853            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
28854            .await
28855            .expect_err("expired completion must be rejected");
28856        let Error::QueryFailed(failure) = error else {
28857            panic!("expected typed query failure");
28858        };
28859        assert_eq!(failure.status, 409);
28860        assert_eq!(failure.reason, "query_task_timed_out");
28861
28862        let mut worker = Worker::new(client, "rust-workers")
28863            .worker_id("late-worker")
28864            .poll_timeout(Duration::from_millis(10));
28865        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28866        worker.register_query(
28867            "counter",
28868            "current",
28869            |_ctx, _args| async move { Ok(json!(8)) },
28870        );
28871
28872        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
28873        assert_eq!(
28874            worker
28875                .run_once()
28876                .await
28877                .expect("worker continues after late completion"),
28878            0
28879        );
28880        assert_eq!(
28881            server.request_count("/api/worker/query-tasks/query-late/complete"),
28882            2
28883        );
28884        assert_eq!(
28885            server.request_count("/api/worker/query-tasks/query-late/fail"),
28886            0,
28887            "a server completion rejection must not be reported as an encoding failure"
28888        );
28889    }
28890
28891    #[tokio::test]
28892    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
28893        let server = MockWorkerServer::start();
28894        let client = Client::builder(server.base_url())
28895            .timeout(Duration::from_secs(2))
28896            .build()
28897            .expect("client");
28898        let mut worker = Worker::new(client, "rust-workers")
28899            .worker_id("joined-worker")
28900            .poll_timeout(Duration::from_millis(10));
28901        worker.register_workflow(
28902            "joined.workflow",
28903            |_ctx, _input| async move { Ok(Value::Null) },
28904        );
28905        worker.register_activity(
28906            "joined.activity",
28907            |_ctx, _input| async move { Ok(Value::Null) },
28908        );
28909        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
28910            Ok(Value::Null)
28911        });
28912
28913        worker
28914            .run_until(tokio::time::sleep(Duration::from_millis(20)))
28915            .await
28916            .expect("normal shutdown");
28917
28918        let deregistration_path = "/api/worker/registrations/mock-worker";
28919        assert_eq!(server.request_count(deregistration_path), 1);
28920        for poll_path in [
28921            "/api/worker/workflow-tasks/poll",
28922            "/api/worker/activity-tasks/poll",
28923            "/api/worker/query-tasks/poll",
28924        ] {
28925            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
28926        }
28927        assert_eq!(
28928            server.captured_paths().last().map(String::as_str),
28929            Some(deregistration_path),
28930            "deregistration must start only after every poller has joined"
28931        );
28932    }
28933
28934    #[tokio::test]
28935    async fn registration_failure_does_not_deregister() {
28936        let server = MockWorkerServer::rejected_registration();
28937        let client = Client::builder(server.base_url())
28938            .timeout(Duration::from_secs(2))
28939            .build()
28940            .expect("client");
28941        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
28942
28943        let error = worker
28944            .run_until(async {})
28945            .await
28946            .expect_err("registration must fail");
28947        assert!(matches!(
28948            error,
28949            Error::Http {
28950                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28951                ..
28952            }
28953        ));
28954        assert!(server
28955            .captured_paths()
28956            .iter()
28957            .all(|path| !path.starts_with("/api/worker/registrations/")));
28958    }
28959
28960    #[tokio::test]
28961    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
28962        let server = MockWorkerServer::rejected_registration_protocol();
28963        let client = Client::builder(server.base_url())
28964            .timeout(Duration::from_secs(2))
28965            .build()
28966            .expect("client");
28967        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
28968
28969        let error = worker
28970            .run_until(async {})
28971            .await
28972            .expect_err("a protocol 1.16 server must reject this worker");
28973        let Error::Protocol(failure) = error else {
28974            panic!("expected typed protocol rejection");
28975        };
28976        assert_eq!(failure.reason, "unsupported_protocol_version");
28977        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
28978        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
28979        assert_eq!(
28980            server
28981                .worker_protocol_for("/api/worker/register")
28982                .as_deref(),
28983            Some(WORKER_PROTOCOL_VERSION)
28984        );
28985    }
28986
28987    #[tokio::test]
28988    async fn declined_registration_does_not_deregister() {
28989        let server = MockWorkerServer::declined_registration();
28990        let client = Client::builder(server.base_url())
28991            .timeout(Duration::from_secs(2))
28992            .build()
28993            .expect("client");
28994        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
28995
28996        let error = worker
28997            .run_until(async {})
28998            .await
28999            .expect_err("declined registration must fail");
29000        assert!(matches!(error, Error::WorkerLoop(_)));
29001        assert!(error.to_string().contains("was not accepted"));
29002        assert!(server
29003            .captured_paths()
29004            .iter()
29005            .all(|path| !path.starts_with("/api/worker/registrations/")));
29006    }
29007
29008    #[tokio::test]
29009    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
29010        let server = MockWorkerServer::rejected_deregistration();
29011        let client = Client::builder(server.base_url())
29012            .timeout(Duration::from_secs(2))
29013            .build()
29014            .expect("client");
29015        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
29016
29017        let error = worker
29018            .run_until(async {})
29019            .await
29020            .expect_err("deregistration must fail");
29021        assert!(matches!(
29022            error,
29023            Error::Http {
29024                status: reqwest::StatusCode::FORBIDDEN,
29025                ..
29026            }
29027        ));
29028        assert_eq!(
29029            server.request_count("/api/worker/registrations/mock-worker"),
29030            1
29031        );
29032    }
29033
29034    #[tokio::test]
29035    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
29036        let server = MockWorkerServer::rejected_deregistration_protocol();
29037        let client = Client::builder(server.base_url())
29038            .timeout(Duration::from_secs(2))
29039            .build()
29040            .expect("client");
29041        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
29042
29043        let error = worker
29044            .run_until(async {})
29045            .await
29046            .expect_err("protocol rejection must fail shutdown");
29047        let Error::Protocol(failure) = error else {
29048            panic!("expected typed protocol failure");
29049        };
29050        assert_eq!(failure.reason, "unsupported_protocol_version");
29051        assert_eq!(
29052            failure.requested_version.as_deref(),
29053            Some(WORKER_PROTOCOL_VERSION)
29054        );
29055        assert_eq!(
29056            server.request_count("/api/worker/registrations/mock-worker"),
29057            1
29058        );
29059    }
29060
29061    #[tokio::test]
29062    async fn primary_poller_error_retains_deregistration_failure_context() {
29063        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
29064        let client = Client::builder(server.base_url())
29065            .timeout(Duration::from_secs(2))
29066            .build()
29067            .expect("client");
29068        let mut worker = Worker::new(client, "rust-workers")
29069            .worker_id("combined-failure")
29070            .poll_timeout(Duration::from_millis(10));
29071        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
29072            Ok(Value::Null)
29073        });
29074
29075        let error = worker
29076            .run()
29077            .await
29078            .expect_err("worker and cleanup must fail");
29079        let summary = error.to_string();
29080        assert!(summary.contains("authentication_failed"));
29081        assert!(summary.contains("worker cannot deregister"));
29082        let Error::WorkerShutdown {
29083            primary,
29084            deregistration,
29085        } = error
29086        else {
29087            panic!("expected combined worker shutdown error");
29088        };
29089        assert!(matches!(
29090            *primary,
29091            Error::Http {
29092                status: reqwest::StatusCode::UNAUTHORIZED,
29093                ..
29094            }
29095        ));
29096        assert!(matches!(
29097            *deregistration,
29098            Error::Http {
29099                status: reqwest::StatusCode::FORBIDDEN,
29100                ..
29101            }
29102        ));
29103        assert_eq!(
29104            server.request_count("/api/worker/registrations/mock-worker"),
29105            1
29106        );
29107    }
29108
29109    #[tokio::test]
29110    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
29111        let server = MockWorkerServer::start();
29112        let client = Client::builder(server.base_url())
29113            .timeout(Duration::from_secs(2))
29114            .build()
29115            .expect("client");
29116        let mut worker = Worker::new(client, "rust-workers")
29117            .worker_id("activity-only-worker")
29118            .poll_timeout(Duration::from_millis(10));
29119
29120        worker.register_activity(
29121            "activity.only",
29122            |_ctx, _args| async move { Ok(Value::Null) },
29123        );
29124
29125        worker.run_until(async {}).await.expect("run worker");
29126    }
29127
29128    #[tokio::test]
29129    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
29130        let server = MockWorkerServer::start();
29131        let client = Client::builder(server.base_url())
29132            .timeout(Duration::from_secs(2))
29133            .build()
29134            .expect("client");
29135        let mut worker = Worker::new(client, "rust-workers")
29136            .worker_id("workflow-only-worker")
29137            .poll_timeout(Duration::from_millis(10));
29138
29139        worker.register_workflow(
29140            "workflow.only",
29141            |_ctx, _input| async move { Ok(Value::Null) },
29142        );
29143
29144        worker.run_until(async {}).await.expect("run worker");
29145    }
29146
29147    #[tokio::test]
29148    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
29149        let server = MockWorkerServer::start();
29150        let client = Client::builder(server.base_url())
29151            .timeout(Duration::from_secs(2))
29152            .build()
29153            .expect("client");
29154        let observations = Arc::new(Mutex::new(Vec::new()));
29155        let observed = Arc::clone(&observations);
29156        let mut worker = Worker::new(client, "rust-workers")
29157            .worker_id("observed-heartbeat-worker")
29158            .poll_timeout(Duration::from_millis(10))
29159            .on_worker_heartbeat(move |observation| {
29160                observed
29161                    .lock()
29162                    .expect("heartbeat observations")
29163                    .push(observation.clone());
29164            });
29165
29166        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
29167            Ok(Value::Null)
29168        });
29169        let acknowledged = Arc::clone(&observations);
29170        worker
29171            .run_until(async move {
29172                tokio::time::timeout(Duration::from_secs(2), async move {
29173                    loop {
29174                        if !acknowledged
29175                            .lock()
29176                            .expect("heartbeat observations")
29177                            .is_empty()
29178                        {
29179                            break;
29180                        }
29181                        tokio::time::sleep(Duration::from_millis(1)).await;
29182                    }
29183                })
29184                .await
29185                .expect("heartbeat acknowledgement within timeout");
29186            })
29187            .await
29188            .expect("run worker");
29189
29190        let observations = observations.lock().expect("heartbeat observations");
29191        let first = observations.first().expect("heartbeat acknowledgement");
29192        assert_eq!(first.worker_id, "observed-heartbeat-worker");
29193        assert_eq!(first.task_queue, "rust-workers");
29194        assert!(first.acknowledged_at_unix_millis > 0);
29195        assert_eq!(first.acknowledgement, json!({}));
29196    }
29197
29198    #[tokio::test]
29199    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
29200        let server = MockWorkerServer::delayed_heartbeat_worker();
29201        let client = Client::builder(server.base_url())
29202            .timeout(Duration::from_secs(3))
29203            .build()
29204            .expect("client");
29205        let observations = Arc::new(Mutex::new(Vec::new()));
29206        let observed = Arc::clone(&observations);
29207        let mut worker = Worker::new(client, "rust-snapshot-workers")
29208            .worker_id("rust-snapshot-worker")
29209            .poll_timeout(Duration::from_millis(10))
29210            .on_worker_heartbeat(move |observation| {
29211                observed
29212                    .lock()
29213                    .expect("heartbeat observations")
29214                    .push(observation.clone());
29215            });
29216
29217        worker.register_workflow("snapshot", |ctx, _input| async move {
29218            ctx.wait_signal("finish").await?;
29219            Ok(json!({"status": "finished"}))
29220        });
29221        worker.register_query("snapshot", "current", |ctx, _args| async move {
29222            Ok(json!(ctx
29223                .signals("increment")
29224                .iter()
29225                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
29226                .sum::<i64>()))
29227        });
29228        worker.register_activity("cancel-aware", |_ctx, _args| async move {
29229            Ok(json!({"late": "completion"}))
29230        });
29231
29232        worker
29233            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
29234            .await
29235            .expect("delayed heartbeat must allow a clean worker shutdown");
29236
29237        let observations = observations.lock().expect("heartbeat observations");
29238        assert!(
29239            observations.len() >= 3,
29240            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
29241        );
29242        assert!(
29243            observations.windows(2).all(|pair| {
29244                pair[1].acknowledged_at_unix_millis
29245                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
29246                    >= 850
29247            }),
29248            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
29249        );
29250        drop(observations);
29251
29252        let heartbeat_times = server.request_times("/api/worker/heartbeat");
29253        let delayed_request_at = *heartbeat_times
29254            .get(1)
29255            .expect("intentionally delayed heartbeat request");
29256        let delay_window_start = delayed_request_at + Duration::from_millis(100);
29257        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
29258        for path in [
29259            "/api/worker/workflow-tasks/poll",
29260            "/api/worker/activity-tasks/poll",
29261            "/api/worker/query-tasks/poll",
29262        ] {
29263            assert!(
29264                server
29265                    .request_times(path)
29266                    .iter()
29267                    .any(|received_at| *received_at >= delay_window_start
29268                        && *received_at <= delay_window_end),
29269                "{path} must keep polling while a heartbeat acknowledgement is delayed"
29270            );
29271        }
29272        assert!(
29273            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
29274            "workflow work must be settled"
29275        );
29276        assert!(
29277            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
29278            "activity work must be settled"
29279        );
29280        assert!(
29281            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
29282            "query work must be settled"
29283        );
29284    }
29285
29286    #[tokio::test]
29287    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
29288        let server = MockWorkerServer::heartbeat_retry_worker();
29289        let client = Client::builder(server.base_url())
29290            .timeout(Duration::from_secs(2))
29291            .build()
29292            .expect("client");
29293        let observations = Arc::new(Mutex::new(Vec::new()));
29294        let observed = Arc::clone(&observations);
29295        let worker = Worker::new(client, "rust-workers")
29296            .worker_id("heartbeat-retry-worker")
29297            .retry_policy(WorkerRetryPolicy {
29298                max_retries: 1,
29299                initial_backoff: Duration::from_millis(300),
29300                max_backoff: Duration::from_millis(300),
29301            })
29302            .on_worker_heartbeat(move |observation| {
29303                observed
29304                    .lock()
29305                    .expect("heartbeat observations")
29306                    .push(observation.clone());
29307            });
29308
29309        worker
29310            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
29311            .await
29312            .expect("retryable heartbeat failure must remain bounded and recover");
29313
29314        let observations = observations.lock().expect("heartbeat observations");
29315        assert!(observations.len() >= 3, "heartbeat retry must recover");
29316        assert!(
29317            observations.windows(2).all(|pair| {
29318                pair[1]
29319                    .acknowledged_at_unix_millis
29320                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
29321                    >= 850
29322            }),
29323            "a successful retry must start a fresh advertised cadence: {observations:?}"
29324        );
29325        assert_eq!(
29326            server.request_count("/api/worker/heartbeat"),
29327            observations.len() + 1,
29328            "one retryable failure must add exactly one bounded request"
29329        );
29330    }
29331
29332    #[tokio::test]
29333    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
29334        let server = MockWorkerServer::waiting_query_worker();
29335        let client = Client::builder(server.base_url())
29336            .timeout(Duration::from_secs(2))
29337            .build()
29338            .expect("client");
29339        let observations = Arc::new(Mutex::new(Vec::new()));
29340        let observed = Arc::clone(&observations);
29341        let mut worker = Worker::new(client, "rust-snapshot-workers")
29342            .worker_id("rust-snapshot-worker")
29343            .poll_timeout(Duration::from_millis(10))
29344            .on_worker_heartbeat(move |observation| {
29345                observed
29346                    .lock()
29347                    .expect("heartbeat observations")
29348                    .push(observation.clone());
29349            });
29350
29351        worker.register_workflow("snapshot", |ctx, _input| async move {
29352            ctx.wait_signal("finish").await?;
29353            Ok(json!({"status": "finished"}))
29354        });
29355        worker.register_query("snapshot", "current", |ctx, _args| async move {
29356            let current = ctx
29357                .signals("increment")
29358                .iter()
29359                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
29360                .sum::<i64>();
29361            Ok(json!(current))
29362        });
29363        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
29364        worker
29365            .declare_workflow_signals("snapshot", &["finish"])
29366            .expect("declare finish signal");
29367
29368        worker
29369            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
29370            .await
29371            .expect("pending workflow and query poller must remain live until shutdown");
29372
29373        assert!(
29374            observations.lock().expect("heartbeat observations").len() >= 4,
29375            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
29376        );
29377        assert!(
29378            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
29379            "workflow polling must continue after empty replay acknowledgements"
29380        );
29381        assert!(
29382            server.request_count("/api/worker/query-tasks/poll") >= 2,
29383            "query polling must continue after serving the current query"
29384        );
29385        assert_eq!(
29386            server.request_body("/api/worker/register")["capabilities"],
29387            json!([
29388                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
29389                "workflow_entry_arguments_validation",
29390                DURABLE_SELECTION_CAPABILITY,
29391                MEMO_UPSERTS_CAPABILITY,
29392                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
29393                QUERY_TASKS_CAPABILITY,
29394                WORKFLOW_UPDATES_CAPABILITY,
29395                MESSAGE_STREAMS_CAPABILITY
29396            ])
29397        );
29398        assert_eq!(
29399            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
29400            json!({
29401                "queries": ["current"],
29402                "query_contracts": [{
29403                    "name": "current",
29404                    "parameters": [{
29405                        "name": "args", "position": 0, "required": false,
29406                        "variadic": true, "type": null, "allows_null": true,
29407                        "default_available": false, "default": null,
29408                    }],
29409                }],
29410                "signals": ["finish"],
29411                "signal_contracts": [{
29412                    "name": "finish",
29413                    "parameters": [{
29414                        "name": "args", "position": 0, "required": false,
29415                        "variadic": true, "type": null, "allows_null": true,
29416                        "default_available": false, "default": null,
29417                    }],
29418                }],
29419                "updates": ["replace"],
29420                "update_contracts": [{
29421                    "name": "replace",
29422                    "parameters": [{
29423                        "name": "args", "position": 0, "required": false,
29424                        "variadic": true, "type": null, "allows_null": true,
29425                        "default_available": false, "default": null,
29426                    }],
29427                }],
29428                "update_validators": [],
29429            })
29430        );
29431
29432        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
29433        assert_eq!(
29434            opened["commands"],
29435            json!([{
29436                "type": "open_signal_wait",
29437                "signal_name": "finish",
29438            }])
29439        );
29440
29441        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
29442            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
29443            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
29444            let failure = server.request_body(&fail_path);
29445            assert_eq!(
29446                failure["failure"]["type"],
29447                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
29448            );
29449            assert_eq!(server.request_count(&completion_path), 0);
29450        }
29451
29452        let query_completion =
29453            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
29454        assert_eq!(query_completion["result"], json!(8));
29455
29456        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
29457        assert_eq!(
29458            server.request_count(terminal_path),
29459            1,
29460            "the matching signal must settle the workflow exactly once"
29461        );
29462        let terminal = server.request_body(terminal_path);
29463        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
29464        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
29465        assert_eq!(
29466            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
29467                .expect("terminal workflow result"),
29468            json!({"status": "finished"})
29469        );
29470    }
29471
29472    #[tokio::test]
29473    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
29474        let server = MockWorkerServer::transient_worker_failures();
29475        let client = Client::builder(server.base_url())
29476            .timeout(Duration::from_secs(2))
29477            .build()
29478            .expect("client");
29479        let mut worker = Worker::new(client, "rust-workers")
29480            .worker_id("retry-worker")
29481            .poll_timeout(Duration::from_millis(10))
29482            .retry_policy(WorkerRetryPolicy {
29483                max_retries: 2,
29484                initial_backoff: Duration::from_millis(1),
29485                max_backoff: Duration::from_millis(1),
29486            });
29487        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29488        worker.register_activity(
29489            "counter.activity",
29490            |_ctx, _input| async move { Ok(Value::Null) },
29491        );
29492        worker.register_query(
29493            "counter",
29494            "current",
29495            |_ctx, _args| async move { Ok(json!(8)) },
29496        );
29497
29498        worker
29499            .run_until(tokio::time::sleep(Duration::from_millis(75)))
29500            .await
29501            .expect("transient failures must not stop the worker");
29502
29503        for path in [
29504            "/api/worker/heartbeat",
29505            "/api/worker/workflow-tasks/poll",
29506            "/api/worker/activity-tasks/poll",
29507            "/api/worker/query-tasks/poll",
29508        ] {
29509            assert!(
29510                server.request_count(path) >= 2,
29511                "{path} must continue after its transient failure"
29512            );
29513        }
29514    }
29515
29516    #[tokio::test]
29517    async fn worker_continues_after_long_poll_capacity_backpressure() {
29518        let server = MockWorkerServer::capacity_limited_activity_poll();
29519        let client = Client::builder(server.base_url())
29520            .timeout(Duration::from_secs(2))
29521            .build()
29522            .expect("client");
29523        let mut worker = Worker::new(client, "rust-workers")
29524            .worker_id("capacity-worker")
29525            .poll_timeout(Duration::from_millis(10))
29526            .retry_policy(WorkerRetryPolicy {
29527                max_retries: 0,
29528                initial_backoff: Duration::from_millis(1),
29529                max_backoff: Duration::from_millis(1),
29530            });
29531        worker.register_activity("capacity.activity", |_ctx, _input| async move {
29532            Ok(json!({"handled": true}))
29533        });
29534
29535        worker
29536            .run_until(tokio::time::sleep(Duration::from_millis(50)))
29537            .await
29538            .expect("capacity backpressure must not stop the worker");
29539
29540        assert!(
29541            server.request_count("/api/worker/activity-tasks/poll") >= 2,
29542            "the activity poller must continue after capacity backpressure"
29543        );
29544        assert_eq!(
29545            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
29546            1,
29547            "the worker must complete work returned after capacity recovers"
29548        );
29549    }
29550
29551    #[test]
29552    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
29553        let capacity = Error::Http {
29554            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
29555            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
29556        };
29557        assert_eq!(
29558            worker_poll_capacity_retry_after(&capacity),
29559            Some(Duration::from_secs(3))
29560        );
29561
29562        let rejected_capacity = Error::Http {
29563            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
29564            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
29565        };
29566        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
29567        assert!(!worker_operation_is_retryable(&rejected_capacity));
29568
29569        let ordinary_rate_limit = Error::Http {
29570            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
29571            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
29572                .to_string(),
29573        };
29574        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
29575        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
29576    }
29577
29578    #[tokio::test]
29579    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
29580        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29581            poll_failures_per_path: 8,
29582            heartbeat_failures: 8,
29583            ..MockWorkerBehavior::default()
29584        });
29585        let client = Client::builder(server.base_url())
29586            .timeout(Duration::from_secs(2))
29587            .build()
29588            .expect("client");
29589        let acknowledgements = Arc::new(AtomicUsize::new(0));
29590        let observed = Arc::clone(&acknowledgements);
29591        let mut worker = Worker::new(client, "rust-workers")
29592            .recover_transient_outages(true)
29593            .poll_timeout(Duration::from_millis(10))
29594            .retry_policy(WorkerRetryPolicy {
29595                max_retries: 2,
29596                initial_backoff: Duration::from_millis(2),
29597                max_backoff: Duration::from_millis(5),
29598            })
29599            .on_worker_heartbeat(move |_| {
29600                observed.fetch_add(1, Ordering::SeqCst);
29601            });
29602        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29603        worker.register_activity(
29604            "counter.activity",
29605            |_ctx, _input| async move { Ok(Value::Null) },
29606        );
29607        worker.register_query("counter", "current", |_ctx, _args| async move {
29608            Ok(Value::Null)
29609        });
29610
29611        worker
29612            .run_until(tokio::time::sleep(Duration::from_millis(500)))
29613            .await
29614            .expect("a recoverable outage must not stop the service worker");
29615
29616        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
29617        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
29618        for path in [
29619            "/api/worker/workflow-tasks/poll",
29620            "/api/worker/activity-tasks/poll",
29621            "/api/worker/query-tasks/poll",
29622        ] {
29623            let bodies = server.request_bodies(path);
29624            assert!(bodies.len() >= 10, "{path} must resume after recovery");
29625            let first = &bodies[0]["poll_request_id"];
29626            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
29627            for body in &bodies[..9] {
29628                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
29629            }
29630            assert_ne!(&bodies[9]["poll_request_id"], first);
29631            let times = server.request_times(path);
29632            for pair in times[..9].windows(2) {
29633                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
29634            }
29635        }
29636    }
29637
29638    #[tokio::test]
29639    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
29640        for heartbeat_outage in [false, true] {
29641            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29642                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
29643                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
29644                ..MockWorkerBehavior::default()
29645            });
29646            let client = Client::builder(server.base_url()).build().expect("client");
29647            let mut worker = Worker::new(client, "rust-workers")
29648                .recover_transient_outages(true)
29649                .retry_policy(WorkerRetryPolicy {
29650                    max_retries: 1,
29651                    initial_backoff: Duration::from_secs(5),
29652                    max_backoff: Duration::from_secs(5),
29653                });
29654            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29655            let started = Instant::now();
29656            worker
29657                .run_until(tokio::time::sleep(Duration::from_millis(200)))
29658                .await
29659                .expect("shutdown during an outage is a normal stop");
29660            assert!(started.elapsed() < Duration::from_secs(1));
29661            let path = if heartbeat_outage {
29662                "/api/worker/heartbeat"
29663            } else {
29664                "/api/worker/workflow-tasks/poll"
29665            };
29666            assert_eq!(server.request_count(path), 1);
29667            assert_eq!(
29668                server.request_count("/api/worker/registrations/mock-worker"),
29669                1
29670            );
29671        }
29672    }
29673
29674    #[tokio::test]
29675    async fn worker_outage_recovery_keeps_run_once_bounded() {
29676        let server = MockWorkerServer::unavailable_polls();
29677        let client = Client::builder(server.base_url()).build().expect("client");
29678        let mut worker = Worker::new(client, "rust-workers")
29679            .recover_transient_outages(true)
29680            .retry_policy(WorkerRetryPolicy {
29681                max_retries: 2,
29682                initial_backoff: Duration::from_millis(1),
29683                max_backoff: Duration::from_millis(1),
29684            });
29685        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29686        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
29687        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
29688    }
29689
29690    #[tokio::test]
29691    async fn worker_outage_recovery_respects_disabled_retries() {
29692        let server = MockWorkerServer::unavailable_polls();
29693        let client = Client::builder(server.base_url()).build().expect("client");
29694        let mut worker = Worker::new(client, "rust-workers")
29695            .recover_transient_outages(true)
29696            .retry_policy(WorkerRetryPolicy {
29697                max_retries: 0,
29698                ..WorkerRetryPolicy::default()
29699            });
29700        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29701        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
29702        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29703    }
29704
29705    #[tokio::test]
29706    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
29707        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29708            heartbeat_failures: usize::MAX,
29709            unauthorized_polls: true,
29710            ..MockWorkerBehavior::default()
29711        });
29712        let client = Client::builder(server.base_url()).build().expect("client");
29713        let mut worker = Worker::new(client, "rust-workers")
29714            .recover_transient_outages(true)
29715            .retry_policy(WorkerRetryPolicy {
29716                max_retries: 1,
29717                initial_backoff: Duration::from_secs(5),
29718                max_backoff: Duration::from_secs(5),
29719            });
29720        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29721        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
29722            .await
29723            .expect("fatal poll errors must interrupt heartbeat recovery")
29724            .expect_err("authentication failure is terminal");
29725        assert!(
29726            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
29727        );
29728        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29729    }
29730
29731    #[tokio::test]
29732    async fn worker_bounds_transport_retries() {
29733        let server = MockWorkerServer::unavailable_polls();
29734        let client = Client::builder(server.base_url())
29735            .timeout(Duration::from_secs(2))
29736            .build()
29737            .expect("client");
29738        let mut worker = Worker::new(client, "rust-workers")
29739            .worker_id("bounded-retry-worker")
29740            .poll_timeout(Duration::from_millis(10))
29741            .retry_policy(WorkerRetryPolicy {
29742                max_retries: 2,
29743                initial_backoff: Duration::from_millis(1),
29744                max_backoff: Duration::from_millis(1),
29745            });
29746        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29747
29748        let error = worker.run().await.expect_err("retry bound must terminate");
29749        assert!(matches!(error, Error::Transport(_)));
29750        assert_eq!(
29751            server.request_count("/api/worker/workflow-tasks/poll"),
29752            3,
29753            "one initial request plus exactly two retries"
29754        );
29755    }
29756
29757    #[tokio::test]
29758    async fn worker_retry_policy_can_disable_poll_retries() {
29759        let server = MockWorkerServer::unavailable_polls();
29760        let client = Client::builder(server.base_url())
29761            .timeout(Duration::from_secs(2))
29762            .build()
29763            .expect("client");
29764        let mut worker = Worker::new(client, "rust-workers")
29765            .worker_id("no-retry-worker")
29766            .poll_timeout(Duration::from_millis(10))
29767            .retry_policy(WorkerRetryPolicy {
29768                max_retries: 0,
29769                initial_backoff: Duration::from_millis(1),
29770                max_backoff: Duration::from_millis(1),
29771            });
29772        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29773
29774        let error = worker
29775            .run_once()
29776            .await
29777            .expect_err("disabled retries must return the first transport failure");
29778        assert!(matches!(error, Error::Transport(_)));
29779        assert_eq!(
29780            server.request_count("/api/worker/workflow-tasks/poll"),
29781            1,
29782            "max_retries=0 must send only the initial request"
29783        );
29784    }
29785
29786    #[tokio::test]
29787    async fn worker_does_not_retry_authentication_failures() {
29788        let server = MockWorkerServer::unauthorized_polls();
29789        let client = Client::builder(server.base_url())
29790            .timeout(Duration::from_secs(2))
29791            .build()
29792            .expect("client");
29793        let mut worker = Worker::new(client, "rust-workers")
29794            .worker_id("unauthorized-worker")
29795            .recover_transient_outages(true)
29796            .poll_timeout(Duration::from_millis(10));
29797        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29798
29799        let error = worker
29800            .run()
29801            .await
29802            .expect_err("authentication must terminate");
29803        let Error::Http { status, body } = error else {
29804            panic!("expected stable HTTP authentication error");
29805        };
29806        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
29807        assert!(body.contains("authentication_failed"));
29808        assert_eq!(
29809            server.request_count("/api/worker/workflow-tasks/poll"),
29810            1,
29811            "authentication failures must not be retried"
29812        );
29813    }
29814
29815    #[test]
29816    fn duplicate_registration_keeps_the_original_workflow() {
29817        let client = Client::new("http://127.0.0.1:9").expect("client");
29818        let mut worker = Worker::new(client, "registration-tests");
29819        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29820        let original = Arc::clone(&worker.workflows["same"].execute);
29821        worker
29822            .set_workflow_definition_sources("same", &["first workflow source"])
29823            .expect("source identity");
29824        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
29825        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
29826        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
29827        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
29828    }
29829
29830    #[test]
29831    fn duplicate_registration_keeps_the_original_activity() {
29832        let client = Client::new("http://127.0.0.1:9").expect("client");
29833        let mut worker = Worker::new(client, "registration-tests");
29834        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
29835        let original = Arc::clone(&worker.activities["same"]);
29836        worker.register_activity_avro_value("same", |_ctx, _input| async {
29837            Ok(AvroValue::String("second".into()))
29838        });
29839        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
29840    }
29841
29842    #[test]
29843    fn duplicate_registration_keeps_original_query_and_update_handlers() {
29844        let client = Client::new("http://127.0.0.1:9").expect("client");
29845        let mut worker = Worker::new(client, "registration-tests");
29846        worker.register_query("orders", "same", |_ctx, _input| async {
29847            Ok(json!("first"))
29848        });
29849        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
29850            panic!("snapshot query");
29851        };
29852        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
29853            Ok(json!("second"))
29854        });
29855        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
29856            panic!("duplicate replaced the query adapter");
29857        };
29858        assert!(Arc::ptr_eq(&original, retained));
29859        worker.register_update("orders", "same", |_ctx, _input| async {
29860            Ok(json!("first"))
29861        });
29862        let original = Arc::clone(&worker.updates["orders"]["same"]);
29863        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
29864            Ok(AvroValue::Null)
29865        });
29866        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
29867    }
29868
29869    #[tokio::test]
29870    async fn duplicate_registration_fails_before_server_contact() {
29871        let server = MockWorkerServer::start();
29872        let client = Client::builder(server.base_url()).build().expect("client");
29873        let mut worker =
29874            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
29875        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29876        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
29877        let error = worker
29878            .run_once()
29879            .await
29880            .expect_err("ambiguous worker must not poll");
29881        assert!(
29882            error.to_string().contains("duplicate_registration"),
29883            "{error}"
29884        );
29885        assert!(server.requests.lock().expect("requests").is_empty());
29886    }
29887
29888    #[derive(Clone, Debug)]
29889    struct CapturedRequest {
29890        headers: String,
29891        method: String,
29892        path: String,
29893        authorization: Option<String>,
29894        namespace: Option<String>,
29895        worker_protocol: Option<String>,
29896        control_protocol: Option<String>,
29897        body: String,
29898        received_at: Instant,
29899    }
29900
29901    struct MockWorkerServer {
29902        addr: SocketAddr,
29903        stop: Arc<AtomicBool>,
29904        requests: Arc<Mutex<Vec<CapturedRequest>>>,
29905        thread: Option<thread::JoinHandle<()>>,
29906    }
29907
29908    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
29909
29910    #[derive(Clone, Copy, Default)]
29911    struct MockWorkerBehavior {
29912        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
29913        request_override: Option<RequestOverride>,
29914        storage_refusals: usize,
29915        storage_path: Option<&'static str>,
29916        storage_unavailable: bool,
29917        storage_mid_poll: bool,
29918        storage_activity: bool,
29919        storage_query: bool,
29920        storage_wrong_poll_id: bool,
29921        reject_query_protocol: bool,
29922        reject_query_completion: bool,
29923        waiting_query_worker: bool,
29924        decline_registration: bool,
29925        complete_named_signal: bool,
29926        poll_failures_per_path: usize,
29927        long_poll_capacity_responses_per_path: usize,
29928        heartbeat_failures: usize,
29929        heartbeat_failure_request: Option<usize>,
29930        delayed_heartbeat_request: Option<usize>,
29931        heartbeat_response_delay: Duration,
29932        concurrent_requests: bool,
29933        unauthorized_polls: bool,
29934        reject_registration: bool,
29935        reject_registration_protocol: bool,
29936        reject_deregistration: bool,
29937        reject_deregistration_protocol: bool,
29938        cancelled_activity: bool,
29939        draining_polls: bool,
29940        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
29941        workflow_completion_status: Option<&'static str>,
29942        workflow_completion_body: Option<&'static str>,
29943    }
29944
29945    impl MockWorkerServer {
29946        fn start() -> Self {
29947            Self::start_with_behavior(MockWorkerBehavior::default())
29948        }
29949
29950        fn reject_query_protocol() -> Self {
29951            Self::start_with_behavior(MockWorkerBehavior {
29952                reject_query_protocol: true,
29953                ..MockWorkerBehavior::default()
29954            })
29955        }
29956
29957        fn reject_query_completion() -> Self {
29958            Self::start_with_behavior(MockWorkerBehavior {
29959                reject_query_completion: true,
29960                ..MockWorkerBehavior::default()
29961            })
29962        }
29963
29964        fn waiting_query_worker() -> Self {
29965            Self::start_with_behavior(MockWorkerBehavior {
29966                waiting_query_worker: true,
29967                complete_named_signal: true,
29968                ..MockWorkerBehavior::default()
29969            })
29970        }
29971
29972        fn transient_worker_failures() -> Self {
29973            Self::start_with_behavior(MockWorkerBehavior {
29974                poll_failures_per_path: 1,
29975                heartbeat_failures: 1,
29976                ..MockWorkerBehavior::default()
29977            })
29978        }
29979
29980        fn consecutive_poll_failures(count: usize) -> Self {
29981            Self::start_with_behavior(MockWorkerBehavior {
29982                poll_failures_per_path: count,
29983                ..MockWorkerBehavior::default()
29984            })
29985        }
29986
29987        fn capacity_limited_activity_poll() -> Self {
29988            Self::start_with_behavior(MockWorkerBehavior {
29989                long_poll_capacity_responses_per_path: 1,
29990                ..MockWorkerBehavior::default()
29991            })
29992        }
29993
29994        fn delayed_heartbeat_worker() -> Self {
29995            Self::start_with_behavior(MockWorkerBehavior {
29996                waiting_query_worker: true,
29997                delayed_heartbeat_request: Some(2),
29998                heartbeat_response_delay: Duration::from_millis(1_500),
29999                concurrent_requests: true,
30000                cancelled_activity: true,
30001                ..MockWorkerBehavior::default()
30002            })
30003        }
30004
30005        fn heartbeat_retry_worker() -> Self {
30006            Self::start_with_behavior(MockWorkerBehavior {
30007                waiting_query_worker: true,
30008                heartbeat_failure_request: Some(2),
30009                concurrent_requests: true,
30010                ..MockWorkerBehavior::default()
30011            })
30012        }
30013
30014        fn unavailable_polls() -> Self {
30015            Self::start_with_behavior(MockWorkerBehavior {
30016                poll_failures_per_path: usize::MAX,
30017                ..MockWorkerBehavior::default()
30018            })
30019        }
30020
30021        fn unauthorized_polls() -> Self {
30022            Self::start_with_behavior(MockWorkerBehavior {
30023                unauthorized_polls: true,
30024                ..MockWorkerBehavior::default()
30025            })
30026        }
30027
30028        fn rejected_registration() -> Self {
30029            Self::start_with_behavior(MockWorkerBehavior {
30030                reject_registration: true,
30031                ..MockWorkerBehavior::default()
30032            })
30033        }
30034
30035        fn rejected_registration_protocol() -> Self {
30036            Self::start_with_behavior(MockWorkerBehavior {
30037                reject_registration_protocol: true,
30038                ..MockWorkerBehavior::default()
30039            })
30040        }
30041
30042        fn declined_registration() -> Self {
30043            Self::start_with_behavior(MockWorkerBehavior {
30044                decline_registration: true,
30045                ..MockWorkerBehavior::default()
30046            })
30047        }
30048
30049        fn rejected_deregistration() -> Self {
30050            Self::start_with_behavior(MockWorkerBehavior {
30051                reject_deregistration: true,
30052                ..MockWorkerBehavior::default()
30053            })
30054        }
30055
30056        fn rejected_deregistration_protocol() -> Self {
30057            Self::start_with_behavior(MockWorkerBehavior {
30058                reject_deregistration_protocol: true,
30059                ..MockWorkerBehavior::default()
30060            })
30061        }
30062
30063        fn unauthorized_polls_and_rejected_deregistration() -> Self {
30064            Self::start_with_behavior(MockWorkerBehavior {
30065                unauthorized_polls: true,
30066                reject_deregistration: true,
30067                ..MockWorkerBehavior::default()
30068            })
30069        }
30070
30071        fn cancelled_activity() -> Self {
30072            Self::start_with_behavior(MockWorkerBehavior {
30073                cancelled_activity: true,
30074                ..MockWorkerBehavior::default()
30075            })
30076        }
30077
30078        fn draining_polls() -> Self {
30079            Self::start_with_behavior(MockWorkerBehavior {
30080                draining_polls: true,
30081                ..MockWorkerBehavior::default()
30082            })
30083        }
30084
30085        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
30086            Self::start_with_behavior(MockWorkerBehavior {
30087                invalid_task_payload_codec: Some(codec),
30088                ..MockWorkerBehavior::default()
30089            })
30090        }
30091
30092        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
30093            Self::start_with_behavior(MockWorkerBehavior {
30094                workflow_completion_status: Some(status),
30095                workflow_completion_body: Some(body),
30096                ..MockWorkerBehavior::default()
30097            })
30098        }
30099
30100        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
30101            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
30102            listener
30103                .set_nonblocking(true)
30104                .expect("configure mock listener");
30105            let addr = listener.local_addr().expect("mock server address");
30106            let stop = Arc::new(AtomicBool::new(false));
30107            let server_stop = Arc::clone(&stop);
30108            let requests = Arc::new(Mutex::new(Vec::new()));
30109            let server_requests = Arc::clone(&requests);
30110            let thread = thread::spawn(move || {
30111                let mut request_threads = Vec::new();
30112                while !server_stop.load(Ordering::SeqCst) {
30113                    match listener.accept() {
30114                        Ok((mut stream, _)) => {
30115                            if behavior.concurrent_requests {
30116                                let requests = Arc::clone(&server_requests);
30117                                request_threads.push(thread::spawn(move || {
30118                                    handle_mock_worker_request(&mut stream, &requests, behavior)
30119                                }));
30120                            } else {
30121                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
30122                            }
30123                        }
30124                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
30125                            let mut index = 0;
30126                            while index < request_threads.len() {
30127                                if request_threads[index].is_finished() {
30128                                    request_threads
30129                                        .swap_remove(index)
30130                                        .join()
30131                                        .expect("join mock request");
30132                                } else {
30133                                    index += 1;
30134                                }
30135                            }
30136                            thread::sleep(Duration::from_millis(5));
30137                        }
30138                        Err(_) => break,
30139                    }
30140                }
30141                for request_thread in request_threads {
30142                    request_thread.join().expect("join mock request");
30143                }
30144            });
30145
30146            Self {
30147                addr,
30148                stop,
30149                requests,
30150                thread: Some(thread),
30151            }
30152        }
30153
30154        fn base_url(&self) -> String {
30155            format!("http://{}", self.addr)
30156        }
30157
30158        fn worker_protocol_for(&self, path: &str) -> Option<String> {
30159            self.requests
30160                .lock()
30161                .expect("captured requests")
30162                .iter()
30163                .find(|request| request.path == path)
30164                .and_then(|request| request.worker_protocol.clone())
30165        }
30166
30167        fn control_protocol_for(&self, path: &str) -> Option<String> {
30168            self.requests
30169                .lock()
30170                .expect("captured requests")
30171                .iter()
30172                .find(|request| request.path == path)
30173                .and_then(|request| request.control_protocol.clone())
30174        }
30175
30176        fn method_for(&self, path: &str) -> Option<String> {
30177            self.requests
30178                .lock()
30179                .expect("captured requests")
30180                .iter()
30181                .find(|request| request.path == path)
30182                .map(|request| request.method.clone())
30183        }
30184
30185        fn authorization_for(&self, path: &str) -> Option<String> {
30186            self.requests
30187                .lock()
30188                .expect("captured requests")
30189                .iter()
30190                .find(|request| request.path == path)
30191                .and_then(|request| request.authorization.clone())
30192        }
30193
30194        fn namespace_for(&self, path: &str) -> Option<String> {
30195            self.requests
30196                .lock()
30197                .expect("captured requests")
30198                .iter()
30199                .find(|request| request.path == path)
30200                .and_then(|request| request.namespace.clone())
30201        }
30202
30203        fn request_count(&self, path: &str) -> usize {
30204            self.requests
30205                .lock()
30206                .expect("captured requests")
30207                .iter()
30208                .filter(|request| request.path == path)
30209                .count()
30210        }
30211
30212        fn captured_paths(&self) -> Vec<String> {
30213            self.requests
30214                .lock()
30215                .expect("captured requests")
30216                .iter()
30217                .map(|request| request.path.clone())
30218                .collect()
30219        }
30220
30221        fn request_times(&self, path: &str) -> Vec<Instant> {
30222            self.requests
30223                .lock()
30224                .expect("captured requests")
30225                .iter()
30226                .filter(|request| request.path == path)
30227                .map(|request| request.received_at)
30228                .collect()
30229        }
30230
30231        fn request_body(&self, path: &str) -> Value {
30232            let requests = self.requests.lock().expect("captured requests");
30233            let body = &requests
30234                .iter()
30235                .find(|request| request.path == path)
30236                .unwrap_or_else(|| panic!("missing request for {path}"))
30237                .body;
30238            serde_json::from_str(body).unwrap_or_else(|error| {
30239                panic!("invalid JSON request body for {path}: {error}: {body:?}")
30240            })
30241        }
30242
30243        fn request_bodies(&self, path: &str) -> Vec<Value> {
30244            self.requests
30245                .lock()
30246                .expect("captured requests")
30247                .iter()
30248                .filter(|request| request.path == path)
30249                .map(|request| {
30250                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
30251                        panic!(
30252                            "invalid JSON request body for {path}: {error}: {:?}",
30253                            request.body
30254                        )
30255                    })
30256                })
30257                .collect()
30258        }
30259    }
30260
30261    impl Drop for MockWorkerServer {
30262        fn drop(&mut self) {
30263            self.stop.store(true, Ordering::SeqCst);
30264            let _ = TcpStream::connect(self.addr);
30265
30266            if let Some(thread) = self.thread.take() {
30267                thread.join().expect("join mock server");
30268            }
30269        }
30270    }
30271
30272    fn handle_mock_worker_request(
30273        stream: &mut TcpStream,
30274        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
30275        behavior: MockWorkerBehavior,
30276    ) {
30277        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
30278        let mut buffer = [0_u8; 8192];
30279        let mut request = Vec::new();
30280
30281        loop {
30282            match stream.read(&mut buffer) {
30283                Ok(0) => break,
30284                Ok(read) => {
30285                    request.extend_from_slice(&buffer[..read]);
30286                    if mock_request_is_complete(&request) {
30287                        break;
30288                    }
30289                }
30290                Err(error)
30291                    if matches!(
30292                        error.kind(),
30293                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
30294                    ) =>
30295                {
30296                    break;
30297                }
30298                Err(_) => return,
30299            }
30300        }
30301
30302        let request = String::from_utf8_lossy(&request);
30303        let body = request
30304            .split_once("\r\n\r\n")
30305            .map(|(_, body)| body)
30306            .unwrap_or_default();
30307        let path = request
30308            .lines()
30309            .next()
30310            .and_then(|line| line.split_whitespace().nth(1))
30311            .unwrap_or_default();
30312        let method = request
30313            .lines()
30314            .next()
30315            .and_then(|line| line.split_whitespace().next())
30316            .unwrap_or_default();
30317        let authorization = request.lines().find_map(|line| {
30318            let (name, value) = line.split_once(':')?;
30319            name.eq_ignore_ascii_case("Authorization")
30320                .then(|| value.trim().to_string())
30321        });
30322        let namespace = request.lines().find_map(|line| {
30323            let (name, value) = line.split_once(':')?;
30324            name.eq_ignore_ascii_case("X-Namespace")
30325                .then(|| value.trim().to_string())
30326        });
30327        let worker_protocol = request.lines().find_map(|line| {
30328            let (name, value) = line.split_once(':')?;
30329            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
30330                .then(|| value.trim().to_string())
30331        });
30332        let control_protocol = request.lines().find_map(|line| {
30333            let (name, value) = line.split_once(':')?;
30334            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
30335                .then(|| value.trim().to_string())
30336        });
30337        let request_number = {
30338            let mut requests = requests.lock().expect("captured requests");
30339            requests.push(CapturedRequest {
30340                headers: request
30341                    .split_once("\r\n\r\n")
30342                    .map_or("", |(headers, _)| headers)
30343                    .to_owned(),
30344                method: method.to_string(),
30345                path: path.to_string(),
30346                authorization,
30347                namespace,
30348                worker_protocol: worker_protocol.clone(),
30349                control_protocol,
30350                body: body.to_string(),
30351                received_at: Instant::now(),
30352            });
30353            requests
30354                .iter()
30355                .filter(|request| request.path == path)
30356                .count()
30357        };
30358
30359        if let Some(response) = behavior
30360            .request_override
30361            .and_then(|handler| handler(path, body, request_number))
30362        {
30363            write_mock_response(stream, response.0, &response.1);
30364            return;
30365        }
30366        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
30367            write_mock_response(stream, response.0, &response.1);
30368            return;
30369        }
30370        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
30371            return;
30372        }
30373        let pressure_path = behavior
30374            .storage_path
30375            .is_some_and(|part| path.contains(part));
30376        let prior_failures = if path.ends_with("/poll") {
30377            behavior.poll_failures_per_path
30378        } else {
30379            0
30380        };
30381        if pressure_path
30382            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
30383        {
30384            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
30385            let poll_id = path
30386                .ends_with("/poll")
30387                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
30388            let mut refusal = storage_refusal(
30389                poll_id,
30390                behavior.storage_unavailable,
30391                behavior.storage_mid_poll,
30392            );
30393            if behavior.storage_wrong_poll_id {
30394                refusal["poll_request_id"] = json!("wrong-poll");
30395            }
30396            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
30397            return;
30398        }
30399        if path.contains("/storage-task/")
30400            || path.contains("/storage-activity/")
30401            || path.contains("/storage-query/")
30402        {
30403            write_mock_response(stream, "200 OK", "{}");
30404            return;
30405        }
30406        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
30407            write_mock_response(stream, "200 OK", &json!({"task":{
30408                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
30409                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
30410                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
30411                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
30412                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
30413            }}).to_string());
30414            return;
30415        }
30416        if behavior.storage_activity
30417            && path == "/api/worker/activity-tasks/poll"
30418            && request_number == 1
30419        {
30420            write_mock_response(stream, "200 OK", &json!({"task":{
30421                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
30422                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
30423                "attempt_number":7, "lease_owner":"storage-worker"
30424            }}).to_string());
30425            return;
30426        }
30427
30428        if path == "/api/worker/register" {
30429            if behavior.reject_registration_protocol {
30430                write_mock_response(
30431                    stream,
30432                    "400 Bad Request",
30433                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
30434                );
30435                return;
30436            }
30437            if behavior.reject_registration {
30438                write_mock_response(
30439                    stream,
30440                    "503 Service Unavailable",
30441                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
30442                );
30443                return;
30444            }
30445        }
30446
30447        if path.starts_with("/api/worker/registrations/") {
30448            if behavior.reject_deregistration_protocol {
30449                write_mock_response(
30450                    stream,
30451                    "400 Bad Request",
30452                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
30453                );
30454            } else if behavior.reject_deregistration {
30455                write_mock_response(
30456                    stream,
30457                    "403 Forbidden",
30458                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
30459                );
30460            } else {
30461                write_mock_response(
30462                    stream,
30463                    "200 OK",
30464                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
30465                );
30466            }
30467            return;
30468        }
30469
30470        let is_poll = matches!(
30471            path,
30472            "/api/worker/workflow-tasks/poll"
30473                | "/api/worker/activity-tasks/poll"
30474                | "/api/worker/query-tasks/poll"
30475        );
30476        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
30477            write_mock_response(
30478                stream,
30479                "429 Too Many Requests",
30480                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
30481            );
30482            return;
30483        }
30484        if is_poll && request_number <= behavior.poll_failures_per_path {
30485            return;
30486        }
30487        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
30488            return;
30489        }
30490        if path == "/api/worker/heartbeat"
30491            && behavior.heartbeat_failure_request == Some(request_number)
30492        {
30493            return;
30494        }
30495        if path == "/api/worker/heartbeat"
30496            && behavior.delayed_heartbeat_request == Some(request_number)
30497        {
30498            thread::sleep(behavior.heartbeat_response_delay);
30499        }
30500        if behavior.unauthorized_polls && is_poll {
30501            write_mock_response(
30502                stream,
30503                "401 Unauthorized",
30504                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
30505            );
30506            return;
30507        }
30508        if behavior.draining_polls && is_poll {
30509            write_mock_response(
30510                stream,
30511                "409 Conflict",
30512                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
30513            );
30514            return;
30515        }
30516
30517        if let Some(codec_case) = behavior.invalid_task_payload_codec {
30518            if is_poll && request_number == 1 {
30519                let mut task = match path {
30520                    "/api/worker/workflow-tasks/poll" => json!({
30521                        "task_id": "codec-workflow",
30522                        "workflow_type": "codec.workflow",
30523                        "payload_codec": DEFAULT_CODEC,
30524                        "workflow_task_attempt": 1,
30525                        "lease_owner": "codec-worker"
30526                    }),
30527                    "/api/worker/activity-tasks/poll" => json!({
30528                        "task_id": "codec-activity",
30529                        "activity_attempt_id": "codec-activity-attempt",
30530                        "activity_type": "codec.activity",
30531                        "payload_codec": DEFAULT_CODEC,
30532                        "attempt_number": 1,
30533                        "lease_owner": "codec-worker"
30534                    }),
30535                    "/api/worker/query-tasks/poll" => json!({
30536                        "query_task_id": "codec-query",
30537                        "query_task_attempt": 1,
30538                        "workflow_type": "codec.workflow",
30539                        "query_name": "known",
30540                        "payload_codec": DEFAULT_CODEC,
30541                        "lease_owner": "codec-worker"
30542                    }),
30543                    _ => unreachable!("is_poll limits task codec probe paths"),
30544                };
30545                codec_case.apply(&mut task);
30546                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
30547                return;
30548            }
30549
30550            if matches!(
30551                path,
30552                "/api/worker/workflow-tasks/codec-workflow/fail"
30553                    | "/api/worker/activity-tasks/codec-activity/fail"
30554                    | "/api/worker/query-tasks/codec-query/fail"
30555            ) {
30556                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
30557                return;
30558            }
30559        }
30560
30561        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
30562            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
30563            let body = format!(
30564                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
30565            );
30566            write_mock_response(stream, "400 Bad Request", &body);
30567            return;
30568        }
30569
30570        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
30571        {
30572            write_mock_response(
30573                stream,
30574                "409 Conflict",
30575                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
30576            );
30577            return;
30578        }
30579
30580        if behavior.workflow_completion_status.is_some()
30581            && path == "/api/worker/workflow-tasks/poll"
30582            && request_number == 1
30583        {
30584            write_mock_response(
30585                stream,
30586                "200 OK",
30587                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"}}"#,
30588            );
30589            return;
30590        }
30591
30592        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
30593            if let (Some(status), Some(body)) = (
30594                behavior.workflow_completion_status,
30595                behavior.workflow_completion_body,
30596            ) {
30597                write_mock_response(stream, status, body);
30598                return;
30599            }
30600        }
30601
30602        if behavior.waiting_query_worker {
30603            if behavior.complete_named_signal
30604                && path == "/api/worker/workflow-tasks/poll"
30605                && request_number == 1
30606            {
30607                let body = json!({
30608                    "task": {
30609                        "task_id": "snapshot-open",
30610                        "workflow_id": "snapshot-1",
30611                        "run_id": "snapshot-run-1",
30612                        "workflow_type": "snapshot",
30613                        "payload_codec": DEFAULT_CODEC,
30614                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30615                            .expect("Avro workflow arguments"),
30616                        "history_events": [],
30617                        "workflow_task_attempt": 1,
30618                        "lease_owner": "rust-snapshot-worker"
30619                    }
30620                })
30621                .to_string();
30622                write_mock_response(stream, "200 OK", &body);
30623                return;
30624            }
30625
30626            let signal_request = request_number - usize::from(behavior.complete_named_signal);
30627            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
30628            if path == "/api/worker/workflow-tasks/poll"
30629                && signal_request >= 1
30630                && signal_request <= signal_request_limit
30631            {
30632                let finish = behavior.complete_named_signal && signal_request == 3;
30633                let amounts = if signal_request == 1 {
30634                    vec![3]
30635                } else {
30636                    vec![3, 5]
30637                };
30638                let task_id = if signal_request == 1 {
30639                    "snapshot-wait-3"
30640                } else if finish {
30641                    "snapshot-finish"
30642                } else {
30643                    "snapshot-wait-5"
30644                };
30645                let mut history_events = std::iter::once(json!({
30646                    "event_type": "SignalWaitOpened",
30647                    "payload": {"sequence": 1, "signal_name": "finish"}
30648                }))
30649                .chain(amounts.iter().enumerate().map(|(index, amount)| {
30650                    json!({
30651                        "event_type": "SignalReceived",
30652                        "payload": {
30653                            "signal_id": format!("increment-{amount}"),
30654                            "signal_name": "increment",
30655                            "workflow_sequence": index + 2,
30656                            "payload_codec": DEFAULT_CODEC,
30657                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30658                                .expect("Avro signal envelope")
30659                        }
30660                    })
30661                }))
30662                .collect::<Vec<_>>();
30663                let (resume_id, resume_name, resume_arguments) = if finish {
30664                    history_events.push(json!({
30665                        "event_type": "SignalReceived",
30666                        "payload": {
30667                            "signal_id": "finish",
30668                            "signal_name": "finish",
30669                            "workflow_sequence": 4,
30670                            "payload_codec": DEFAULT_CODEC,
30671                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30672                                .expect("Avro finish signal envelope")
30673                        }
30674                    }));
30675                    (
30676                        "finish".to_string(),
30677                        "finish".to_string(),
30678                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
30679                            .expect("Avro finish resume signal"),
30680                    )
30681                } else {
30682                    let amount = amounts.last().expect("amount");
30683                    (
30684                        format!("increment-{amount}"),
30685                        "increment".to_string(),
30686                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30687                            .expect("Avro increment resume signal"),
30688                    )
30689                };
30690                let body = json!({
30691                    "task": {
30692                        "task_id": task_id,
30693                        "workflow_id": "snapshot-1",
30694                        "run_id": "snapshot-run-1",
30695                        "workflow_type": "snapshot",
30696                        "payload_codec": DEFAULT_CODEC,
30697                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30698                            .expect("Avro workflow arguments"),
30699                        "history_events": history_events,
30700                        "workflow_task_attempt": 1,
30701                        "workflow_signal_id": resume_id,
30702                        "signal_name": resume_name,
30703                        "signal_arguments": resume_arguments,
30704                        "lease_owner": "rust-snapshot-worker"
30705                    }
30706                })
30707                .to_string();
30708                write_mock_response(stream, "200 OK", &body);
30709                return;
30710            }
30711
30712            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
30713                let history_events = [3, 5]
30714                    .into_iter()
30715                    .enumerate()
30716                    .map(|(index, amount)| {
30717                        json!({
30718                            "event_type": "SignalReceived",
30719                            "payload": {
30720                                "signal_id": format!("increment-{amount}"),
30721                                "signal_name": "increment",
30722                                "workflow_sequence": index + 2,
30723                                "payload_codec": DEFAULT_CODEC,
30724                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30725                                    .expect("Avro query signal envelope")
30726                            }
30727                        })
30728                    })
30729                    .collect::<Vec<_>>();
30730                let body = json!({
30731                    "task": {
30732                        "query_task_id": "snapshot-current",
30733                        "query_task_attempt": 1,
30734                        "lease_owner": "rust-snapshot-worker",
30735                        "workflow_id": "snapshot-1",
30736                        "run_id": "snapshot-run-1",
30737                        "workflow_type": "snapshot",
30738                        "query_name": "current",
30739                        "payload_codec": DEFAULT_CODEC,
30740                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30741                            .expect("Avro workflow arguments"),
30742                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30743                            .expect("Avro query arguments"),
30744                        "history_events": history_events,
30745                        "run_status": "waiting"
30746                    }
30747                })
30748                .to_string();
30749                write_mock_response(stream, "200 OK", &body);
30750                return;
30751            }
30752
30753            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
30754                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
30755            {
30756                write_mock_response(
30757                    stream,
30758                    "200 OK",
30759                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
30760                );
30761                return;
30762            }
30763
30764            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
30765                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
30766                return;
30767            }
30768
30769            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
30770                write_mock_response(
30771                    stream,
30772                    "200 OK",
30773                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
30774                );
30775                return;
30776            }
30777
30778            if path == "/api/worker/query-tasks/snapshot-current/complete" {
30779                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
30780                return;
30781            }
30782        }
30783
30784        if matches!(
30785            path,
30786            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
30787        ) {
30788            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30789                .expect("typed mock result");
30790            let body = json!({
30791                "result": typed_fidelity_probe().into_json().expect("result projection"),
30792                "result_envelope": result,
30793            })
30794            .to_string();
30795            write_mock_response(stream, "200 OK", &body);
30796            return;
30797        }
30798
30799        if path == "/api/workflows/typed-1" {
30800            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30801                .expect("typed mock result");
30802            let body = json!({
30803                "workflow_id": "typed-1",
30804                "run_id": "run-typed-1",
30805                "workflow_type": "typed.echo",
30806                "status": "completed",
30807                "output": typed_fidelity_probe().into_json().expect("output projection"),
30808                "output_envelope": result,
30809            })
30810            .to_string();
30811            write_mock_response(stream, "200 OK", &body);
30812            return;
30813        }
30814
30815        let (status, body) = match path {
30816            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
30817            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
30818            "/api/workflows" => (
30819                "201 Created",
30820                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
30821            ),
30822            "/api/worker/register" if behavior.decline_registration => (
30823                "200 OK",
30824                r#"{"worker_id":"declined-worker","registered":false}"#,
30825            ),
30826            "/api/worker/register" if behavior.waiting_query_worker => (
30827                "200 OK",
30828                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
30829            ),
30830            "/api/worker/register" => (
30831                "200 OK",
30832                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
30833            ),
30834            "/api/worker/heartbeat" => ("200 OK", "{}"),
30835            "/api/worker/activity-tasks/poll"
30836                if behavior.cancelled_activity && request_number == 1 =>
30837            {
30838                (
30839                    "200 OK",
30840                    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"}}"#,
30841                )
30842            }
30843            "/api/worker/activity-tasks/poll"
30844                if behavior.long_poll_capacity_responses_per_path > 0
30845                    && request_number
30846                        == behavior
30847                            .long_poll_capacity_responses_per_path
30848                            .saturating_add(1) =>
30849            {
30850                (
30851                    "200 OK",
30852                    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"}}"#,
30853                )
30854            }
30855            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
30856                ("200 OK", r#"{"task":null}"#)
30857            }
30858            "/api/worker/query-tasks/poll"
30859                if behavior.reject_query_completion && request_number == 1 =>
30860            {
30861                (
30862                    "200 OK",
30863                    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"}}"#,
30864                )
30865            }
30866            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
30867            "/api/worker/query-tasks/query-capture/complete"
30868            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
30869            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
30870                "200 OK",
30871                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
30872            ),
30873            "/api/worker/activity-tasks/activity-cancel/complete" => (
30874                "409 Conflict",
30875                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
30876            ),
30877            "/api/worker/activity-tasks/activity-typed/complete"
30878            | "/api/worker/activity-tasks/activity-typed/fail"
30879            | "/api/worker/activity-tasks/capacity-activity/complete"
30880            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
30881            "/api/workflows/counter-1/query/current" => (
30882                "200 OK",
30883                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
30884            ),
30885            "/api/workflows/counter-1/query/missing" => (
30886                "404 Not Found",
30887                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
30888            ),
30889            "/api/workflows/wf-lifecycle/cancel" => (
30890                "200 OK",
30891                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
30892            ),
30893            "/api/workflows/wf-lifecycle/terminate" => (
30894                "200 OK",
30895                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
30896            ),
30897            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
30898                "200 OK",
30899                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
30900            ),
30901            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
30902                "200 OK",
30903                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
30904            ),
30905            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
30906                "202 Accepted",
30907                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
30908            ),
30909            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
30910                "200 OK",
30911                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}"#,
30912            ),
30913            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
30914                "409 Conflict",
30915                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
30916            ),
30917            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
30918            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
30919                "409 Conflict",
30920                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
30921            ),
30922            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
30923                "200 OK",
30924                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"}]}}"#,
30925            ),
30926            "/api/workflows/wf-cancelled" => (
30927                "200 OK",
30928                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
30929            ),
30930            "/api/workflows/wf-terminated" => (
30931                "200 OK",
30932                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
30933            ),
30934            "/api/workflows/wf-timed-out" => (
30935                "200 OK",
30936                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
30937            ),
30938            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
30939                "200 OK",
30940                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
30941            ),
30942            "/api/workflows/wf-selected" => (
30943                "200 OK",
30944                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
30945            ),
30946            "/api/workflows/wf-selected/runs/run-selected" => (
30947                "200 OK",
30948                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
30949            ),
30950            _ => ("404 Not Found", r#"{"message":"not found"}"#),
30951        };
30952        write_mock_response(stream, status, body);
30953    }
30954
30955    fn mock_request_is_complete(request: &[u8]) -> bool {
30956        let Some(header_end) = request
30957            .windows(4)
30958            .position(|window| window == b"\r\n\r\n")
30959            .map(|position| position + 4)
30960        else {
30961            return false;
30962        };
30963        let headers = String::from_utf8_lossy(&request[..header_end]);
30964        let content_length = headers.lines().find_map(|line| {
30965            let (name, value) = line.split_once(':')?;
30966            name.eq_ignore_ascii_case("content-length")
30967                .then(|| value.trim().parse::<usize>().ok())
30968                .flatten()
30969        });
30970
30971        request.len() >= header_end + content_length.unwrap_or(0)
30972    }
30973
30974    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
30975        let response = format!(
30976            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
30977            body.len()
30978        );
30979
30980        let _ = stream.write_all(response.as_bytes());
30981        let _ = stream.flush();
30982    }
30983
30984    fn activity_completion_backend_recovery(
30985        path: &str,
30986        _body: &str,
30987        request_number: usize,
30988    ) -> Option<(&'static str, String)> {
30989        match path {
30990            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
30991                "200 OK",
30992                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(),
30993            )),
30994            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
30995                "503 Service Unavailable",
30996                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(),
30997            )),
30998            "/api/worker/activity-tasks/recover-activity/complete" => Some((
30999                "200 OK",
31000                r#"{"outcome":"completed","recorded":true}"#.to_string(),
31001            )),
31002            _ => None,
31003        }
31004    }
31005
31006    fn workflow_completion_backend_recovery(
31007        path: &str,
31008        _body: &str,
31009        request_number: usize,
31010    ) -> Option<(&'static str, String)> {
31011        match path {
31012            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
31013                "200 OK",
31014                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
31015            )),
31016            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
31017                "503 Service Unavailable",
31018                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(),
31019            )),
31020            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
31021                "200 OK",
31022                r#"{"outcome":"completed","recorded":true}"#.to_string(),
31023            )),
31024            _ => None,
31025        }
31026    }
31027
31028    fn workflow_completion_lock_pressure(
31029        path: &str,
31030        body: &str,
31031        request_number: usize,
31032    ) -> Option<(&'static str, String)> {
31033        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
31034            return Some((
31035                "503 Service Unavailable",
31036                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
31037                    "outcome":"deferred", "recorded":false, "retryable":true,
31038                    "retry_after_seconds":1, "task_id":"recover-workflow",
31039                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
31040                    "backend":{"driver":"sqlite", "lock_pressure":true}})
31041                .to_string(),
31042            ));
31043        }
31044        workflow_completion_backend_recovery(path, body, request_number)
31045    }
31046
31047    fn workflow_completion_lock_pressure_forever(
31048        path: &str,
31049        body: &str,
31050        request_number: usize,
31051    ) -> Option<(&'static str, String)> {
31052        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
31053            return workflow_completion_lock_pressure(path, body, 1);
31054        }
31055        workflow_completion_lock_pressure(path, body, request_number)
31056    }
31057
31058    fn workflow_completion_lock_pressure_then_expired(
31059        path: &str,
31060        body: &str,
31061        request_number: usize,
31062    ) -> Option<(&'static str, String)> {
31063        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
31064            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
31065                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
31066        }
31067        workflow_completion_lock_pressure(path, body, request_number)
31068    }
31069
31070    fn workflow_completion_lock_pressure_then_slow(
31071        path: &str,
31072        body: &str,
31073        request_number: usize,
31074    ) -> Option<(&'static str, String)> {
31075        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
31076            thread::sleep(Duration::from_secs(2));
31077        }
31078        workflow_completion_lock_pressure(path, body, request_number)
31079    }
31080
31081    fn workflow_completion_pressure_then_backend_loss(
31082        path: &str,
31083        body: &str,
31084        request_number: usize,
31085    ) -> Option<(&'static str, String)> {
31086        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
31087            return Some((
31088                "503 Service Unavailable",
31089                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
31090                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
31091                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
31092                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
31093                .to_string(),
31094            ));
31095        }
31096        workflow_completion_lock_pressure(path, body, request_number)
31097    }
31098
31099    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
31100        let client = Client::builder(server.base_url())
31101            .timeout(Duration::from_secs(4))
31102            .build()
31103            .unwrap();
31104        let mut worker = Worker::new(client, "recover-queue")
31105            .worker_id("recover-worker")
31106            .poll_timeout(Duration::from_millis(10));
31107        worker.register_workflow("recover.workflow", move |_ctx, _args| {
31108            let calls = Arc::clone(&calls);
31109            async move {
31110                calls.fetch_add(1, Ordering::SeqCst);
31111                Ok(json!("done"))
31112            }
31113        });
31114        worker
31115    }
31116
31117    #[tokio::test]
31118    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
31119        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31120            request_override: Some(workflow_completion_lock_pressure_forever),
31121            ..MockWorkerBehavior::default()
31122        });
31123        let calls = Arc::new(AtomicUsize::new(0));
31124        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
31125            .with_storage_admission(Arc::new(AtomicBool::new(false)));
31126        worker
31127            .client
31128            .worker_storage_admission
31129            .as_mut()
31130            .unwrap()
31131            .workflow_completion_retry_deadline =
31132            Some(tokio::time::Instant::now() + Duration::from_millis(250));
31133        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
31134            .await
31135            .unwrap();
31136        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
31137        assert_eq!(calls.load(Ordering::SeqCst), 1);
31138        assert_eq!(
31139            server
31140                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
31141                .len(),
31142            1
31143        );
31144    }
31145
31146    #[tokio::test]
31147    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
31148        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31149            request_override: Some(workflow_completion_lock_pressure_then_slow),
31150            ..MockWorkerBehavior::default()
31151        });
31152        let calls = Arc::new(AtomicUsize::new(0));
31153        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
31154            .with_storage_admission(Arc::new(AtomicBool::new(false)));
31155        let start = tokio::time::Instant::now();
31156        worker
31157            .client
31158            .worker_storage_admission
31159            .as_mut()
31160            .unwrap()
31161            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
31162        assert!(matches!(
31163            worker.poll_workflow_once().await,
31164            Err(Error::Timeout)
31165        ));
31166        assert!(start.elapsed() < Duration::from_secs(2));
31167        assert_eq!(calls.load(Ordering::SeqCst), 1);
31168        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
31169        assert_eq!(bodies.len(), 2);
31170        assert_eq!(bodies[0], bodies[1]);
31171    }
31172
31173    #[tokio::test]
31174    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
31175        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31176            request_override: Some(workflow_completion_pressure_then_backend_loss),
31177            ..MockWorkerBehavior::default()
31178        });
31179        let calls = Arc::new(AtomicUsize::new(0));
31180        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
31181            .with_storage_admission(Arc::new(AtomicBool::new(false)));
31182        let start = tokio::time::Instant::now();
31183        worker
31184            .client
31185            .worker_storage_admission
31186            .as_mut()
31187            .unwrap()
31188            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
31189        let result = worker.poll_workflow_once().await;
31190        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
31191        assert!(start.elapsed() < Duration::from_secs(2));
31192        assert_eq!(calls.load(Ordering::SeqCst), 1);
31193        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
31194        assert_eq!(bodies.len(), 2);
31195        assert_eq!(bodies[0], bodies[1]);
31196    }
31197
31198    #[tokio::test]
31199    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
31200        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31201            request_override: Some(workflow_completion_lock_pressure_forever),
31202            ..MockWorkerBehavior::default()
31203        });
31204        let calls = Arc::new(AtomicUsize::new(0));
31205        let stop = Arc::new(AtomicBool::new(false));
31206        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
31207            .with_storage_admission(Arc::clone(&stop));
31208        let shutdown = async {
31209            while server
31210                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
31211                .is_empty()
31212            {
31213                tokio::time::sleep(Duration::from_millis(10)).await;
31214            }
31215            stop.store(true, Ordering::SeqCst);
31216        };
31217        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
31218            tokio::join!(worker.poll_workflow_once(), shutdown)
31219        })
31220        .await
31221        .unwrap();
31222        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
31223        assert_eq!(calls.load(Ordering::SeqCst), 1);
31224        assert_eq!(
31225            server
31226                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
31227                .len(),
31228            1
31229        );
31230    }
31231
31232    #[tokio::test]
31233    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
31234        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31235            request_override: Some(workflow_completion_lock_pressure_then_expired),
31236            ..MockWorkerBehavior::default()
31237        });
31238        let calls = Arc::new(AtomicUsize::new(0));
31239        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
31240        let result = worker.run_once().await;
31241        assert!(
31242            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
31243        );
31244        assert_eq!(calls.load(Ordering::SeqCst), 1);
31245        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
31246        assert_eq!(bodies.len(), 2);
31247        assert_eq!(bodies[0], bodies[1]);
31248        assert!(server
31249            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
31250            .is_empty());
31251    }
31252
31253    #[tokio::test]
31254    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
31255        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31256            request_override: Some(workflow_completion_lock_pressure),
31257            ..MockWorkerBehavior::default()
31258        });
31259        let client = Client::builder(server.base_url())
31260            .timeout(Duration::from_secs(2))
31261            .build()
31262            .unwrap();
31263        let calls = Arc::new(AtomicUsize::new(0));
31264        let mut worker = Worker::new(client, "recover-queue")
31265            .worker_id("recover-worker")
31266            .recover_transient_outages(true)
31267            .poll_timeout(Duration::from_millis(10))
31268            .retry_policy(WorkerRetryPolicy {
31269                max_retries: 1,
31270                initial_backoff: Duration::from_millis(10),
31271                max_backoff: Duration::from_millis(10),
31272            });
31273        worker.register_workflow("recover.workflow", {
31274            let calls = Arc::clone(&calls);
31275            move |_ctx, _args| {
31276                let calls = Arc::clone(&calls);
31277                async move {
31278                    calls.fetch_add(1, Ordering::SeqCst);
31279                    Ok(json!("done"))
31280                }
31281            }
31282        });
31283        let start = tokio::time::Instant::now();
31284        assert_eq!(worker.run_once().await.unwrap(), 1);
31285        assert!(start.elapsed() >= Duration::from_secs(1));
31286        assert_eq!(calls.load(Ordering::SeqCst), 1);
31287        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
31288        assert_eq!(bodies.len(), 2);
31289        assert_eq!(bodies[0], bodies[1]);
31290    }
31291
31292    #[test]
31293    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
31294        let path = "/worker/workflow-tasks/recover-workflow/complete";
31295        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
31296        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
31297            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
31298            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
31299            "backend":{"driver":"sqlite", "lock_pressure":true}});
31300        let error = |body: Value| Error::Http {
31301            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
31302            body: body.to_string(),
31303        };
31304        assert_eq!(
31305            worker_deferred_workflow_completion_retry_after(
31306                &error(response.clone()),
31307                path,
31308                Some(&request)
31309            ),
31310            Some(Duration::from_secs(1))
31311        );
31312        for (field, value) in [
31313            ("reason", json!("backend_unavailable")),
31314            ("operation", json!("complete_activity_task")),
31315            ("task_id", json!("other-task")),
31316            ("lease_owner", json!("other-owner")),
31317            ("workflow_task_attempt", json!(4)),
31318            ("recorded", json!(true)),
31319            ("recorded", Value::Null),
31320            ("recorded", json!("false")),
31321            ("retryable", json!(false)),
31322            ("retry_after_seconds", json!(0)),
31323            ("retry_after_seconds", json!(-1)),
31324            ("retry_after_seconds", json!(1.0)),
31325            ("retry_after_seconds", json!("1")),
31326            ("retry_after_seconds", json!(6)),
31327            ("backend", json!({"lock_pressure":false})),
31328        ] {
31329            let mut invalid = response.clone();
31330            invalid[field] = value;
31331            assert_eq!(
31332                worker_deferred_workflow_completion_retry_after(
31333                    &error(invalid),
31334                    path,
31335                    Some(&request)
31336                ),
31337                None,
31338                "invalid {field}"
31339            );
31340        }
31341        for field in [
31342            "reason",
31343            "operation",
31344            "task_id",
31345            "lease_owner",
31346            "workflow_task_attempt",
31347            "recorded",
31348            "retryable",
31349            "retry_after_seconds",
31350            "backend",
31351        ] {
31352            let mut missing = response.clone();
31353            missing.as_object_mut().unwrap().remove(field);
31354            assert_eq!(
31355                worker_deferred_workflow_completion_retry_after(
31356                    &error(missing),
31357                    path,
31358                    Some(&request)
31359                ),
31360                None,
31361                "missing {field}"
31362            );
31363        }
31364        assert_eq!(
31365            worker_deferred_workflow_completion_retry_after(
31366                &error(response.clone()),
31367                "/worker/activity-tasks/recover-workflow/complete",
31368                Some(&request)
31369            ),
31370            None
31371        );
31372        assert_eq!(
31373            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
31374            None
31375        );
31376        let wrong_status = Error::Http {
31377            status: reqwest::StatusCode::CONFLICT,
31378            body: response.to_string(),
31379        };
31380        assert_eq!(
31381            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
31382            None
31383        );
31384    }
31385
31386    fn activity_completion_stale_after_backend_recovery(
31387        path: &str,
31388        body: &str,
31389        request_number: usize,
31390    ) -> Option<(&'static str, String)> {
31391        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
31392            return Some((
31393                "409 Conflict",
31394                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(),
31395            ));
31396        }
31397        activity_completion_backend_recovery(path, body, request_number)
31398    }
31399
31400    fn activity_completion_remains_unavailable(
31401        path: &str,
31402        body: &str,
31403        request_number: usize,
31404    ) -> Option<(&'static str, String)> {
31405        if path == "/api/worker/activity-tasks/recover-activity/complete" {
31406            return activity_completion_backend_recovery(path, body, 1);
31407        }
31408        activity_completion_backend_recovery(path, body, request_number)
31409    }
31410
31411    #[tokio::test]
31412    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
31413        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31414            request_override: Some(activity_completion_backend_recovery),
31415            ..MockWorkerBehavior::default()
31416        });
31417        let client = Client::builder(server.base_url())
31418            .timeout(Duration::from_secs(2))
31419            .build()
31420            .expect("client");
31421        let handler_calls = Arc::new(AtomicUsize::new(0));
31422        let mut worker = Worker::new(client, "recover-queue")
31423            .worker_id("recover-worker")
31424            .poll_timeout(Duration::from_millis(10));
31425        worker.register_activity("recover.activity", {
31426            let handler_calls = Arc::clone(&handler_calls);
31427            move |_ctx, _args| {
31428                let handler_calls = Arc::clone(&handler_calls);
31429                async move {
31430                    handler_calls.fetch_add(1, Ordering::SeqCst);
31431                    Ok(json!("done"))
31432                }
31433            }
31434        });
31435
31436        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
31437        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
31438        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
31439        assert_eq!(bodies.len(), 2);
31440        assert_eq!(bodies[0], bodies[1]);
31441    }
31442
31443    #[tokio::test]
31444    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
31445        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31446            request_override: Some(workflow_completion_backend_recovery),
31447            ..MockWorkerBehavior::default()
31448        });
31449        let client = Client::builder(server.base_url())
31450            .timeout(Duration::from_secs(2))
31451            .build()
31452            .expect("client");
31453        let handler_calls = Arc::new(AtomicUsize::new(0));
31454        let mut worker = Worker::new(client, "recover-queue")
31455            .worker_id("recover-worker")
31456            .poll_timeout(Duration::from_millis(10));
31457        worker.register_workflow("recover.workflow", {
31458            let handler_calls = Arc::clone(&handler_calls);
31459            move |_ctx, _args| {
31460                let handler_calls = Arc::clone(&handler_calls);
31461                async move {
31462                    handler_calls.fetch_add(1, Ordering::SeqCst);
31463                    Ok(json!("done"))
31464                }
31465            }
31466        });
31467
31468        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
31469        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
31470        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
31471        assert_eq!(bodies.len(), 2);
31472        assert_eq!(bodies[0], bodies[1]);
31473    }
31474
31475    #[tokio::test]
31476    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
31477        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31478            request_override: Some(activity_completion_stale_after_backend_recovery),
31479            ..MockWorkerBehavior::default()
31480        });
31481        let client = Client::builder(server.base_url())
31482            .timeout(Duration::from_secs(2))
31483            .build()
31484            .expect("client");
31485        let handler_calls = Arc::new(AtomicUsize::new(0));
31486        let mut worker = Worker::new(client, "recover-queue")
31487            .worker_id("recover-worker")
31488            .poll_timeout(Duration::from_millis(10));
31489        worker.register_activity("recover.activity", {
31490            let handler_calls = Arc::clone(&handler_calls);
31491            move |_ctx, _args| {
31492                let handler_calls = Arc::clone(&handler_calls);
31493                async move {
31494                    handler_calls.fetch_add(1, Ordering::SeqCst);
31495                    Ok(json!("done"))
31496                }
31497            }
31498        });
31499
31500        assert_eq!(
31501            worker
31502                .run_once()
31503                .await
31504                .expect("authoritative stale outcome"),
31505            1
31506        );
31507        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
31508        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
31509        assert_eq!(bodies.len(), 2);
31510        assert_eq!(bodies[0], bodies[1]);
31511    }
31512
31513    #[test]
31514    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
31515        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
31516        let response = json!({
31517            "reason":"backend_unavailable", "operation":"complete_activity_task",
31518            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
31519            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
31520            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
31521        });
31522        let path = "/worker/activity-tasks/recover-activity/complete";
31523        let error = |body: Value| Error::Http {
31524            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
31525            body: body.to_string(),
31526        };
31527        assert_eq!(
31528            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
31529            Some(Duration::from_secs(1))
31530        );
31531
31532        for (field, invalid) in [
31533            ("operation", json!("poll_activity_task")),
31534            ("outcome", json!("rejected")),
31535            ("worker_id", json!("another-worker")),
31536            ("task_queue", json!("recover-queue")),
31537            ("retryable", json!(false)),
31538            ("retry_after_seconds", json!(0)),
31539            ("task_id", json!("another-task")),
31540            ("lease_owner", json!("another-worker")),
31541            ("activity_attempt_id", json!("another-attempt")),
31542        ] {
31543            let mut invalid_response = response.clone();
31544            invalid_response[field] = invalid;
31545            assert_eq!(
31546                worker_fenced_completion_retry_after(
31547                    &error(invalid_response),
31548                    path,
31549                    Some(&request)
31550                ),
31551                None,
31552                "must not retry mismatched {field}"
31553            );
31554        }
31555        assert_eq!(
31556            worker_fenced_completion_retry_after(&error(response), path, None),
31557            None
31558        );
31559    }
31560
31561    #[tokio::test]
31562    async fn shutdown_interrupts_fenced_completion_backend_wait() {
31563        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31564            request_override: Some(activity_completion_remains_unavailable),
31565            ..MockWorkerBehavior::default()
31566        });
31567        let client = Client::builder(server.base_url())
31568            .timeout(Duration::from_secs(2))
31569            .build()
31570            .expect("client");
31571        let stop = Arc::new(AtomicBool::new(false));
31572        let worker = Worker::new(client, "recover-queue")
31573            .worker_id("recover-worker")
31574            .with_storage_admission(Arc::clone(&stop));
31575        let completion = tokio::spawn(async move {
31576            worker
31577                .client
31578                .complete_activity_task(
31579                    "recover-activity",
31580                    "recover-attempt",
31581                    "recover-worker",
31582                    json!("done"),
31583                    DEFAULT_CODEC,
31584                )
31585                .await
31586        });
31587        let path = "/api/worker/activity-tasks/recover-activity/complete";
31588        tokio::time::timeout(Duration::from_secs(2), async {
31589            while server.request_count(path) == 0 {
31590                tokio::time::sleep(Duration::from_millis(10)).await;
31591            }
31592        })
31593        .await
31594        .expect("first completion request");
31595        stop.store(true, Ordering::SeqCst);
31596        let error = tokio::time::timeout(Duration::from_secs(1), completion)
31597            .await
31598            .expect("shutdown must interrupt retry wait")
31599            .expect("completion task")
31600            .expect_err("backend is still unavailable");
31601        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
31602        assert_eq!(server.request_count(path), 1);
31603    }
31604}