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 runtime_payloads;
12mod runtime_uploads;
13mod sticky_worker;
14mod sticky_workflow_cache;
15mod worker_session;
16mod workflow_hydration;
17
18pub use cancellation_context::{
19    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
20};
21pub use cancellation_scope::CancellationScopeOpenReceipt;
22#[doc(hidden)]
23pub use cancellation_scope_history::{
24    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
25};
26#[doc(hidden)]
27pub use cancellation_scope_replay::CancellationScopeRequested;
28
29pub use cooperative_cancellation::{
30    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
31    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
32    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
33    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
34};
35
36use std::{
37    any::{type_name, Any, TypeId},
38    collections::{BTreeMap, BTreeSet, HashMap},
39    future::Future,
40    io::{self, Read},
41    pin::Pin,
42    sync::{
43        atomic::{AtomicBool, Ordering},
44        Arc, Mutex, OnceLock,
45    },
46    task::{Context as TaskContext, Poll},
47    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
48};
49
50use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
51use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
52use chrono::DateTime;
53use futures_util::{
54    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
55};
56pub use local_activity::LocalActivityOptions;
57use serde::{
58    de::DeserializeOwned,
59    ser::{SerializeMap, SerializeSeq},
60    Deserialize, Deserializer, Serialize, Serializer,
61};
62pub use serde_json::{json, Value};
63use sha2::{Digest, Sha256};
64pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
65use thiserror::Error;
66pub use uuid::Uuid;
67pub use worker_session::{WorkerSession, WorkerSessionOptions};
68
69pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
70pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
71
72/// Select the worker request protocol without enabling optional capabilities.
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum WorkerProtocolVersion {
76    /// Compatibility with Servers that implement only worker protocol 1.19.
77    V119,
78    /// The default worker protocol.
79    #[default]
80    V120,
81}
82
83impl WorkerProtocolVersion {
84    fn as_str(self) -> &'static str {
85        match self {
86            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
87            Self::V120 => WORKER_PROTOCOL_VERSION,
88        }
89    }
90}
91const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
92/// First additive worker protocol that defines portable worker-affinity features.
93pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
94pub const CONTROL_PLANE_VERSION: &str = "2";
95pub const DEFAULT_CODEC: &str = "avro";
96pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
97/// Worker-registration capability for authored condition-wait occurrence identity.
98pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
99    "condition_wait_occurrence_identity";
100/// Worker-registration capability for portable memo upserts.
101pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
102/// Worker-registration capability for server-routed read-only queries.
103pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
104/// Worker-registration capability for canonical typed search attributes.
105pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
106/// Worker-registration capability for synchronous workflow updates.
107pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
108/// Worker-registration capability for durable named input streams.
109pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
110/// Worker-registration capability for persisted first-completion selection.
111pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
112pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
113pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
114pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
115pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
116pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
117/// First additive worker protocol that defines query-task transport.
118pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
119/// First additive worker protocol that defines typed search-attribute upserts.
120pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
121/// First additive worker protocol that defines portable memo upserts.
122pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
123/// First additive worker protocol that preserves declared search-attribute types.
124pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
125/// First additive worker protocol that defines external durable condition waits.
126pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
127/// First additive worker protocol that preserves authored condition-wait occurrences.
128pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
129/// First additive worker protocol that defines durable selection groups.
130pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
131
132pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
133    let Some((major, minor)) = version.split_once('.') else {
134        return false;
135    };
136    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
137}
138
139fn validate_user_signal_name(signal_name: &str) -> Result<()> {
140    if signal_name == MESSAGE_STREAM_SIGNAL {
141        return Err(Error::Codec(format!(
142            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
143        )));
144    }
145    Ok(())
146}
147
148const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
149const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
150    "Workflow task waiting for scheduled history.";
151const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
152const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
153const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
154const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
155const MAX_MEMO_ENTRIES: usize = 100;
156const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
157const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
158
159const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
160    "lease_expired",
161    "query_task_not_found",
162    "query_task_not_leased",
163    "query_task_timed_out",
164];
165
166/// Manifest for the default service-worker profile.
167///
168/// Inline local execution is enabled separately by [`Worker::local_activities`].
169/// Local execution, sessions and caching require explicit Worker configuration.
170pub fn portable_worker_affinity_capability_manifest() -> Value {
171    json!({
172        "local_activities": {
173            "supported": false,
174            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
175            "reason": "rust_worker_does_not_execute_record_local_activity",
176        },
177        "worker_sessions": {
178            "supported": false,
179            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
180            "reason": "rust_worker_has_no_typed_session_lifecycle",
181        },
182        "sticky_execution": {
183            "supported": false,
184            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
185            "reason": "rust_worker_uses_complete_durable_history_replay",
186        },
187    })
188}
189
190/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
191pub const AVRO_VALUE_SCHEMA_JSON: &str =
192    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
193pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
194pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
195const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
196
197static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
198static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
199    OnceLock::new();
200
201#[derive(Clone, Copy)]
202enum RequestProtocol {
203    ControlPlane,
204    DefaultWorker,
205    Worker(&'static str),
206}
207
208pub type Result<T> = std::result::Result<T, Error>;
209
210#[derive(Debug, Error)]
211pub enum Error {
212    #[error("transport error: {0}")]
213    Transport(#[from] reqwest::Error),
214    #[error(
215        "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"
216    )]
217    InvalidBaseUrl,
218    #[error("json error: {0}")]
219    Json(#[from] serde_json::Error),
220    #[error("http {status}: {body}")]
221    Http {
222        status: reqwest::StatusCode,
223        body: String,
224    },
225    #[error("codec error: {0}")]
226    Codec(String),
227    #[error(transparent)]
228    QueryFailed(QueryFailure),
229    #[error(transparent)]
230    Protocol(ProtocolFailure),
231    #[error(transparent)]
232    NonDeterministicReplay(ReplayFailure),
233    #[error(transparent)]
234    ChildWorkflowFailed(ChildWorkflowFailure),
235    #[error(transparent)]
236    ActivityFailed(ActivityFailure),
237    #[error(transparent)]
238    ParallelFailed(ParallelFailure),
239    #[error(transparent)]
240    SagaCompensationFailed(SagaCompensationFailure),
241    #[error(transparent)]
242    InvalidParallelGroup(ParallelGroupError),
243    #[error(transparent)]
244    DurableOperationCancelled(DurableOperationCancelled),
245    #[error(transparent)]
246    WorkflowCancellationRequested(WorkflowCancellationRequested),
247    #[error(transparent)]
248    CooperativeCancellationRequested(CooperativeCancellationRequested),
249    #[error(transparent)]
250    CancellationScopeRequested(CancellationScopeRequested),
251    #[error(transparent)]
252    WorkflowCommandRejected(WorkflowCommandRejection),
253    #[error(transparent)]
254    WorkflowFailed(WorkflowTerminalOutcome),
255    #[error(transparent)]
256    WorkflowCancelled(WorkflowTerminalOutcome),
257    #[error(transparent)]
258    WorkflowTerminated(WorkflowTerminalOutcome),
259    #[error(transparent)]
260    WorkflowTimedOut(WorkflowTerminalOutcome),
261    #[error(transparent)]
262    ActivityTaskRejected(ActivityTaskRejection),
263    #[error("workflow handler {0:?} is not registered")]
264    WorkflowNotRegistered(String),
265    #[error("activity handler {0:?} is not registered")]
266    ActivityNotRegistered(String),
267    #[error(
268        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
269    )]
270    HandlerType {
271        handler_kind: HandlerKind,
272        handler_name: String,
273        value_kind: HandlerValueKind,
274        rust_type: &'static str,
275        message: String,
276    },
277    #[error("workflow future yielded without emitting a durable command")]
278    WorkflowYieldedWithoutCommand,
279    #[error(
280        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
281    )]
282    MissingWorkflowCommandIdentity,
283    #[error("workflow state lock is poisoned")]
284    WorkflowStatePoisoned,
285    #[error("timer duration is too large for the worker protocol")]
286    TimerDurationOverflow,
287    #[error(transparent)]
288    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
289    #[error(transparent)]
290    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
291    #[error("operation timed out")]
292    Timeout,
293    #[error(
294        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
295    )]
296    MissingRoleCredentials {
297        role: &'static str,
298        opposite_role: &'static str,
299    },
300    #[error("worker loop error: {0}")]
301    WorkerLoop(String),
302    #[error(
303        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
304    )]
305    UnsupportedUpdateValidators { workflow_type: String },
306    #[error("{primary}; worker deregistration also failed: {deregistration}")]
307    WorkerShutdown {
308        primary: Box<Error>,
309        deregistration: Box<Error>,
310    },
311    #[error("invalid child workflow options: {0}")]
312    InvalidChildWorkflowOptions(String),
313    #[error("invalid workflow memo update: {0}")]
314    InvalidMemoUpdate(String),
315    #[error(
316        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
317    )]
318    WorkflowMemoUpdatesUnavailable,
319    #[error("cooperative cancellation is unavailable: {0}")]
320    CooperativeCancellationUnavailable(String),
321    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
322    CancellationScopeExecutionUnavailable,
323    #[error("invalid cooperative cancellation: {0}")]
324    InvalidCooperativeCancellation(String),
325    #[error("activity execution no longer owns its claim: {0}")]
326    ActivityExecutionAbandoned(String),
327    #[error(transparent)]
328    InvalidActivityOptions(ActivityOptionsError),
329    #[error(transparent)]
330    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
331    #[doc(hidden)]
332    #[error("workflow requested continue as new")]
333    ContinueAsNew(ContinueAsNewRequest),
334}
335
336/// Handler namespaces checked independently within a Worker.
337#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
338pub enum RegistrationKind {
339    Workflow,
340    Activity,
341    Query,
342    Update,
343}
344
345impl std::fmt::Display for RegistrationKind {
346    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347        formatter.write_str(match self {
348            Self::Workflow => "workflow",
349            Self::Activity => "activity",
350            Self::Query => "query",
351            Self::Update => "update",
352        })
353    }
354}
355
356/// The authoring adapter and source location of a handler registration.
357#[derive(Clone, Debug, PartialEq, Eq)]
358pub struct HandlerRegistration {
359    pub method: &'static str,
360    pub handler_type: &'static str,
361    pub file: &'static str,
362    pub line: u32,
363    pub column: u32,
364}
365
366impl std::fmt::Display for HandlerRegistration {
367    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368        write!(
369            formatter,
370            "{} at {}:{}:{} ({})",
371            self.method, self.file, self.line, self.column, self.handler_type
372        )
373    }
374}
375
376/// Ambiguous local configuration, rejected before contacting Server.
377#[derive(Clone, Debug, Error, PartialEq, Eq)]
378#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
379pub struct DuplicateRegistrationError {
380    pub handler_kind: RegistrationKind,
381    pub handler_name: String,
382    /// Query/update registrations are scoped to their owning workflow type.
383    pub workflow_type: Option<String>,
384    pub first_definition: HandlerRegistration,
385    pub second_definition: HandlerRegistration,
386}
387
388impl From<DuplicateRegistrationError> for Error {
389    fn from(error: DuplicateRegistrationError) -> Self {
390        Self::WorkerLoop(error.to_string())
391    }
392}
393
394/// Validation failure for a durable condition-wait definition.
395#[derive(Clone, Debug, Error, PartialEq, Eq)]
396pub enum ConditionWaitOptionsError {
397    #[error("condition_key must be non-empty")]
398    EmptyKey,
399    #[error("condition_definition_fingerprint must be non-empty")]
400    EmptyPredicateIdentity,
401    #[error("condition timeout is too large for the worker protocol")]
402    TimeoutOverflow,
403}
404
405/// Stable identity and optional durable timeout for a condition wait.
406///
407/// `predicate_identity` is recorded as the worker protocol's
408/// `condition_definition_fingerprint` and must change whenever predicate
409/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
410/// is written inline; it derives this identity from the predicate tokens.
411#[derive(Clone, Debug, PartialEq, Eq)]
412pub struct ConditionWaitOptions {
413    condition_key: String,
414    predicate_identity: String,
415    timeout: Option<Duration>,
416}
417
418impl ConditionWaitOptions {
419    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
420        Self {
421            condition_key: condition_key.into(),
422            predicate_identity: predicate_identity.into(),
423            timeout: None,
424        }
425    }
426
427    pub fn timeout(mut self, timeout: Duration) -> Self {
428        self.timeout = Some(timeout);
429        self
430    }
431
432    fn validate(
433        &self,
434    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
435        let condition_key = self.condition_key.trim();
436        if condition_key.is_empty() {
437            return Err(ConditionWaitOptionsError::EmptyKey);
438        }
439        let predicate_identity = self.predicate_identity.trim();
440        if predicate_identity.is_empty() {
441            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
442        }
443        let timeout_seconds = self
444            .timeout
445            .map(|timeout| {
446                timeout
447                    .as_secs()
448                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
449                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
450            })
451            .transpose()?;
452
453        Ok(ValidatedConditionWaitOptions {
454            condition_key: condition_key.to_string(),
455            predicate_identity: predicate_identity.to_string(),
456            timeout_seconds,
457        })
458    }
459}
460
461#[derive(Clone, Debug, PartialEq, Eq)]
462struct ValidatedConditionWaitOptions {
463    condition_key: String,
464    predicate_identity: String,
465    timeout_seconds: Option<u64>,
466}
467
468const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
469
470/// Unambiguous terminal result of a durable condition wait.
471#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
472#[serde(rename_all = "snake_case")]
473pub enum ConditionWaitResult {
474    Satisfied,
475    TimedOut,
476}
477
478impl ConditionWaitResult {
479    pub fn is_satisfied(self) -> bool {
480        self == Self::Satisfied
481    }
482
483    pub fn is_timed_out(self) -> bool {
484        self == Self::TimedOut
485    }
486}
487
488/// Build the stable condition definition identity used by [`wait_condition!`].
489#[doc(hidden)]
490pub fn __condition_definition_fingerprint(source: &str) -> String {
491    let mut digest = Sha256::new();
492    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
493    digest.update(source.as_bytes());
494    format!("sha256:{:x}", digest.finalize())
495}
496
497/// Create a durable condition wait whose predicate definition is fingerprinted
498/// from its inline Rust tokens.
499///
500/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
501/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
502#[macro_export]
503macro_rules! wait_condition {
504    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
505        $ctx.wait_condition(
506            $crate::ConditionWaitOptions::new(
507                $key,
508                $crate::__condition_definition_fingerprint(concat!(
509                    module_path!(),
510                    "\0",
511                    stringify!($predicate)
512                )),
513            )
514            .timeout($timeout),
515            $predicate,
516        )
517    }};
518    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
519        $ctx.wait_condition(
520            $crate::ConditionWaitOptions::new(
521                $key,
522                $crate::__condition_definition_fingerprint(concat!(
523                    module_path!(),
524                    "\0",
525                    stringify!($predicate)
526                )),
527            ),
528            $predicate,
529        )
530    }};
531}
532
533const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
534const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
535const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
536const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
537const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
538
539/// Validation failure for a typed workflow search-attribute update.
540#[derive(Clone, Debug, Error, PartialEq, Eq)]
541pub enum SearchAttributeUpdateError {
542    #[error("search-attribute update requires at least one attribute")]
543    Empty,
544    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
545    InvalidKey(String),
546    #[error("search-attribute update exceeds the limit of 100 attributes")]
547    TooManyAttributes,
548    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
549    ValueTooLong {
550        key: String,
551        kind: &'static str,
552        limit: usize,
553    },
554    #[error(
555        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
556    )]
557    EmptyString(String),
558    #[error("search attribute {0:?} has a non-finite float value")]
559    NonFiniteFloat(String),
560    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
561    InvalidDateTime(String),
562    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
563    PayloadTooLarge,
564}
565
566/// One public typed search-attribute value.
567#[derive(Clone, Debug, PartialEq)]
568pub enum SearchAttributeValue {
569    String(String),
570    Keyword(String),
571    KeywordList(Vec<String>),
572    Int(i64),
573    Float(f64),
574    Bool(bool),
575    DateTime(String),
576    Delete,
577}
578
579impl SearchAttributeValue {
580    fn type_name(&self) -> Option<&'static str> {
581        match self {
582            Self::String(_) => Some("string"),
583            Self::Keyword(_) => Some("keyword"),
584            Self::KeywordList(_) => Some("keyword_list"),
585            Self::Int(_) => Some("int"),
586            Self::Float(_) => Some("float"),
587            Self::Bool(_) => Some("bool"),
588            Self::DateTime(_) => Some("datetime"),
589            Self::Delete => None,
590        }
591    }
592
593    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
594        let normalize_string = |value: String, kind: &'static str, limit: usize| {
595            let value = value.trim().to_string();
596            if value.is_empty() {
597                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
598            }
599            if value.len() > limit {
600                return Err(SearchAttributeUpdateError::ValueTooLong {
601                    key: key.to_string(),
602                    kind,
603                    limit,
604                });
605            }
606            Ok(value)
607        };
608
609        match self {
610            Self::String(value) => Ok(Self::String(normalize_string(
611                value,
612                "string",
613                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
614            )?)),
615            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
616                value,
617                "keyword",
618                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
619            )?)),
620            Self::KeywordList(values) => {
621                let values = values
622                    .into_iter()
623                    .map(|value| {
624                        let value = value.trim().to_string();
625                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
626                            return Err(SearchAttributeUpdateError::ValueTooLong {
627                                key: key.to_string(),
628                                kind: "keyword-list entry",
629                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
630                            });
631                        }
632                        Ok(value)
633                    })
634                    .collect::<std::result::Result<Vec<_>, _>>()?;
635                Ok(Self::KeywordList(values))
636            }
637            Self::Float(value) if !value.is_finite() => {
638                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
639            }
640            Self::DateTime(value) => {
641                let value =
642                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
643                if DateTime::parse_from_rfc3339(&value).is_err() {
644                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
645                }
646                Ok(Self::DateTime(value))
647            }
648            value => Ok(value),
649        }
650    }
651
652    fn into_json(self) -> Value {
653        match self {
654            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
655                Value::String(value)
656            }
657            Self::KeywordList(values) => {
658                Value::Array(values.into_iter().map(Value::String).collect())
659            }
660            Self::Int(value) => json!(value),
661            Self::Float(value) => json!(value),
662            Self::Bool(value) => json!(value),
663            Self::Delete => Value::Null,
664        }
665    }
666}
667
668/// Validated typed workflow-side search-attribute mutation.
669#[derive(Clone, Debug, Default, PartialEq)]
670pub struct SearchAttributeUpdate {
671    attributes: BTreeMap<String, SearchAttributeValue>,
672}
673
674impl SearchAttributeUpdate {
675    pub fn new() -> Self {
676        Self::default()
677    }
678
679    pub fn set(
680        mut self,
681        key: impl Into<String>,
682        value: SearchAttributeValue,
683    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
684        let key = key.into();
685        validate_search_attribute_key(&key)?;
686        if !self.attributes.contains_key(&key)
687            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
688        {
689            return Err(SearchAttributeUpdateError::TooManyAttributes);
690        }
691        self.attributes.insert(key.clone(), value.normalized(&key)?);
692        self.validate_size()?;
693        Ok(self)
694    }
695
696    pub fn string(
697        self,
698        key: impl Into<String>,
699        value: impl Into<String>,
700    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
701        self.set(key, SearchAttributeValue::String(value.into()))
702    }
703
704    pub fn keyword(
705        self,
706        key: impl Into<String>,
707        value: impl Into<String>,
708    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
709        self.set(key, SearchAttributeValue::Keyword(value.into()))
710    }
711
712    pub fn keyword_list<I, V>(
713        self,
714        key: impl Into<String>,
715        values: I,
716    ) -> std::result::Result<Self, SearchAttributeUpdateError>
717    where
718        I: IntoIterator<Item = V>,
719        V: Into<String>,
720    {
721        self.set(
722            key,
723            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
724        )
725    }
726
727    pub fn int(
728        self,
729        key: impl Into<String>,
730        value: i64,
731    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
732        self.set(key, SearchAttributeValue::Int(value))
733    }
734
735    pub fn float(
736        self,
737        key: impl Into<String>,
738        value: f64,
739    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
740        self.set(key, SearchAttributeValue::Float(value))
741    }
742
743    pub fn bool(
744        self,
745        key: impl Into<String>,
746        value: bool,
747    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
748        self.set(key, SearchAttributeValue::Bool(value))
749    }
750
751    pub fn datetime(
752        self,
753        key: impl Into<String>,
754        value: impl Into<String>,
755    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
756        self.set(key, SearchAttributeValue::DateTime(value.into()))
757    }
758
759    pub fn delete(
760        self,
761        key: impl Into<String>,
762    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
763        self.set(key, SearchAttributeValue::Delete)
764    }
765
766    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
767        let (attributes, _) = self.clone().into_wire_parts();
768        if serde_json::to_vec(&attributes)
769            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
770            .unwrap_or(true)
771        {
772            return Err(SearchAttributeUpdateError::PayloadTooLarge);
773        }
774        Ok(())
775    }
776
777    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
778        let mut attributes = serde_json::Map::new();
779        let mut attribute_types = BTreeMap::new();
780        for (key, value) in self.attributes {
781            if let Some(type_name) = value.type_name() {
782                attribute_types.insert(key.clone(), type_name.to_string());
783            }
784            attributes.insert(key, value.into_json());
785        }
786        (Value::Object(attributes), attribute_types)
787    }
788
789    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
790        if self.attributes.is_empty() {
791            return Err(SearchAttributeUpdateError::Empty);
792        }
793        self.validate_size()
794    }
795}
796
797fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
798    let valid = !key.is_empty()
799        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
800        && key
801            .bytes()
802            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
803    if valid {
804        Ok(())
805    } else {
806        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
807    }
808}
809
810/// The registered handler family reported by [`Error::HandlerType`].
811#[derive(Clone, Copy, Debug, PartialEq, Eq)]
812pub enum HandlerKind {
813    Workflow,
814    Activity,
815}
816
817impl std::fmt::Display for HandlerKind {
818    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
819        formatter.write_str(match self {
820            Self::Workflow => "workflow",
821            Self::Activity => "activity",
822        })
823    }
824}
825
826/// Whether a typed handler failed to adapt its input or result.
827#[derive(Clone, Copy, Debug, PartialEq, Eq)]
828pub enum HandlerValueKind {
829    Input,
830    Result,
831}
832
833impl std::fmt::Display for HandlerValueKind {
834    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
835        formatter.write_str(match self {
836            Self::Input => "input",
837            Self::Result => "result",
838        })
839    }
840}
841
842/// The lifecycle command sent to a workflow execution.
843#[derive(Clone, Copy, Debug, PartialEq, Eq)]
844pub enum WorkflowCommandKind {
845    Cancel,
846    Terminate,
847}
848
849impl WorkflowCommandKind {
850    fn as_str(self) -> &'static str {
851        match self {
852            Self::Cancel => "cancel",
853            Self::Terminate => "terminate",
854        }
855    }
856}
857
858/// Optional structured fields for a cancellation or termination request.
859#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
860pub struct WorkflowCommandOptions {
861    #[serde(skip_serializing_if = "Option::is_none")]
862    pub reason: Option<String>,
863    #[serde(skip_serializing_if = "Option::is_none")]
864    pub request_id: Option<String>,
865}
866
867/// Server-enforced timeout policy for a workflow start.
868///
869/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
870/// only bounds how long the caller waits. A server deadline produces a terminal
871/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
872/// `run_timeout`.
873#[derive(Clone, Debug, PartialEq, Eq)]
874pub struct WorkflowStartOptions {
875    pub execution_timeout_seconds: u64,
876    pub run_timeout_seconds: u64,
877}
878
879impl Default for WorkflowStartOptions {
880    fn default() -> Self {
881        Self {
882            execution_timeout_seconds: 3600,
883            run_timeout_seconds: 600,
884        }
885    }
886}
887
888impl WorkflowStartOptions {
889    pub fn new() -> Self {
890        Self::default()
891    }
892
893    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
894        self.execution_timeout_seconds = seconds;
895        self
896    }
897
898    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
899        self.run_timeout_seconds = seconds;
900        self
901    }
902
903    fn validate(&self) -> Result<()> {
904        if self.execution_timeout_seconds == 0 {
905            return Err(Error::Codec(
906                "execution_timeout_seconds must be at least 1".to_string(),
907            ));
908        }
909        if self.run_timeout_seconds == 0 {
910            return Err(Error::Codec(
911                "run_timeout_seconds must be at least 1".to_string(),
912            ));
913        }
914        if self.run_timeout_seconds > self.execution_timeout_seconds {
915            return Err(Error::Codec(
916                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
917            ));
918        }
919
920        Ok(())
921    }
922}
923
924/// Optional routing overrides for a continue-as-new transition.
925///
926/// Omitted values retain the current workflow type and task queue. Server-owned
927/// instance metadata is not accepted here and is carried by the server.
928#[derive(Clone, Debug, Default, PartialEq, Eq)]
929pub struct ContinueAsNewOptions {
930    pub workflow_type: Option<String>,
931    pub task_queue: Option<String>,
932}
933
934impl ContinueAsNewOptions {
935    pub fn new() -> Self {
936        Self::default()
937    }
938
939    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
940        self.workflow_type = Some(workflow_type.into());
941        self
942    }
943
944    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
945        self.task_queue = Some(task_queue.into());
946        self
947    }
948
949    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
950        for (field, value) in [
951            ("workflow_type", self.workflow_type.as_deref()),
952            ("task_queue", self.task_queue.as_deref()),
953        ] {
954            if value.is_some_and(|value| value.trim().is_empty()) {
955                return Err(ContinueAsNewOptionsError {
956                    field,
957                    message: format!("{field} must not be empty"),
958                });
959            }
960        }
961        Ok(())
962    }
963}
964
965/// A stable validation error raised before a continue-as-new command is emitted.
966#[derive(Clone, Debug, Error, PartialEq, Eq)]
967#[error("invalid continue-as-new option {field}: {message}")]
968pub struct ContinueAsNewOptionsError {
969    pub field: &'static str,
970    pub message: String,
971}
972
973/// Public history-budget information attached to the current workflow task.
974#[derive(Clone, Debug, Default, PartialEq, Eq)]
975pub struct WorkflowHistoryBudget {
976    pub event_count: u64,
977    pub size_bytes: Option<u64>,
978    pub continue_as_new_recommended: bool,
979    pub pressure: Option<String>,
980}
981
982#[doc(hidden)]
983#[derive(Clone, Debug)]
984pub struct ContinueAsNewRequest {
985    arguments: AvroValue,
986    options: ContinueAsNewOptions,
987}
988
989impl WorkflowCommandOptions {
990    pub fn new() -> Self {
991        Self::default()
992    }
993
994    pub fn reason(mut self, reason: impl Into<String>) -> Self {
995        self.reason = Some(reason.into());
996        self
997    }
998
999    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1000        self.request_id = Some(request_id.into());
1001        self
1002    }
1003}
1004
1005/// The accepted, machine-readable result of a lifecycle command.
1006#[derive(Clone, Debug, PartialEq)]
1007pub struct WorkflowCommandResult {
1008    pub command: WorkflowCommandKind,
1009    pub workflow_id: String,
1010    pub run_id: Option<String>,
1011    pub outcome: Option<String>,
1012    pub reason: Option<String>,
1013    pub command_status: Option<String>,
1014    pub raw: Value,
1015}
1016
1017/// A new run continuing a failed run from its recorded activity boundary.
1018#[derive(Clone, Debug, PartialEq)]
1019pub struct WorkflowRedriveResult {
1020    pub workflow_id: String,
1021    pub source_run_id: String,
1022    pub run_id: String,
1023    pub resume_step_sequence: u64,
1024    pub raw: Value,
1025}
1026
1027/// A stable rejection returned by instance- or selected-run lifecycle commands.
1028#[derive(Clone, Debug, Error)]
1029#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1030pub struct WorkflowCommandRejection {
1031    pub command: WorkflowCommandKind,
1032    pub status: u16,
1033    pub reason: String,
1034    pub message: String,
1035    pub workflow_id: String,
1036    pub run_id: Option<String>,
1037    pub target_scope: Option<String>,
1038    pub body: Value,
1039}
1040
1041/// Stable terminal categories returned by [`WorkflowHandle::result`].
1042#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1043pub enum WorkflowTerminalKind {
1044    Failed,
1045    Cancelled,
1046    Terminated,
1047    TimedOut,
1048}
1049
1050/// A typed terminal workflow outcome with durable identity and failure metadata.
1051///
1052/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1053/// of parsing its display representation. Fields remain `None` when an older
1054/// server did not publish that metadata.
1055#[derive(Clone, Debug, Error)]
1056#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1057pub struct WorkflowTerminalOutcome {
1058    pub kind: WorkflowTerminalKind,
1059    pub workflow_id: String,
1060    pub run_id: Option<String>,
1061    pub reason: String,
1062    pub failure_category: Option<String>,
1063    pub failure_id: Option<String>,
1064    pub exception_type: Option<String>,
1065    pub exception_class: Option<String>,
1066    pub non_retryable: Option<bool>,
1067    pub message: Option<String>,
1068    pub exception: Option<Value>,
1069    pub raw: Value,
1070}
1071
1072/// A worker-side activity settlement or heartbeat rejected by durable state.
1073#[derive(Clone, Debug, Error)]
1074#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1075pub struct ActivityTaskRejection {
1076    pub operation: String,
1077    pub status: u16,
1078    pub reason: String,
1079    pub task_id: String,
1080    pub activity_attempt_id: String,
1081    pub cancel_requested: bool,
1082    pub can_continue: Option<bool>,
1083    pub run_closed_reason: Option<String>,
1084    pub body: Value,
1085}
1086
1087/// Stable validation categories for [`ActivityOptions`].
1088#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1089pub enum ActivityOptionsErrorKind {
1090    EmptyTaskQueue,
1091    EmptyRetryPolicy,
1092    InvalidMaxAttempts,
1093    BackoffWithoutRetryBudget,
1094    TooManyBackoffIntervals,
1095    InvalidBackoffCoefficient,
1096    BackoffGenerationTooLarge,
1097    BackoffOverflow,
1098    EmptyNonRetryableErrorType,
1099    TimeoutNotPositive,
1100    MissingTotalTimeout,
1101    TimeoutOverflow,
1102    TimeoutOrder,
1103}
1104
1105/// A machine-readable activity-options validation failure.
1106#[derive(Clone, Debug, Error, PartialEq, Eq)]
1107#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1108pub struct ActivityOptionsError {
1109    pub kind: ActivityOptionsErrorKind,
1110    pub field: Option<&'static str>,
1111    pub message: String,
1112}
1113
1114impl ActivityOptionsError {
1115    fn new(
1116        kind: ActivityOptionsErrorKind,
1117        field: Option<&'static str>,
1118        message: impl Into<String>,
1119    ) -> Self {
1120        Self {
1121            kind,
1122            field,
1123            message: message.into(),
1124        }
1125    }
1126}
1127
1128/// Stable terminal categories returned when an awaited activity does not succeed.
1129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1130pub enum ActivityFailureKind {
1131    Failed,
1132    Cancelled,
1133    TimedOut,
1134}
1135
1136/// A stable, machine-readable terminal activity failure.
1137///
1138/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1139/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1140#[derive(Clone, Debug, Error, PartialEq)]
1141#[error("activity failed ({reason}): {message}")]
1142pub struct ActivityFailure {
1143    pub kind: ActivityFailureKind,
1144    pub reason: String,
1145    pub message: String,
1146    pub activity_execution_id: Option<String>,
1147    pub activity_attempt_id: Option<String>,
1148    pub activity_type: Option<String>,
1149    pub activity_class: Option<String>,
1150    pub attempt_number: Option<u64>,
1151    pub failure_id: Option<String>,
1152    pub failure_category: Option<String>,
1153    pub timeout_kind: Option<String>,
1154    pub non_retryable: bool,
1155    pub exception_type: Option<String>,
1156    pub exception_class: Option<String>,
1157    pub code: Option<Value>,
1158    pub exception: Option<Value>,
1159}
1160
1161/// Stable terminal categories returned when an awaited child does not succeed.
1162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1163pub enum ChildWorkflowFailureKind {
1164    Failed,
1165    Cancelled,
1166    Terminated,
1167}
1168
1169/// A stable, machine-readable child workflow failure delivered to its parent.
1170///
1171/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1172/// of parsing the display message. Child and parent identifiers retain the
1173/// relationship recorded in durable history across worker restarts.
1174#[derive(Clone, Debug, Error)]
1175#[error("child workflow failed ({reason}): {message}")]
1176pub struct ChildWorkflowFailure {
1177    pub kind: ChildWorkflowFailureKind,
1178    pub reason: String,
1179    pub message: String,
1180    pub parent_workflow_id: Option<String>,
1181    pub parent_workflow_run_id: Option<String>,
1182    pub child_workflow_id: Option<String>,
1183    pub child_workflow_run_id: Option<String>,
1184    pub child_workflow_type: Option<String>,
1185    pub failure_id: Option<String>,
1186    pub failure_category: Option<String>,
1187    pub exception_type: Option<String>,
1188    pub exception_class: Option<String>,
1189    pub non_retryable: bool,
1190    pub code: Option<Value>,
1191    pub exception: Option<Value>,
1192}
1193
1194/// The identity of one durable workflow execution.
1195#[derive(Clone, Debug, PartialEq, Eq)]
1196pub struct WorkflowIdentity {
1197    pub workflow_id: Option<String>,
1198    pub run_id: Option<String>,
1199}
1200
1201/// A successful child result together with its durable parent-child identity.
1202#[derive(Clone, Debug, PartialEq)]
1203pub struct ChildWorkflowResult {
1204    pub parent: WorkflowIdentity,
1205    pub child: WorkflowIdentity,
1206    pub child_workflow_type: Option<String>,
1207    pub result: Value,
1208}
1209
1210/// Lossless successful child result for fixed Avro Value workflows.
1211#[derive(Clone, Debug, PartialEq)]
1212pub struct ChildWorkflowAvroResult {
1213    pub parent: WorkflowIdentity,
1214    pub child: WorkflowIdentity,
1215    pub child_workflow_type: Option<String>,
1216    pub result: AvroValue,
1217}
1218
1219/// Stable user-facing identity for one member of a durable selection group.
1220#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1221#[serde(untagged)]
1222pub enum SelectionKey {
1223    Index(usize),
1224    Name(String),
1225}
1226
1227impl From<usize> for SelectionKey {
1228    fn from(value: usize) -> Self {
1229        Self::Index(value)
1230    }
1231}
1232
1233impl From<String> for SelectionKey {
1234    fn from(value: String) -> Self {
1235        Self::Name(value)
1236    }
1237}
1238
1239impl From<&str> for SelectionKey {
1240    fn from(value: &str) -> Self {
1241        Self::Name(value.to_string())
1242    }
1243}
1244
1245/// Typed result of explicitly awaiting a cancelled non-winning operation.
1246#[derive(Clone, Debug, Error, PartialEq, Eq)]
1247#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1248pub struct DurableOperationCancelled {
1249    pub selection_group_id: String,
1250    pub member_key: SelectionKey,
1251    pub member_index: usize,
1252    pub operation_kind: String,
1253    pub operation_identity: String,
1254}
1255
1256/// Stable identity for one enclosing deterministic parallel group.
1257///
1258/// The same fields are attached to every ordinary activity, timer, or child
1259/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1260/// no Rust-specific wire command is introduced.
1261#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1262pub struct ParallelGroupMetadata {
1263    pub parallel_group_id: String,
1264    pub parallel_group_kind: String,
1265    pub parallel_group_base_sequence: u64,
1266    pub parallel_group_size: usize,
1267    pub parallel_group_index: usize,
1268    #[serde(default, skip_serializing_if = "Option::is_none")]
1269    pub parallel_group_mode: Option<String>,
1270    #[serde(default, skip_serializing_if = "Option::is_none")]
1271    pub selection_member_key: Option<SelectionKey>,
1272    #[serde(default, skip_serializing_if = "Option::is_none")]
1273    pub selection_member_index: Option<usize>,
1274    #[serde(default, skip_serializing_if = "Option::is_none")]
1275    pub selection_member_base_sequence: Option<u64>,
1276    #[serde(default, skip_serializing_if = "Option::is_none")]
1277    pub selection_member_size: Option<usize>,
1278    #[serde(default, skip_serializing_if = "Option::is_none")]
1279    pub selection_member_kind: Option<String>,
1280}
1281
1282/// One input-ordered result returned by [`WorkflowContext::parallel`].
1283#[derive(Clone, Debug, PartialEq)]
1284pub enum ParallelResult {
1285    Activity(Value),
1286    ChildWorkflow(ChildWorkflowResult),
1287    Timer,
1288    Signal(Vec<Value>),
1289    Condition(ConditionWaitResult),
1290    Group(Vec<ParallelResult>),
1291}
1292
1293/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1294#[derive(Clone, Debug, PartialEq)]
1295pub enum ParallelAvroResult {
1296    Activity(AvroValue),
1297    ChildWorkflow(ChildWorkflowAvroResult),
1298    Timer,
1299    Signal(Vec<AvroValue>),
1300    Condition(ConditionWaitResult),
1301    Group(Vec<ParallelAvroResult>),
1302}
1303
1304impl ParallelAvroResult {
1305    fn into_json_result(self) -> Result<ParallelResult> {
1306        match self {
1307            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1308            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1309                parent: result.parent,
1310                child: result.child,
1311                child_workflow_type: result.child_workflow_type,
1312                result: result.result.into_json()?,
1313            })),
1314            Self::Timer => Ok(ParallelResult::Timer),
1315            Self::Signal(values) => Ok(ParallelResult::Signal(
1316                values
1317                    .into_iter()
1318                    .map(AvroValue::into_json)
1319                    .collect::<Result<Vec<_>>>()?,
1320            )),
1321            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1322            Self::Group(results) => Ok(ParallelResult::Group(
1323                results
1324                    .into_iter()
1325                    .map(Self::into_json_result)
1326                    .collect::<Result<Vec<_>>>()?,
1327            )),
1328        }
1329    }
1330}
1331
1332/// One successful leaf retained when another parallel member failed.
1333#[derive(Clone, Debug, PartialEq)]
1334pub struct ParallelCompletion {
1335    pub member_path: Vec<usize>,
1336    pub result: ParallelResult,
1337}
1338
1339/// A deterministic join failed after some siblings had already completed.
1340///
1341/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1342/// error. `completed` is declaration ordered and contains only durable
1343/// successes observed in the same replay. Late sibling completions can add
1344/// entries on a later replay without changing `member_path` or the selected
1345/// positional failure.
1346#[derive(Debug, Error)]
1347#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1348pub struct ParallelFailure {
1349    pub group_id: String,
1350    pub member_path: Vec<usize>,
1351    pub group_path: Vec<ParallelGroupMetadata>,
1352    pub completed: Vec<ParallelCompletion>,
1353    #[source]
1354    pub cause: Box<Error>,
1355}
1356
1357/// Stable validation error returned before an invalid group emits commands.
1358#[derive(Clone, Debug, Error, PartialEq, Eq)]
1359#[error("invalid deterministic parallel group ({reason}): {message}")]
1360pub struct ParallelGroupError {
1361    pub reason: &'static str,
1362    pub member_path: Vec<usize>,
1363    pub message: String,
1364}
1365
1366/// Cooperative workflow cancellation observed at an author-controlled point.
1367#[derive(Clone, Debug, Error, PartialEq, Eq)]
1368#[error("workflow cancellation was requested")]
1369pub struct WorkflowCancellationRequested;
1370
1371/// A forward saga failure followed by a terminal compensation failure.
1372#[derive(Debug, Error)]
1373#[error(
1374    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1375)]
1376pub struct SagaCompensationFailure {
1377    pub initiating_failure: Box<Error>,
1378    pub compensation_failure: Box<Error>,
1379    pub compensation_activity_type: String,
1380    pub compensation_registration_order: usize,
1381}
1382
1383/// Server behavior when a parent closes while its child is still open.
1384#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1385pub enum ParentClosePolicy {
1386    #[default]
1387    Abandon,
1388    /// Legacy terminal cancellation without cooperative cleanup.
1389    RequestCancel,
1390    /// Request cooperative cleanup with the original lineage and deadline.
1391    RequestCancellation,
1392    Terminate,
1393}
1394
1395impl ParentClosePolicy {
1396    fn as_str(self) -> &'static str {
1397        match self {
1398            Self::Abandon => "abandon",
1399            Self::RequestCancel => "request_cancel",
1400            Self::RequestCancellation => "request_cancellation",
1401            Self::Terminate => "terminate",
1402        }
1403    }
1404}
1405
1406/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1407#[non_exhaustive]
1408#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1409pub enum CancellationPolicy {
1410    /// Request cancellation and continue without waiting. Historical Activity default.
1411    TryCancel,
1412    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1413    WaitCancellationCompleted,
1414    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1415    #[default]
1416    Abandon,
1417}
1418
1419impl CancellationPolicy {
1420    fn as_str(self) -> &'static str {
1421        match self {
1422            Self::TryCancel => "try_cancel",
1423            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1424            Self::Abandon => "abandon",
1425        }
1426    }
1427}
1428
1429/// Durable retry policy for one child workflow invocation.
1430#[derive(Clone, Debug, Default, PartialEq, Eq)]
1431pub struct ChildWorkflowRetryPolicy {
1432    pub max_attempts: Option<u32>,
1433    pub backoff_seconds: Vec<u64>,
1434    pub non_retryable_error_types: Vec<String>,
1435}
1436
1437/// Options recorded with a child-workflow command.
1438///
1439/// The task queue is mandatory so routing is explicit and replay-stable.
1440#[derive(Clone, Debug, PartialEq, Eq)]
1441pub struct ChildWorkflowOptions {
1442    pub task_queue: String,
1443    pub parent_close_policy: ParentClosePolicy,
1444    pub cancellation_policy: CancellationPolicy,
1445    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1446    pub execution_timeout_seconds: Option<u64>,
1447    pub run_timeout_seconds: Option<u64>,
1448}
1449
1450impl ChildWorkflowOptions {
1451    pub fn new(task_queue: impl Into<String>) -> Self {
1452        Self {
1453            task_queue: task_queue.into(),
1454            parent_close_policy: ParentClosePolicy::Abandon,
1455            cancellation_policy: CancellationPolicy::Abandon,
1456            retry_policy: None,
1457            execution_timeout_seconds: None,
1458            run_timeout_seconds: None,
1459        }
1460    }
1461
1462    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1463        self.parent_close_policy = policy;
1464        self
1465    }
1466
1467    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1468        self.cancellation_policy = policy;
1469        self
1470    }
1471
1472    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1473        self.retry_policy = Some(policy);
1474        self
1475    }
1476
1477    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1478        self.execution_timeout_seconds = Some(seconds);
1479        self
1480    }
1481
1482    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1483        self.run_timeout_seconds = Some(seconds);
1484        self
1485    }
1486}
1487
1488/// Backoff intervals for one durable activity retry policy.
1489#[derive(Clone, Debug, PartialEq, Eq)]
1490pub enum ActivityBackoff {
1491    /// Use these intervals between attempts. The server repeats the final
1492    /// interval if the retry budget contains more attempts than entries.
1493    /// All entries are retained, including those beyond the retry budget.
1494    Explicit(Vec<Duration>),
1495    /// Generate one interval for every retry using integer exponential growth.
1496    Exponential {
1497        initial_interval: Duration,
1498        coefficient: u32,
1499        maximum_interval: Option<Duration>,
1500    },
1501}
1502
1503/// Durable server-side retry policy for one activity execution.
1504#[derive(Clone, Debug, Default, PartialEq, Eq)]
1505pub struct ActivityRetryPolicy {
1506    pub max_attempts: Option<u32>,
1507    pub backoff: Option<ActivityBackoff>,
1508    pub non_retryable_error_types: Vec<String>,
1509}
1510
1511impl ActivityRetryPolicy {
1512    /// Start a policy with a finite attempt budget, including the first attempt.
1513    pub fn new(max_attempts: u32) -> Self {
1514        Self {
1515            max_attempts: Some(max_attempts),
1516            ..Self::default()
1517        }
1518    }
1519
1520    /// Preserve the complete explicit list independently of the attempt budget.
1521    /// Unused entries remain part of the policy compared during replay.
1522    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1523        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1524        self
1525    }
1526
1527    pub fn exponential_backoff(
1528        mut self,
1529        initial_interval: Duration,
1530        coefficient: u32,
1531        maximum_interval: Option<Duration>,
1532    ) -> Self {
1533        self.backoff = Some(ActivityBackoff::Exponential {
1534            initial_interval,
1535            coefficient,
1536            maximum_interval,
1537        });
1538        self
1539    }
1540
1541    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1542        self.non_retryable_error_types.push(error_type.into());
1543        self
1544    }
1545
1546    pub fn non_retryable_error_types(
1547        mut self,
1548        error_types: impl IntoIterator<Item = impl Into<String>>,
1549    ) -> Self {
1550        self.non_retryable_error_types
1551            .extend(error_types.into_iter().map(Into::into));
1552        self
1553    }
1554}
1555
1556/// Options recorded atomically on one deterministic `schedule_activity` command.
1557///
1558/// Durations are rounded up to whole seconds when encoded, so the server never
1559/// receives a shorter timeout or backoff than the caller requested.
1560#[derive(Clone, Debug, Default, PartialEq, Eq)]
1561pub struct ActivityOptions {
1562    pub task_queue: Option<String>,
1563    pub retry_policy: Option<ActivityRetryPolicy>,
1564    pub start_to_close_timeout: Option<Duration>,
1565    pub schedule_to_start_timeout: Option<Duration>,
1566    pub schedule_to_close_timeout: Option<Duration>,
1567    pub heartbeat_timeout: Option<Duration>,
1568    pub cancellation_policy: Option<CancellationPolicy>,
1569}
1570
1571impl ActivityOptions {
1572    pub fn new() -> Self {
1573        Self::default()
1574    }
1575
1576    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1577        self.task_queue = Some(task_queue.into());
1578        self
1579    }
1580
1581    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1582        self.retry_policy = Some(policy);
1583        self
1584    }
1585
1586    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1587        self.start_to_close_timeout = Some(timeout);
1588        self
1589    }
1590
1591    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1592        self.schedule_to_start_timeout = Some(timeout);
1593        self
1594    }
1595
1596    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1597        self.schedule_to_close_timeout = Some(timeout);
1598        self
1599    }
1600
1601    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1602        self.heartbeat_timeout = Some(timeout);
1603        self
1604    }
1605
1606    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1607        self.cancellation_policy = Some(policy);
1608        self
1609    }
1610
1611    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1612        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1613            && self.schedule_to_close_timeout.is_none()
1614        {
1615            return Err(ActivityOptionsError::new(
1616                ActivityOptionsErrorKind::MissingTotalTimeout,
1617                Some("schedule_to_close_timeout"),
1618                "remote Activity Abandon requires a finite positive total timeout",
1619            ));
1620        }
1621        if self
1622            .task_queue
1623            .as_deref()
1624            .is_some_and(|queue| queue.trim().is_empty())
1625        {
1626            return Err(ActivityOptionsError::new(
1627                ActivityOptionsErrorKind::EmptyTaskQueue,
1628                Some("task_queue"),
1629                "task_queue must not be empty",
1630            ));
1631        }
1632
1633        for (field, value) in [
1634            ("start_to_close_timeout", self.start_to_close_timeout),
1635            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1636            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1637            ("heartbeat_timeout", self.heartbeat_timeout),
1638        ] {
1639            if value.is_some_and(|value| value.is_zero()) {
1640                return Err(ActivityOptionsError::new(
1641                    ActivityOptionsErrorKind::TimeoutNotPositive,
1642                    Some(field),
1643                    format!("{field} must be positive"),
1644                ));
1645            }
1646        }
1647
1648        validate_timeout_order(
1649            "heartbeat_timeout",
1650            self.heartbeat_timeout,
1651            "start_to_close_timeout",
1652            self.start_to_close_timeout,
1653        )?;
1654        validate_timeout_order(
1655            "start_to_close_timeout",
1656            self.start_to_close_timeout,
1657            "schedule_to_close_timeout",
1658            self.schedule_to_close_timeout,
1659        )?;
1660        validate_timeout_order(
1661            "schedule_to_start_timeout",
1662            self.schedule_to_start_timeout,
1663            "schedule_to_close_timeout",
1664            self.schedule_to_close_timeout,
1665        )?;
1666
1667        Ok(ValidatedActivityOptions {
1668            task_queue: self.task_queue.clone(),
1669            retry_policy: self
1670                .retry_policy
1671                .as_ref()
1672                .map(validate_activity_retry_policy)
1673                .transpose()?,
1674            start_to_close_timeout: timeout_seconds(
1675                "start_to_close_timeout",
1676                self.start_to_close_timeout,
1677            )?,
1678            schedule_to_start_timeout: timeout_seconds(
1679                "schedule_to_start_timeout",
1680                self.schedule_to_start_timeout,
1681            )?,
1682            schedule_to_close_timeout: timeout_seconds(
1683                "schedule_to_close_timeout",
1684                self.schedule_to_close_timeout,
1685            )?,
1686            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1687            cancellation_policy: self.cancellation_policy,
1688        })
1689    }
1690}
1691
1692/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1693///
1694/// Constructors capture arguments but perform no I/O. The join validates the
1695/// complete tree, attaches the existing parallel-group metadata to every
1696/// ordinary command, schedules all leaves, and then suspends.
1697pub enum ParallelOperation {
1698    Activity {
1699        activity_type: String,
1700        options: ActivityOptions,
1701        arguments: Result<AvroValue>,
1702    },
1703    ChildWorkflow {
1704        workflow_type: String,
1705        options: ChildWorkflowOptions,
1706        arguments: Result<AvroValue>,
1707    },
1708    Timer(Duration),
1709    Signal(String),
1710    Condition {
1711        options: ConditionWaitOptions,
1712        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1713    },
1714    Group(Vec<ParallelOperation>),
1715}
1716
1717impl ParallelOperation {
1718    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1719        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1720    }
1721
1722    pub fn activity_with_options<T: Serialize>(
1723        activity_type: impl Into<String>,
1724        options: ActivityOptions,
1725        args: T,
1726    ) -> Self {
1727        Self::Activity {
1728            activity_type: activity_type.into(),
1729            options,
1730            arguments: AvroValue::from_serialize(&args),
1731        }
1732    }
1733
1734    pub fn child_workflow<T: Serialize>(
1735        workflow_type: impl Into<String>,
1736        options: ChildWorkflowOptions,
1737        args: T,
1738    ) -> Self {
1739        Self::ChildWorkflow {
1740            workflow_type: workflow_type.into(),
1741            options,
1742            arguments: AvroValue::from_serialize(&args),
1743        }
1744    }
1745
1746    pub fn timer(duration: Duration) -> Self {
1747        Self::Timer(duration)
1748    }
1749
1750    pub fn signal(signal_name: impl Into<String>) -> Self {
1751        Self::Signal(signal_name.into())
1752    }
1753
1754    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1755    where
1756        F: Fn() -> Result<bool> + Send + 'static,
1757    {
1758        Self::Condition {
1759            options,
1760            predicate: Box::new(predicate),
1761        }
1762    }
1763
1764    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1765        Self::Group(operations)
1766    }
1767}
1768
1769#[derive(Clone, Debug)]
1770struct ValidatedActivityOptions {
1771    task_queue: Option<String>,
1772    retry_policy: Option<Value>,
1773    start_to_close_timeout: Option<u64>,
1774    schedule_to_start_timeout: Option<u64>,
1775    schedule_to_close_timeout: Option<u64>,
1776    heartbeat_timeout: Option<u64>,
1777    cancellation_policy: Option<CancellationPolicy>,
1778}
1779
1780fn validate_timeout_order(
1781    smaller_name: &'static str,
1782    smaller: Option<Duration>,
1783    larger_name: &'static str,
1784    larger: Option<Duration>,
1785) -> std::result::Result<(), ActivityOptionsError> {
1786    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1787        return Err(ActivityOptionsError::new(
1788            ActivityOptionsErrorKind::TimeoutOrder,
1789            Some(smaller_name),
1790            format!("{smaller_name} must be <= {larger_name}"),
1791        ));
1792    }
1793    Ok(())
1794}
1795
1796fn timeout_seconds(
1797    field: &'static str,
1798    value: Option<Duration>,
1799) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1800    value
1801        .map(|value| {
1802            activity_protocol_seconds(value).ok_or_else(|| {
1803                ActivityOptionsError::new(
1804                    ActivityOptionsErrorKind::TimeoutOverflow,
1805                    Some(field),
1806                    format!("{field} is too large for the worker protocol"),
1807                )
1808            })
1809        })
1810        .transpose()
1811}
1812
1813fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1814    value
1815        .as_secs()
1816        .checked_add(u64::from(value.subsec_nanos() > 0))
1817}
1818
1819fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1820    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1821}
1822
1823fn validate_activity_retry_policy(
1824    policy: &ActivityRetryPolicy,
1825) -> std::result::Result<Value, ActivityOptionsError> {
1826    if policy.max_attempts.is_none()
1827        && policy.backoff.is_none()
1828        && policy.non_retryable_error_types.is_empty()
1829    {
1830        return Err(ActivityOptionsError::new(
1831            ActivityOptionsErrorKind::EmptyRetryPolicy,
1832            Some("retry_policy"),
1833            "retry_policy must configure at least one field",
1834        ));
1835    }
1836    if policy.max_attempts == Some(0) {
1837        return Err(ActivityOptionsError::new(
1838            ActivityOptionsErrorKind::InvalidMaxAttempts,
1839            Some("retry_policy.max_attempts"),
1840            "max_attempts must be >= 1",
1841        ));
1842    }
1843    if policy
1844        .non_retryable_error_types
1845        .iter()
1846        .any(|error_type| error_type.trim().is_empty())
1847    {
1848        return Err(ActivityOptionsError::new(
1849            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
1850            Some("retry_policy.non_retryable_error_types"),
1851            "non_retryable_error_types must not contain empty values",
1852        ));
1853    }
1854
1855    let backoff_seconds = match &policy.backoff {
1856        None => None,
1857        Some(backoff) => {
1858            let max_attempts = policy.max_attempts.ok_or_else(|| {
1859                ActivityOptionsError::new(
1860                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
1861                    Some("retry_policy.backoff"),
1862                    "backoff requires max_attempts",
1863                )
1864            })?;
1865            let retry_count = max_attempts.saturating_sub(1) as usize;
1866            let intervals = match backoff {
1867                ActivityBackoff::Explicit(intervals) => intervals.clone(),
1868                ActivityBackoff::Exponential {
1869                    initial_interval,
1870                    coefficient,
1871                    maximum_interval,
1872                } => {
1873                    if *coefficient < 1 {
1874                        return Err(ActivityOptionsError::new(
1875                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
1876                            Some("retry_policy.backoff.coefficient"),
1877                            "backoff coefficient must be >= 1",
1878                        ));
1879                    }
1880                    if retry_count > 10_000 {
1881                        return Err(ActivityOptionsError::new(
1882                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
1883                            Some("retry_policy.max_attempts"),
1884                            "generated backoff supports at most 10000 retry intervals",
1885                        ));
1886                    }
1887                    let mut current = *initial_interval;
1888                    let mut intervals = Vec::with_capacity(retry_count);
1889                    for _ in 0..retry_count {
1890                        let interval = maximum_interval
1891                            .map(|maximum| current.min(maximum))
1892                            .unwrap_or(current);
1893                        intervals.push(interval);
1894                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
1895                            break;
1896                        }
1897                        current = current.checked_mul(*coefficient).ok_or_else(|| {
1898                            ActivityOptionsError::new(
1899                                ActivityOptionsErrorKind::BackoffOverflow,
1900                                Some("retry_policy.backoff"),
1901                                "generated backoff interval overflowed",
1902                            )
1903                        })?;
1904                    }
1905                    intervals
1906                }
1907            };
1908            Some(
1909                intervals
1910                    .into_iter()
1911                    .map(|interval| {
1912                        activity_protocol_seconds(interval).ok_or_else(|| {
1913                            ActivityOptionsError::new(
1914                                ActivityOptionsErrorKind::BackoffOverflow,
1915                                Some("retry_policy.backoff"),
1916                                "backoff interval is too large for the worker protocol",
1917                            )
1918                        })
1919                    })
1920                    .collect::<std::result::Result<Vec<_>, _>>()?,
1921            )
1922        }
1923    };
1924
1925    let mut encoded = serde_json::Map::new();
1926    if let Some(max_attempts) = policy.max_attempts {
1927        encoded.insert("max_attempts".to_string(), json!(max_attempts));
1928    }
1929    if let Some(backoff_seconds) = backoff_seconds {
1930        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
1931    }
1932    if !policy.non_retryable_error_types.is_empty() {
1933        let mut canonical_error_types = Vec::new();
1934        for error_type in policy
1935            .non_retryable_error_types
1936            .iter()
1937            .map(|error_type| error_type.trim())
1938        {
1939            if !canonical_error_types.contains(&error_type) {
1940                canonical_error_types.push(error_type);
1941            }
1942        }
1943        encoded.insert(
1944            "non_retryable_error_types".to_string(),
1945            json!(canonical_error_types),
1946        );
1947    }
1948    Ok(Value::Object(encoded))
1949}
1950
1951/// A stable, machine-readable failure raised when workflow code no longer
1952/// reconstructs the durable command stream recorded in history.
1953#[derive(Clone, Debug, Error)]
1954#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
1955pub struct ReplayFailure {
1956    pub reason: String,
1957    pub sequence: Option<u64>,
1958    pub expected: Option<String>,
1959    pub actual: Option<String>,
1960    pub message: String,
1961}
1962
1963impl ReplayFailure {
1964    fn new(
1965        reason: impl Into<String>,
1966        sequence: Option<u64>,
1967        expected: Option<String>,
1968        actual: Option<String>,
1969        message: impl Into<String>,
1970    ) -> Self {
1971        Self {
1972            reason: reason.into(),
1973            sequence,
1974            expected,
1975            actual,
1976            message: message.into(),
1977        }
1978    }
1979}
1980
1981/// A stable, machine-readable workflow query or query-task settlement failure.
1982#[derive(Clone, Debug, Error)]
1983#[error("query failed ({reason}, HTTP {status}): {message}")]
1984pub struct QueryFailure {
1985    pub status: u16,
1986    pub reason: String,
1987    pub message: String,
1988    pub body: Value,
1989}
1990
1991/// A stable failure returned when a server rejects an SDK protocol version.
1992#[derive(Clone, Debug, Error)]
1993#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
1994pub struct ProtocolFailure {
1995    pub status: u16,
1996    pub reason: String,
1997    pub message: String,
1998    pub supported_version: Option<String>,
1999    pub requested_version: Option<String>,
2000    pub body: Value,
2001}
2002
2003#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2004pub struct PayloadEnvelope {
2005    pub codec: String,
2006    pub blob: String,
2007}
2008
2009impl PayloadEnvelope {
2010    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2011        encode_payload(value, DEFAULT_CODEC)
2012    }
2013
2014    /// Encode an explicit typed value, including the bytes branch that JSON
2015    /// serialization cannot represent.
2016    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2017        encode_avro_value(value)
2018    }
2019}
2020
2021/// Native adapter for the fixed language-neutral Avro Value schema.
2022#[derive(Clone, Debug)]
2023pub enum AvroValue {
2024    Null,
2025    Boolean(bool),
2026    Long(i64),
2027    Double(f64),
2028    Bytes(Vec<u8>),
2029    String(String),
2030    Array(Vec<AvroValue>),
2031    Map(BTreeMap<String, AvroValue>),
2032}
2033
2034impl PartialEq for AvroValue {
2035    fn eq(&self, other: &Self) -> bool {
2036        match (self, other) {
2037            (Self::Null, Self::Null) => true,
2038            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2039            (Self::Long(left), Self::Long(right)) => left == right,
2040            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2041            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2042            (Self::String(left), Self::String(right)) => left == right,
2043            (Self::Array(left), Self::Array(right)) => left == right,
2044            (Self::Map(left), Self::Map(right)) => left == right,
2045            _ => false,
2046        }
2047    }
2048}
2049
2050impl AvroValue {
2051    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2052        Self::from_serde_value(
2053            serde_value::to_value(value).map_err(|error| {
2054                Error::Codec(format!("could not adapt value for Avro: {error}"))
2055            })?,
2056        )
2057    }
2058
2059    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2060        use serde_value::Value as SerdeValue;
2061
2062        match value {
2063            SerdeValue::Unit => Ok(Self::Null),
2064            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2065            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2066            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2067            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2068            SerdeValue::I64(value) => Ok(Self::Long(value)),
2069            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2070            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2071            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2072            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2073                Error::Codec(
2074                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2075                        .to_string(),
2076                )
2077            }),
2078            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2079            SerdeValue::F64(value) => Self::finite_double(value),
2080            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2081            SerdeValue::String(value) => Ok(Self::String(value)),
2082            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2083            SerdeValue::Option(None) => Ok(Self::Null),
2084            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2085                Self::from_serde_value(*value)
2086            }
2087            SerdeValue::Seq(values) => values
2088                .into_iter()
2089                .map(Self::from_serde_value)
2090                .collect::<Result<Vec<_>>>()
2091                .map(Self::Array),
2092            SerdeValue::Map(values) => values
2093                .into_iter()
2094                .map(|(key, value)| {
2095                    let SerdeValue::String(key) = key else {
2096                        return Err(Error::Codec(
2097                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2098                        ));
2099                    };
2100
2101                    Ok((key, Self::from_serde_value(value)?))
2102                })
2103                .collect::<Result<BTreeMap<_, _>>>()
2104                .map(Self::Map),
2105        }
2106    }
2107
2108    fn finite_double(value: f64) -> Result<Self> {
2109        if !value.is_finite() {
2110            return Err(Error::Codec(
2111                "non_finite_float: Avro Value doubles must be finite".to_string(),
2112            ));
2113        }
2114
2115        Ok(Self::Double(value))
2116    }
2117
2118    fn into_json(self) -> Result<Value> {
2119        match self {
2120            Self::Null => Ok(Value::Null),
2121            Self::Boolean(value) => Ok(Value::Bool(value)),
2122            Self::Long(value) => Ok(Value::Number(value.into())),
2123            Self::Double(value) => serde_json::Number::from_f64(value)
2124                .map(Value::Number)
2125                .ok_or_else(|| {
2126                    Error::Codec(
2127                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2128                    )
2129                }),
2130            Self::Bytes(value) => Ok(json!({
2131                "$type": "bytes",
2132                "base64": BASE64.encode(value),
2133            })),
2134            Self::String(value) => Ok(Value::String(value)),
2135            Self::Array(values) => values
2136                .into_iter()
2137                .map(Self::into_json)
2138                .collect::<Result<Vec<_>>>()
2139                .map(Value::Array),
2140            Self::Map(values) => values
2141                .into_iter()
2142                .map(|(key, value)| Ok((key, value.into_json()?)))
2143                .collect::<Result<serde_json::Map<_, _>>>()
2144                .map(Value::Object),
2145        }
2146    }
2147
2148    fn into_serde_value(self) -> serde_value::Value {
2149        use serde_value::Value as SerdeValue;
2150
2151        match self {
2152            Self::Null => SerdeValue::Unit,
2153            Self::Boolean(value) => SerdeValue::Bool(value),
2154            Self::Long(value) => SerdeValue::I64(value),
2155            Self::Double(value) => SerdeValue::F64(value),
2156            Self::Bytes(value) => SerdeValue::Bytes(value),
2157            Self::String(value) => SerdeValue::String(value),
2158            Self::Array(values) => {
2159                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2160            }
2161            Self::Map(values) => SerdeValue::Map(
2162                values
2163                    .into_iter()
2164                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2165                    .collect(),
2166            ),
2167        }
2168    }
2169
2170    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2171        self.into_serde_value().deserialize_into().map_err(|error| {
2172            Error::Codec(format!(
2173                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2174            ))
2175        })
2176    }
2177}
2178
2179impl Serialize for AvroValue {
2180    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2181    where
2182        S: Serializer,
2183    {
2184        match self {
2185            Self::Null => serializer.serialize_unit(),
2186            Self::Boolean(value) => serializer.serialize_bool(*value),
2187            Self::Long(value) => serializer.serialize_i64(*value),
2188            Self::Double(value) => serializer.serialize_f64(*value),
2189            Self::Bytes(value) => serializer.serialize_bytes(value),
2190            Self::String(value) => serializer.serialize_str(value),
2191            Self::Array(values) => {
2192                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2193                for value in values {
2194                    sequence.serialize_element(value)?;
2195                }
2196                sequence.end()
2197            }
2198            Self::Map(values) => {
2199                let mut map = serializer.serialize_map(Some(values.len()))?;
2200                for (key, value) in values {
2201                    map.serialize_entry(key, value)?;
2202                }
2203                map.end()
2204            }
2205        }
2206    }
2207}
2208
2209pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2210    let datum = avro_value_to_datum(value)?;
2211    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2212        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2213    let mut bytes = Vec::with_capacity(datum.len() + 10);
2214    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2215    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2216    bytes.extend_from_slice(&datum);
2217    Ok(PayloadEnvelope {
2218        codec: DEFAULT_CODEC.to_string(),
2219        blob: BASE64.encode(bytes),
2220    })
2221}
2222
2223pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2224    if envelope.codec != DEFAULT_CODEC {
2225        return Err(unsupported_payload_codec(&envelope.codec));
2226    }
2227    decode_avro_value_blob(&envelope.blob)
2228}
2229
2230pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2231    let blob = match codec {
2232        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2233        other => return Err(unsupported_payload_codec(other)),
2234    };
2235
2236    Ok(PayloadEnvelope {
2237        codec: codec.to_string(),
2238        blob,
2239    })
2240}
2241
2242pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2243    match envelope.codec.as_str() {
2244        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2245        other => Err(unsupported_payload_codec(other)),
2246    }
2247}
2248
2249fn handler_type_error<T>(
2250    handler_kind: HandlerKind,
2251    handler_name: &str,
2252    value_kind: HandlerValueKind,
2253    message: impl Into<String>,
2254) -> Error {
2255    Error::HandlerType {
2256        handler_kind,
2257        handler_name: handler_name.to_string(),
2258        value_kind,
2259        rust_type: type_name::<T>(),
2260        message: message.into(),
2261    }
2262}
2263
2264fn decode_handler_input<T: DeserializeOwned>(
2265    arguments: AvroValue,
2266    handler_kind: HandlerKind,
2267    handler_name: &str,
2268) -> Result<T> {
2269    let argument = match arguments {
2270        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2271            arguments.pop().expect("one typed handler argument")
2272        }
2273        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2274        AvroValue::Array(arguments) => {
2275            return Err(handler_type_error::<T>(
2276                handler_kind,
2277                handler_name,
2278                HandlerValueKind::Input,
2279                format!(
2280                    "typed handlers accept one request value, but the task carried {} arguments",
2281                    arguments.len()
2282                ),
2283            ));
2284        }
2285        argument => argument,
2286    };
2287
2288    argument.deserialize().map_err(|error| {
2289        handler_type_error::<T>(
2290            handler_kind,
2291            handler_name,
2292            HandlerValueKind::Input,
2293            error.to_string(),
2294        )
2295    })
2296}
2297
2298fn encode_handler_result<T: Serialize>(
2299    result: &T,
2300    handler_kind: HandlerKind,
2301    handler_name: &str,
2302) -> Result<AvroValue> {
2303    AvroValue::from_serialize(result).map_err(|error| {
2304        handler_type_error::<T>(
2305            handler_kind,
2306            handler_name,
2307            HandlerValueKind::Result,
2308            error.to_string(),
2309        )
2310    })
2311}
2312
2313fn decode_handler_result<T: DeserializeOwned>(
2314    result: AvroValue,
2315    handler_kind: HandlerKind,
2316    handler_name: &str,
2317) -> Result<T> {
2318    result.deserialize().map_err(|error| {
2319        handler_type_error::<T>(
2320            handler_kind,
2321            handler_name,
2322            HandlerValueKind::Result,
2323            error.to_string(),
2324        )
2325    })
2326}
2327
2328#[cfg(test)]
2329fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2330    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2331}
2332
2333fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2334    validate_payload_codec(fallback_codec)?;
2335
2336    if value.is_null() {
2337        return Ok(Value::Null);
2338    }
2339
2340    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2341        return decode_blob(blob, codec);
2342    }
2343
2344    if let Some(blob) = value.as_str() {
2345        return decode_blob(blob, fallback_codec);
2346    }
2347
2348    Err(untagged_payload_value())
2349}
2350
2351fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2352    let envelope = match codec {
2353        DEFAULT_CODEC => encode_avro_value(value)?,
2354        other => return Err(unsupported_payload_codec(other)),
2355    };
2356    Ok(serde_json::to_value(envelope)?)
2357}
2358
2359fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2360    validate_payload_codec(fallback_codec)?;
2361
2362    if value.is_null() {
2363        return Ok(AvroValue::Null);
2364    }
2365
2366    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2367        validate_payload_codec(codec)?;
2368        return decode_avro_value_blob(blob);
2369    }
2370
2371    if let Some(blob) = value.as_str() {
2372        return match fallback_codec {
2373            DEFAULT_CODEC => decode_avro_value_blob(blob),
2374            other => Err(unsupported_payload_codec(other)),
2375        };
2376    }
2377
2378    Err(untagged_payload_value())
2379}
2380
2381fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2382    match value {
2383        AvroValue::Null => AvroValue::Array(Vec::new()),
2384        AvroValue::Array(_) => value,
2385        other => AvroValue::Array(vec![other]),
2386    }
2387}
2388
2389fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2390    match codec {
2391        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2392        other => Err(unsupported_payload_codec(other)),
2393    }
2394}
2395
2396fn validate_payload_codec(codec: &str) -> Result<()> {
2397    match codec {
2398        DEFAULT_CODEC => Ok(()),
2399        MISSING_TASK_PAYLOAD_CODEC => {
2400            Err(invalid_task_payload_codec("task payload_codec is missing"))
2401        }
2402        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2403        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2404            "task payload_codec must be a string",
2405        )),
2406        other => Err(unsupported_payload_codec(other)),
2407    }
2408}
2409
2410fn invalid_task_payload_codec(reason: &str) -> Error {
2411    Error::Codec(format!(
2412        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2413    ))
2414}
2415
2416fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2417    let Some(object) = value.as_object() else {
2418        return Ok(None);
2419    };
2420    if !object.contains_key("codec") && !object.contains_key("blob") {
2421        return Ok(None);
2422    }
2423
2424    let codec = object
2425        .get("codec")
2426        .and_then(Value::as_str)
2427        .ok_or_else(invalid_payload_envelope)?;
2428    validate_payload_codec(codec)?;
2429    let blob = object
2430        .get("blob")
2431        .and_then(Value::as_str)
2432        .ok_or_else(invalid_payload_envelope)?;
2433    Ok(Some((codec, blob)))
2434}
2435
2436fn invalid_payload_envelope() -> Error {
2437    Error::Codec(
2438        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2439            .to_string(),
2440    )
2441}
2442
2443fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2444    for command in commands {
2445        let Some(command) = command.as_object() else {
2446            continue;
2447        };
2448        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2449            continue;
2450        };
2451        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2452            continue;
2453        };
2454
2455        if let Some(codec) = command.get("payload_codec") {
2456            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2457            validate_payload_codec(codec)?;
2458        }
2459
2460        let payload = command
2461            .get(payload_field)
2462            .ok_or_else(invalid_payload_envelope)?;
2463        if runtime_payloads::Reference::parse(payload)?.is_none() {
2464            validate_outbound_payload_envelope(payload)?;
2465        }
2466    }
2467    Ok(())
2468}
2469
2470fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2471    if commands.iter().any(|command| {
2472        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2473            && command
2474                .get("condition_wait_occurrence_id")
2475                .and_then(Value::as_str)
2476                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2477    }) {
2478        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2479    } else if commands.iter().any(|command| {
2480        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2481            && command.get("attribute_types").is_some()
2482    }) {
2483        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2484    } else if commands
2485        .iter()
2486        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2487    {
2488        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2489    } else if commands
2490        .iter()
2491        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2492    {
2493        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2494    } else if commands.iter().any(|command| {
2495        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2496    }) {
2497        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2498    } else {
2499        MINIMUM_WORKER_PROTOCOL_VERSION
2500    }
2501}
2502
2503fn workflow_completion_protocol_version_with_message_streams(
2504    commands: &[Value],
2505    has_message_stream_metadata: bool,
2506) -> &'static str {
2507    let command_protocol = workflow_completion_protocol_version(commands);
2508    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2509        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2510    } else {
2511        command_protocol
2512    }
2513}
2514
2515fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2516    match command_type {
2517        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2518        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2519        "start_service_operation" => Some("request_payload"),
2520        "upsert_memo" => Some("entries"),
2521        _ => None,
2522    }
2523}
2524
2525fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2526    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2527        return Err(untagged_payload_value());
2528    };
2529    validate_payload_codec(codec)?;
2530    decode_avro_value_blob(blob)?;
2531    Ok(())
2532}
2533
2534fn unsupported_payload_codec(codec: &str) -> Error {
2535    Error::Codec(format!(
2536        "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"
2537    ))
2538}
2539
2540fn untagged_payload_value() -> Error {
2541    Error::Codec(
2542        "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"
2543            .to_string(),
2544    )
2545}
2546
2547fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2548    let bytes = BASE64.decode(blob).map_err(|err| {
2549        Error::Codec(format!(
2550            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2551        ))
2552    })?;
2553
2554    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2555        return Err(unsupported_payload_codec("json"));
2556    }
2557
2558    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2559        return Err(Error::Codec(
2560            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2561        ));
2562    }
2563
2564    let fingerprint: [u8; 8] = bytes[2..10]
2565        .try_into()
2566        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2567    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2568        return Err(Error::Codec(format!(
2569            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2570            fingerprint
2571                .iter()
2572                .map(|byte| format!("{byte:02x}"))
2573                .collect::<String>()
2574        )));
2575    }
2576
2577    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2578    // The current fingerprint selects the current immutable schema, so reader
2579    // resolution would only re-walk the same recursive union. Future retained
2580    // writer fingerprints supply a distinct reader schema in this branch.
2581    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2582    if datum_reader.truncated {
2583        return Err(Error::Codec(
2584            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2585        ));
2586    }
2587    let datum = datum.map_err(|err| {
2588        Error::Codec(format!(
2589            "invalid_payload_framing: malformed Avro Value datum: {err}"
2590        ))
2591    })?;
2592    if datum_reader.remaining() != 0 {
2593        return Err(Error::Codec(format!(
2594            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2595            datum_reader.remaining()
2596        )));
2597    }
2598    avro_value_from_datum(datum)
2599}
2600
2601struct StrictAvroDatumReader<'a> {
2602    bytes: &'a [u8],
2603    offset: usize,
2604    truncated: bool,
2605}
2606
2607impl<'a> StrictAvroDatumReader<'a> {
2608    fn new(bytes: &'a [u8]) -> Self {
2609        Self {
2610            bytes,
2611            offset: 0,
2612            truncated: false,
2613        }
2614    }
2615
2616    fn remaining(&self) -> usize {
2617        self.bytes.len() - self.offset
2618    }
2619}
2620
2621impl Read for StrictAvroDatumReader<'_> {
2622    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2623        let count = buffer.len().min(self.remaining());
2624        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2625        self.offset += count;
2626        if count < buffer.len() {
2627            self.truncated = true;
2628        }
2629
2630        Ok(count)
2631    }
2632}
2633
2634fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2635    let branch = match value {
2636        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2637        AvroValue::Boolean(value) => AvroDatum::Union(
2638            1,
2639            Box::new(AvroDatum::Record(vec![(
2640                "boolean".to_string(),
2641                AvroDatum::Boolean(*value),
2642            )])),
2643        ),
2644        AvroValue::Long(value) => AvroDatum::Union(
2645            2,
2646            Box::new(AvroDatum::Record(vec![(
2647                "long".to_string(),
2648                AvroDatum::Long(*value),
2649            )])),
2650        ),
2651        AvroValue::Double(value) => {
2652            if !value.is_finite() {
2653                return Err(Error::Codec(
2654                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2655                ));
2656            }
2657            AvroDatum::Union(
2658                3,
2659                Box::new(AvroDatum::Record(vec![(
2660                    "double".to_string(),
2661                    AvroDatum::Double(*value),
2662                )])),
2663            )
2664        }
2665        AvroValue::Bytes(value) => AvroDatum::Union(
2666            4,
2667            Box::new(AvroDatum::Record(vec![(
2668                "bytes".to_string(),
2669                AvroDatum::Bytes(value.clone()),
2670            )])),
2671        ),
2672        AvroValue::String(value) => AvroDatum::Union(
2673            5,
2674            Box::new(AvroDatum::Record(vec![(
2675                "string".to_string(),
2676                AvroDatum::String(value.clone()),
2677            )])),
2678        ),
2679        AvroValue::Array(values) => AvroDatum::Union(
2680            6,
2681            Box::new(AvroDatum::Record(vec![(
2682                "items".to_string(),
2683                AvroDatum::Array(
2684                    values
2685                        .iter()
2686                        .map(avro_value_to_datum)
2687                        .collect::<Result<Vec<_>>>()?,
2688                ),
2689            )])),
2690        ),
2691        AvroValue::Map(values) => AvroDatum::Union(
2692            7,
2693            Box::new(AvroDatum::Record(vec![(
2694                "entries".to_string(),
2695                AvroDatum::Array(
2696                    values
2697                        .iter()
2698                        .map(|(key, value)| {
2699                            Ok(AvroDatum::Record(vec![
2700                                ("key".to_string(), AvroDatum::String(key.clone())),
2701                                ("value".to_string(), avro_value_to_datum(value)?),
2702                            ]))
2703                        })
2704                        .collect::<Result<Vec<_>>>()?,
2705                ),
2706            )])),
2707        ),
2708    };
2709    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2710}
2711
2712fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2713    let AvroDatum::Record(mut outer) = datum else {
2714        return Err(Error::Codec(
2715            "invalid_payload_framing: datum is not a Value record".to_string(),
2716        ));
2717    };
2718    let (_, branch) = outer
2719        .pop()
2720        .filter(|(name, _)| name == "value")
2721        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2722    let AvroDatum::Union(_, branch) = branch else {
2723        return Err(Error::Codec(
2724            "invalid_payload_framing: invalid Value union".to_string(),
2725        ));
2726    };
2727    match *branch {
2728        AvroDatum::Null => Ok(AvroValue::Null),
2729        AvroDatum::Record(mut fields) => {
2730            let (name, value) = fields.pop().ok_or_else(|| {
2731                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2732            })?;
2733            match (name.as_str(), value) {
2734                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2735                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2736                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2737                    Ok(AvroValue::Double(value))
2738                }
2739                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2740                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2741                ("items", AvroDatum::Array(values)) => values
2742                    .into_iter()
2743                    .map(avro_value_from_datum)
2744                    .collect::<Result<Vec<_>>>()
2745                    .map(AvroValue::Array),
2746                ("entries", AvroDatum::Map(values)) => values
2747                    .into_iter()
2748                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2749                    .collect::<Result<BTreeMap<_, _>>>()
2750                    .map(AvroValue::Map),
2751                _ => Err(Error::Codec(
2752                    "invalid_payload_framing: unknown Value branch".to_string(),
2753                )),
2754            }
2755        }
2756        _ => Err(Error::Codec(
2757            "invalid_payload_framing: invalid Value branch".to_string(),
2758        )),
2759    }
2760}
2761
2762fn avro_value_schema() -> Result<&'static Schema> {
2763    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2764        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2765            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2766    }) {
2767        Ok(schema) => Ok(schema),
2768        Err(message) => Err(Error::Codec(message.clone())),
2769    }
2770}
2771
2772fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2773    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2774        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2775        // have the same block representation when each ordered array record
2776        // contains the map key followed by its value, so this encoding-only
2777        // adaptation lets the official encoder retain BTreeMap wire order.
2778        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2779            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2780        let entries_schema = schema
2781            .pointer_mut("/fields/0/type/7/fields/0/type")
2782            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2783        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2784            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2785        }
2786        *entries_schema = json!({
2787            "type": "array",
2788            "items": {
2789                "type": "record",
2790                "name": "MapEntry",
2791                "fields": [
2792                    {"name": "key", "type": "string"},
2793                    {"name": "value", "type": "Value"}
2794                ]
2795            }
2796        });
2797        Schema::parse_str(&schema.to_string())
2798            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2799    }) {
2800        Ok(schema) => Ok(schema),
2801        Err(message) => Err(Error::Codec(message.clone())),
2802    }
2803}
2804
2805#[derive(Clone, Debug)]
2806pub struct Client {
2807    http: reqwest::Client,
2808    hydration_timeout: Duration,
2809    base_url: String,
2810    token: Option<String>,
2811    control_token: Option<String>,
2812    worker_token: Option<String>,
2813    namespace: String,
2814    max_external_payload_bytes: usize,
2815    worker_storage_admission: Option<WorkerStorageAdmission>,
2816    cooperative_worker_protocol: bool,
2817    worker_protocol_version: WorkerProtocolVersion,
2818    local_activities_enabled: bool,
2819    worker_sessions_enabled: bool,
2820    max_concurrent_worker_sessions: usize,
2821    worker_build_id: Option<String>,
2822    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2823    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2824}
2825
2826impl Client {
2827    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2828        Self::builder(base_url).build()
2829    }
2830
2831    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2832        ClientBuilder {
2833            base_url: base_url.into(),
2834            token: None,
2835            control_token: None,
2836            worker_token: None,
2837            namespace: "default".to_string(),
2838            timeout: Duration::from_secs(60),
2839            max_external_payload_bytes: 64 * 1024 * 1024,
2840            worker_protocol_version: WorkerProtocolVersion::default(),
2841        }
2842    }
2843
2844    pub async fn health(&self) -> Result<Value> {
2845        self.request_json(
2846            reqwest::Method::GET,
2847            "/health",
2848            RequestProtocol::ControlPlane,
2849            Option::<&Value>::None,
2850        )
2851        .await
2852    }
2853
2854    pub async fn cluster_info(&self) -> Result<Value> {
2855        self.request_json(
2856            reqwest::Method::GET,
2857            "/cluster/info",
2858            RequestProtocol::ControlPlane,
2859            Option::<&Value>::None,
2860        )
2861        .await
2862    }
2863
2864    pub async fn start_workflow<T: Serialize>(
2865        &self,
2866        workflow_type: &str,
2867        task_queue: &str,
2868        workflow_id: &str,
2869        input: T,
2870    ) -> Result<WorkflowHandle> {
2871        self.start_workflow_with_options(
2872            workflow_type,
2873            task_queue,
2874            workflow_id,
2875            WorkflowStartOptions::default(),
2876            input,
2877        )
2878        .await
2879    }
2880
2881    /// Start a workflow with explicit server-enforced execution and run
2882    /// deadlines.
2883    pub async fn start_workflow_with_options<T: Serialize>(
2884        &self,
2885        workflow_type: &str,
2886        task_queue: &str,
2887        workflow_id: &str,
2888        options: WorkflowStartOptions,
2889        input: T,
2890    ) -> Result<WorkflowHandle> {
2891        options.validate()?;
2892        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2893        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2894        let body = json!({
2895            "workflow_id": workflow_id,
2896            "workflow_type": workflow_type,
2897            "task_queue": task_queue,
2898            "input": input_envelope,
2899            "execution_timeout_seconds": options.execution_timeout_seconds,
2900            "run_timeout_seconds": options.run_timeout_seconds
2901        });
2902
2903        let data: Value = self
2904            .request_json(
2905                reqwest::Method::POST,
2906                "/workflows",
2907                RequestProtocol::ControlPlane,
2908                Some(&body),
2909            )
2910            .await?;
2911
2912        Ok(WorkflowHandle {
2913            client: self.clone(),
2914            workflow_id: data
2915                .get("workflow_id")
2916                .and_then(Value::as_str)
2917                .unwrap_or(workflow_id)
2918                .to_string(),
2919            run_id: data
2920                .get("run_id")
2921                .and_then(Value::as_str)
2922                .map(str::to_string),
2923            workflow_type: data
2924                .get("workflow_type")
2925                .and_then(Value::as_str)
2926                .unwrap_or(workflow_type)
2927                .to_string(),
2928        })
2929    }
2930
2931    pub async fn signal_workflow<T: Serialize>(
2932        &self,
2933        workflow_id: &str,
2934        signal_name: &str,
2935        input: T,
2936    ) -> Result<Value> {
2937        self.signal_workflow_target(workflow_id, None, signal_name, input)
2938            .await
2939    }
2940
2941    /// Append one idempotently identified item to an instance-scoped input stream.
2942    pub async fn append_message_stream<T: Serialize>(
2943        &self,
2944        workflow_id: &str,
2945        stream_name: &str,
2946        message_id: &str,
2947        input: T,
2948    ) -> Result<Value> {
2949        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2950        let body = json!({
2951            "message_id": message_id,
2952            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2953        });
2954        self.request_json(
2955            reqwest::Method::POST,
2956            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2957            RequestProtocol::ControlPlane,
2958            Some(&body),
2959        )
2960        .await
2961    }
2962
2963    /// Signal only if `run_id` is still the current run for this instance.
2964    pub async fn signal_workflow_run<T: Serialize>(
2965        &self,
2966        workflow_id: &str,
2967        run_id: &str,
2968        signal_name: &str,
2969        input: T,
2970    ) -> Result<Value> {
2971        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
2972            .await
2973    }
2974
2975    async fn signal_workflow_target<T: Serialize>(
2976        &self,
2977        workflow_id: &str,
2978        run_id: Option<&str>,
2979        signal_name: &str,
2980        input: T,
2981    ) -> Result<Value> {
2982        validate_user_signal_name(signal_name)?;
2983        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2984        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2985        let body = json!({
2986            "input": input_envelope
2987        });
2988        let path = match run_id {
2989            Some(run_id) => {
2990                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
2991            }
2992            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
2993        };
2994        self.request_json(
2995            reqwest::Method::POST,
2996            &path,
2997            RequestProtocol::ControlPlane,
2998            Some(&body),
2999        )
3000        .await
3001    }
3002
3003    /// Close the current run as cancelled immediately.
3004    ///
3005    /// Server revokes open tasks and timers without resuming workflow code for
3006    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3007    /// request on a supporting runtime and opted-in worker.
3008    pub async fn cancel_workflow(
3009        &self,
3010        workflow_id: &str,
3011        options: WorkflowCommandOptions,
3012    ) -> Result<WorkflowCommandResult> {
3013        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3014            .await
3015    }
3016
3017    /// Close the selected run as cancelled, only if `run_id` is still current.
3018    pub async fn cancel_workflow_run(
3019        &self,
3020        workflow_id: &str,
3021        run_id: &str,
3022        options: WorkflowCommandOptions,
3023    ) -> Result<WorkflowCommandResult> {
3024        self.workflow_command(
3025            workflow_id,
3026            Some(run_id),
3027            WorkflowCommandKind::Cancel,
3028            options,
3029        )
3030        .await
3031    }
3032
3033    /// Forcefully terminate the current run for an instance.
3034    pub async fn terminate_workflow(
3035        &self,
3036        workflow_id: &str,
3037        options: WorkflowCommandOptions,
3038    ) -> Result<WorkflowCommandResult> {
3039        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3040            .await
3041    }
3042
3043    /// Forcefully terminate only if `run_id` is still current.
3044    pub async fn terminate_workflow_run(
3045        &self,
3046        workflow_id: &str,
3047        run_id: &str,
3048        options: WorkflowCommandOptions,
3049    ) -> Result<WorkflowCommandResult> {
3050        self.workflow_command(
3051            workflow_id,
3052            Some(run_id),
3053            WorkflowCommandKind::Terminate,
3054            options,
3055        )
3056        .await
3057    }
3058
3059    /// Continue a failed run from its recorded activity failure boundary.
3060    pub async fn redrive_workflow_run(
3061        &self,
3062        workflow_id: &str,
3063        failed_run_id: &str,
3064        request_id: Option<&str>,
3065    ) -> Result<WorkflowRedriveResult> {
3066        let body = request_id
3067            .map(|id| json!({"request_id": id}))
3068            .unwrap_or_else(|| json!({}));
3069        let data: Value = self
3070            .request_json(
3071                reqwest::Method::POST,
3072                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3073                RequestProtocol::ControlPlane,
3074                Some(&body),
3075            )
3076            .await?;
3077        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3078            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3079        {
3080            return Err(Error::Codec(
3081                "redrive response was not accepted".to_string(),
3082            ));
3083        }
3084        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3085            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3086        {
3087            return Err(Error::Codec(
3088                "redrive response does not match the requested source run".to_string(),
3089            ));
3090        }
3091        let run_id = data
3092            .get("run_id")
3093            .and_then(Value::as_str)
3094            .filter(|id| !id.is_empty() && *id != failed_run_id)
3095            .ok_or_else(|| {
3096                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3097            })?;
3098        let resume_step_sequence = data
3099            .get("resume_step_sequence")
3100            .and_then(Value::as_u64)
3101            .filter(|sequence| *sequence > 0)
3102            .ok_or_else(|| {
3103                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3104            })?;
3105        Ok(WorkflowRedriveResult {
3106            workflow_id: workflow_id.to_string(),
3107            source_run_id: failed_run_id.to_string(),
3108            run_id: run_id.to_string(),
3109            resume_step_sequence,
3110            raw: data,
3111        })
3112    }
3113
3114    async fn workflow_command(
3115        &self,
3116        workflow_id: &str,
3117        run_id: Option<&str>,
3118        command: WorkflowCommandKind,
3119        options: WorkflowCommandOptions,
3120    ) -> Result<WorkflowCommandResult> {
3121        let path = match run_id {
3122            Some(run_id) => format!(
3123                "/workflows/{workflow_id}/runs/{run_id}/{}",
3124                command.as_str()
3125            ),
3126            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3127        };
3128        let data = match self
3129            .request_json(
3130                reqwest::Method::POST,
3131                &path,
3132                RequestProtocol::ControlPlane,
3133                Some(&options),
3134            )
3135            .await
3136        {
3137            Ok(data) => data,
3138            Err(Error::Http { status, body }) => {
3139                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3140                    command,
3141                    status,
3142                    body,
3143                    workflow_id,
3144                    run_id,
3145                )));
3146            }
3147            Err(error) => return Err(error),
3148        };
3149
3150        Ok(workflow_command_result(command, data, workflow_id, run_id))
3151    }
3152
3153    /// Execute a named, read-only query against a running or completed workflow.
3154    ///
3155    /// Arguments and results use the platform payload envelope. Server and
3156    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3157    /// reason, HTTP status, and original response body.
3158    pub async fn query_workflow<T: Serialize>(
3159        &self,
3160        workflow_id: &str,
3161        query_name: &str,
3162        input: T,
3163    ) -> Result<Value> {
3164        self.query_workflow_target(workflow_id, None, query_name, input)
3165            .await
3166    }
3167
3168    /// Query only if `run_id` is still current, preventing accidental retargeting.
3169    pub async fn query_workflow_run<T: Serialize>(
3170        &self,
3171        workflow_id: &str,
3172        run_id: &str,
3173        query_name: &str,
3174        input: T,
3175    ) -> Result<Value> {
3176        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3177            .await
3178    }
3179
3180    /// Query a workflow and return the lossless fixed Avro Value result.
3181    pub async fn query_workflow_avro_value<T: Serialize>(
3182        &self,
3183        workflow_id: &str,
3184        query_name: &str,
3185        input: T,
3186    ) -> Result<AvroValue> {
3187        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3188            .await
3189    }
3190
3191    /// Query a selected run and return the lossless fixed Avro Value result.
3192    pub async fn query_workflow_run_avro_value<T: Serialize>(
3193        &self,
3194        workflow_id: &str,
3195        run_id: &str,
3196        query_name: &str,
3197        input: T,
3198    ) -> Result<AvroValue> {
3199        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3200            .await
3201    }
3202
3203    async fn query_workflow_avro_value_target<T: Serialize>(
3204        &self,
3205        workflow_id: &str,
3206        run_id: Option<&str>,
3207        query_name: &str,
3208        input: T,
3209    ) -> Result<AvroValue> {
3210        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3211        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3212        let path = match run_id {
3213            Some(run_id) => {
3214                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3215            }
3216            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3217        };
3218        let response: Value = match self
3219            .request_json(
3220                reqwest::Method::POST,
3221                &path,
3222                RequestProtocol::ControlPlane,
3223                Some(&body),
3224            )
3225            .await
3226        {
3227            Ok(response) => response,
3228            Err(Error::Http { status, body }) => {
3229                return Err(Error::QueryFailed(query_failure(status, body)));
3230            }
3231            Err(error) => return Err(error),
3232        };
3233
3234        let envelope = response
3235            .get("result_envelope")
3236            .filter(|envelope| !envelope.is_null())
3237            .ok_or_else(|| {
3238                Error::Codec(
3239                    "missing_payload_envelope: typed query result requires result_envelope"
3240                        .to_string(),
3241                )
3242            })?;
3243        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3244    }
3245
3246    async fn query_workflow_target<T: Serialize>(
3247        &self,
3248        workflow_id: &str,
3249        run_id: Option<&str>,
3250        query_name: &str,
3251        input: T,
3252    ) -> Result<Value> {
3253        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3254        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3255        let body = json!({
3256            "input": input_envelope
3257        });
3258        let path = match run_id {
3259            Some(run_id) => {
3260                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3261            }
3262            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3263        };
3264        let response: Value = match self
3265            .request_json(
3266                reqwest::Method::POST,
3267                &path,
3268                RequestProtocol::ControlPlane,
3269                Some(&body),
3270            )
3271            .await
3272        {
3273            Ok(response) => response,
3274            Err(Error::Http { status, body }) => {
3275                return Err(Error::QueryFailed(query_failure(status, body)));
3276            }
3277            Err(error) => return Err(error),
3278        };
3279
3280        if let Some(envelope) = response
3281            .get("result_envelope")
3282            .filter(|envelope| !envelope.is_null())
3283        {
3284            return decode_wire_value(envelope, DEFAULT_CODEC);
3285        }
3286
3287        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3288    }
3289
3290    /// Send a synchronous update using fixed Avro Value arguments.
3291    pub async fn update_workflow<T: Serialize>(
3292        &self,
3293        workflow_id: &str,
3294        update_name: &str,
3295        input: T,
3296        request_id: Option<&str>,
3297    ) -> Result<Value> {
3298        let response = self
3299            .update_workflow_response(workflow_id, update_name, input, request_id)
3300            .await?;
3301        if let Some(envelope) = response
3302            .get("result_envelope")
3303            .filter(|envelope| !envelope.is_null())
3304        {
3305            return decode_wire_value(envelope, DEFAULT_CODEC);
3306        }
3307        Ok(response.get("result").cloned().unwrap_or(response))
3308    }
3309
3310    /// Send a synchronous update and retain a bytes-capable Avro result.
3311    pub async fn update_workflow_avro_value<T: Serialize>(
3312        &self,
3313        workflow_id: &str,
3314        update_name: &str,
3315        input: T,
3316        request_id: Option<&str>,
3317    ) -> Result<AvroValue> {
3318        let response = self
3319            .update_workflow_response(workflow_id, update_name, input, request_id)
3320            .await?;
3321        let envelope = response
3322            .get("result_envelope")
3323            .filter(|envelope| !envelope.is_null())
3324            .ok_or_else(|| {
3325                Error::Codec(
3326                    "missing_payload_envelope: typed update result requires result_envelope"
3327                        .to_string(),
3328                )
3329            })?;
3330        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3331    }
3332
3333    async fn update_workflow_response<T: Serialize>(
3334        &self,
3335        workflow_id: &str,
3336        update_name: &str,
3337        input: T,
3338        request_id: Option<&str>,
3339    ) -> Result<Value> {
3340        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3341        let mut body = json!({
3342            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3343            "wait_for": "completed",
3344        });
3345        if let Some(request_id) = request_id {
3346            body["request_id"] = json!(request_id);
3347        }
3348        self.request_json(
3349            reqwest::Method::POST,
3350            &format!("/workflows/{workflow_id}/update/{update_name}"),
3351            RequestProtocol::ControlPlane,
3352            Some(&body),
3353        )
3354        .await
3355    }
3356
3357    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3358        let path = format!("/workflows/{workflow_id}");
3359        let mut data: WorkflowDescription = self
3360            .request_json(
3361                reqwest::Method::GET,
3362                &path,
3363                RequestProtocol::ControlPlane,
3364                Option::<&Value>::None,
3365            )
3366            .await?;
3367        data.decode_payloads()?;
3368        Ok(data)
3369    }
3370
3371    /// Describe one selected run, including historical terminal runs.
3372    pub async fn describe_workflow_run(
3373        &self,
3374        workflow_id: &str,
3375        run_id: &str,
3376    ) -> Result<WorkflowDescription> {
3377        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3378        let mut data: WorkflowDescription = self
3379            .request_json(
3380                reqwest::Method::GET,
3381                &path,
3382                RequestProtocol::ControlPlane,
3383                Option::<&Value>::None,
3384            )
3385            .await?;
3386        data.decode_payloads()?;
3387        Ok(data)
3388    }
3389
3390    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3391        let mut path = format!(
3392            "/workflows/{}/runs/{}/streams",
3393            percent_encode_path_segment(workflow_id),
3394            percent_encode_path_segment(run_id),
3395        );
3396        if let Some(stream_name) = stream_name {
3397            path.push('/');
3398            path.push_str(&percent_encode_path_segment(stream_name));
3399        }
3400        path
3401    }
3402
3403    /// List the run-scoped output streams already opened by a workflow.
3404    pub async fn list_workflow_streams(
3405        &self,
3406        workflow_id: &str,
3407        run_id: &str,
3408    ) -> Result<Vec<WorkflowStreamDescription>> {
3409        let response: WorkflowStreamListResponse = self
3410            .request_json(
3411                reqwest::Method::GET,
3412                &Self::workflow_stream_path(workflow_id, run_id, None),
3413                RequestProtocol::ControlPlane,
3414                Option::<&Value>::None,
3415            )
3416            .await?;
3417        Ok(response.streams)
3418    }
3419
3420    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3421    pub async fn describe_workflow_stream(
3422        &self,
3423        workflow_id: &str,
3424        run_id: &str,
3425        stream_name: &str,
3426    ) -> Result<WorkflowStreamDescription> {
3427        let response: WorkflowStreamDescriptionResponse = self
3428            .request_json(
3429                reqwest::Method::GET,
3430                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3431                RequestProtocol::ControlPlane,
3432                Option::<&Value>::None,
3433            )
3434            .await?;
3435        Ok(response.stream)
3436    }
3437
3438    /// Read one bounded page beginning at a zero-based offset.
3439    ///
3440    /// Delivery is at least once: persist `next_offset` only after processing
3441    /// the page. The future is cancellation-safe; dropping it cancels the
3442    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3443    /// service contract.
3444    pub async fn subscribe_workflow_stream(
3445        &self,
3446        workflow_id: &str,
3447        run_id: &str,
3448        stream_name: &str,
3449        from_offset: u64,
3450        max_items: usize,
3451        wait: Duration,
3452    ) -> Result<WorkflowStreamPage> {
3453        let max_items = max_items.clamp(1, 500);
3454        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3455        let path = format!(
3456            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3457            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3458        );
3459        let response: WorkflowStreamPageResponse = self
3460            .request_json_with_timeout(
3461                reqwest::Method::GET,
3462                &path,
3463                RequestProtocol::ControlPlane,
3464                Option::<&Value>::None,
3465                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3466            )
3467            .await?;
3468
3469        let items = response
3470            .items
3471            .into_iter()
3472            .map(|raw| {
3473                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3474                let envelope = raw.get("payload").cloned();
3475                let payload = envelope
3476                    .as_ref()
3477                    .filter(|value| value.get("blob").is_some())
3478                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3479                    .transpose()?
3480                    .map(AvroValue::into_json)
3481                    .transpose()?;
3482                Ok(WorkflowStreamItem {
3483                    offset,
3484                    payload,
3485                    payload_envelope: envelope,
3486                    payload_reference: raw
3487                        .get("payload_reference")
3488                        .and_then(Value::as_str)
3489                        .map(str::to_string),
3490                    payload_codec: raw
3491                        .get("payload_codec")
3492                        .and_then(Value::as_str)
3493                        .map(str::to_string),
3494                    idempotency_key: raw
3495                        .get("idempotency_key")
3496                        .and_then(Value::as_str)
3497                        .map(str::to_string),
3498                    item_type: raw
3499                        .get("item_type")
3500                        .and_then(Value::as_str)
3501                        .map(str::to_string),
3502                    content_type: raw
3503                        .get("content_type")
3504                        .and_then(Value::as_str)
3505                        .map(str::to_string),
3506                    origin: raw
3507                        .get("origin")
3508                        .and_then(Value::as_str)
3509                        .map(str::to_string),
3510                    origin_reference: raw
3511                        .get("origin_reference")
3512                        .and_then(Value::as_str)
3513                        .map(str::to_string),
3514                    emitted_at: raw
3515                        .get("emitted_at")
3516                        .and_then(Value::as_str)
3517                        .map(str::to_string),
3518                    raw,
3519                })
3520            })
3521            .collect::<Result<Vec<_>>>()?;
3522        Ok(WorkflowStreamPage {
3523            stream: response.stream,
3524            items,
3525            next_offset: response.next_offset,
3526            terminal: response.terminal,
3527        })
3528    }
3529
3530    /// Append inline Avro envelopes or opaque external payload references.
3531    pub async fn append_workflow_stream(
3532        &self,
3533        workflow_id: &str,
3534        run_id: &str,
3535        stream_name: &str,
3536        items: &[WorkflowStreamAppendItem],
3537        max_pending_items: Option<u64>,
3538    ) -> Result<WorkflowStreamAppendResult> {
3539        if items.is_empty() {
3540            return Err(Error::Codec(
3541                "workflow_stream_items_empty: append requires at least one item".to_string(),
3542            ));
3543        }
3544        let mut body = json!({
3545            "items": items
3546                .iter()
3547                .map(|item| item.wire_value(None))
3548                .collect::<Vec<_>>(),
3549        });
3550        if let Some(max_pending_items) = max_pending_items {
3551            if max_pending_items == 0 {
3552                return Err(Error::Codec(
3553                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3554                        .to_string(),
3555                ));
3556            }
3557            body["max_pending_items"] = json!(max_pending_items);
3558        }
3559        let response: WorkflowStreamAppendResponse = self
3560            .request_json(
3561                reqwest::Method::POST,
3562                &format!(
3563                    "{}/items",
3564                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3565                ),
3566                RequestProtocol::ControlPlane,
3567                Some(&body),
3568            )
3569            .await?;
3570        Ok(WorkflowStreamAppendResult {
3571            stream: response.stream,
3572            accepted_offsets: response.accepted_offsets,
3573            accepted: response.accepted,
3574            deduped: response.deduped,
3575        })
3576    }
3577
3578    /// Close a stream, or mark it errored when `error_reason` is supplied.
3579    pub async fn close_workflow_stream(
3580        &self,
3581        workflow_id: &str,
3582        run_id: &str,
3583        stream_name: &str,
3584        error_reason: Option<&str>,
3585        retention_seconds: Option<u64>,
3586    ) -> Result<WorkflowStreamDescription> {
3587        let mut body = json!({});
3588        if let Some(error_reason) = error_reason {
3589            body["error_reason"] = json!(error_reason);
3590        }
3591        if let Some(retention_seconds) = retention_seconds {
3592            if retention_seconds == 0 {
3593                return Err(Error::Codec(
3594                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3595                        .to_string(),
3596                ));
3597            }
3598            body["retention_seconds"] = json!(retention_seconds);
3599        }
3600        let response: WorkflowStreamDescriptionResponse = self
3601            .request_json(
3602                reqwest::Method::POST,
3603                &format!(
3604                    "{}/close",
3605                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3606                ),
3607                RequestProtocol::ControlPlane,
3608                Some(&body),
3609            )
3610            .await?;
3611        Ok(response.stream)
3612    }
3613
3614    pub async fn register_worker(
3615        &self,
3616        worker_id: &str,
3617        task_queue: &str,
3618        supported_workflow_types: Vec<String>,
3619        supported_activity_types: Vec<String>,
3620        max_concurrent_workflow_tasks: usize,
3621        max_concurrent_activity_tasks: usize,
3622    ) -> Result<RegisterWorkerResponse> {
3623        self.register_worker_with_capabilities(
3624            worker_id,
3625            task_queue,
3626            supported_workflow_types,
3627            supported_activity_types,
3628            max_concurrent_workflow_tasks,
3629            max_concurrent_activity_tasks,
3630            Vec::new(),
3631        )
3632        .await
3633    }
3634
3635    /// Register a worker and explicitly advertise additive worker capabilities.
3636    pub async fn register_worker_with_capabilities(
3637        &self,
3638        worker_id: &str,
3639        task_queue: &str,
3640        supported_workflow_types: Vec<String>,
3641        supported_activity_types: Vec<String>,
3642        max_concurrent_workflow_tasks: usize,
3643        max_concurrent_activity_tasks: usize,
3644        capabilities: Vec<String>,
3645    ) -> Result<RegisterWorkerResponse> {
3646        self.register_worker_with_command_contracts(
3647            worker_id,
3648            task_queue,
3649            supported_workflow_types,
3650            supported_activity_types,
3651            max_concurrent_workflow_tasks,
3652            max_concurrent_activity_tasks,
3653            capabilities,
3654            Value::Object(serde_json::Map::new()),
3655        )
3656        .await
3657    }
3658
3659    /// Register a worker and advertise its named query and update handlers.
3660    ///
3661    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3662    /// so a workflow contract with a non-empty or malformed
3663    /// `update_validators` declaration returns
3664    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3665    #[allow(clippy::too_many_arguments)]
3666    pub async fn register_worker_with_command_contracts(
3667        &self,
3668        worker_id: &str,
3669        task_queue: &str,
3670        supported_workflow_types: Vec<String>,
3671        supported_activity_types: Vec<String>,
3672        max_concurrent_workflow_tasks: usize,
3673        max_concurrent_activity_tasks: usize,
3674        capabilities: Vec<String>,
3675        workflow_command_contracts: Value,
3676    ) -> Result<RegisterWorkerResponse> {
3677        self.register_worker_with_definition_fingerprints(
3678            worker_id,
3679            task_queue,
3680            supported_workflow_types,
3681            supported_activity_types,
3682            max_concurrent_workflow_tasks,
3683            max_concurrent_activity_tasks,
3684            capabilities,
3685            workflow_command_contracts,
3686            None,
3687        )
3688        .await
3689    }
3690
3691    #[allow(clippy::too_many_arguments)]
3692    async fn register_worker_with_definition_fingerprints(
3693        &self,
3694        worker_id: &str,
3695        task_queue: &str,
3696        supported_workflow_types: Vec<String>,
3697        supported_activity_types: Vec<String>,
3698        max_concurrent_workflow_tasks: usize,
3699        max_concurrent_activity_tasks: usize,
3700        capabilities: Vec<String>,
3701        workflow_command_contracts: Value,
3702        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3703    ) -> Result<RegisterWorkerResponse> {
3704        if let Some(contracts) = workflow_command_contracts.as_object() {
3705            for (workflow_type, contract) in contracts {
3706                let Some(update_validators) = contract.get("update_validators") else {
3707                    continue;
3708                };
3709                if !update_validators
3710                    .as_array()
3711                    .is_some_and(|validators| validators.is_empty())
3712                {
3713                    return Err(Error::UnsupportedUpdateValidators {
3714                        workflow_type: workflow_type.clone(),
3715                    });
3716                }
3717            }
3718        }
3719
3720        let mut body = json!({
3721            "worker_id": worker_id,
3722            "task_queue": task_queue,
3723            "runtime": "rust",
3724            "sdk_version": SDK_VERSION,
3725            "supported_workflow_types": supported_workflow_types,
3726            "supported_activity_types": supported_activity_types,
3727            "capabilities": capabilities,
3728            "capability_manifest": portable_worker_affinity_capability_manifest(),
3729            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3730            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3731        });
3732        if let Some(build_id) = &self.worker_build_id {
3733            if build_id.is_empty() || build_id.len() > 255 {
3734                return Err(Error::WorkerLoop(
3735                    "worker build ID must contain 1 to 255 bytes".into(),
3736                ));
3737            }
3738            body["build_id"] = json!(build_id);
3739        }
3740        if self.sticky_cache.is_some() {
3741            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
3742                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
3743                "implementation":"bounded_durable_history_cache"});
3744        }
3745        if self.local_activities_enabled {
3746            body["capability_manifest"]["local_activities"] = json!({"supported":true,
3747                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3748        }
3749        if self.worker_sessions_enabled {
3750            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
3751                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3752            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
3753        }
3754        if workflow_command_contracts
3755            .as_object()
3756            .is_some_and(|contracts| !contracts.is_empty())
3757        {
3758            body["workflow_command_contracts"] = workflow_command_contracts;
3759        }
3760        if let Some(fingerprints) = workflow_definition_fingerprints {
3761            body["workflow_definition_fingerprints"] = json!(fingerprints);
3762        }
3763
3764        let response: Value = self
3765            .request_json(
3766                reqwest::Method::POST,
3767                "/worker/register",
3768                RequestProtocol::DefaultWorker,
3769                Some(&body),
3770            )
3771            .await?;
3772        if self.sticky_cache.is_some() {
3773            self.confirm_sticky_registration(&response, worker_id, task_queue)
3774                .await?;
3775        }
3776        if self.local_activities_enabled || self.worker_sessions_enabled {
3777            let compatible = response["registered"].as_bool() == Some(true)
3778                && response["worker_id"].as_str() == Some(worker_id)
3779                && response["namespace"].as_str() == Some(self.namespace.as_str())
3780                && response["task_queue"].as_str() == Some(task_queue)
3781                && response["protocol_version"]
3782                    .as_str()
3783                    .and_then(|version| version.strip_prefix("1."))
3784                    .and_then(|minor| minor.parse::<u64>().ok())
3785                    .is_some_and(|minor| minor >= 18)
3786                && (!self.local_activities_enabled
3787                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
3788                        == Some(true))
3789                && (!self.worker_sessions_enabled
3790                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
3791                        == Some(true)
3792                        && response["capabilities"].as_array().is_some_and(|accepted| {
3793                            capabilities.iter().all(|capability| {
3794                                accepted
3795                                    .iter()
3796                                    .any(|value| value.as_str() == Some(capability.as_str()))
3797                            })
3798                        })));
3799            if !compatible {
3800                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
3801                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
3802                } else {
3803                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
3804                });
3805                if response["registered"] == true
3806                    && response["worker_id"].as_str() == Some(worker_id)
3807                {
3808                    if let Err(deregistration) =
3809                        self.deregister_worker_registration(worker_id).await
3810                    {
3811                        return Err(Error::WorkerShutdown {
3812                            primary: Box::new(error),
3813                            deregistration: Box::new(deregistration),
3814                        });
3815                    }
3816                }
3817                return Err(error);
3818            }
3819        }
3820        if self.cooperative_worker_protocol {
3821            let compatible = response["registered"].as_bool() == Some(true)
3822                && response["worker_id"].as_str() == Some(worker_id)
3823                && response["namespace"].as_str() == Some(self.namespace.as_str())
3824                && response["task_queue"].as_str() == Some(task_queue)
3825                && response["protocol_version"]
3826                    .as_str()
3827                    .is_some_and(cooperative_cancellation::supports_protocol)
3828                && response["server_capabilities"]["cooperative_cancellation"].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::CooperativeCancellationUnavailable(
3839                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3840                );
3841                if response["registered"].as_bool() == Some(true)
3842                    && response["worker_id"].as_str() == Some(worker_id)
3843                {
3844                    if let Err(deregistration) =
3845                        self.deregister_worker_registration(worker_id).await
3846                    {
3847                        return Err(Error::WorkerShutdown {
3848                            primary: Box::new(error),
3849                            deregistration: Box::new(deregistration),
3850                        });
3851                    }
3852                }
3853                return Err(error);
3854            }
3855        }
3856        Ok(serde_json::from_value(response)?)
3857    }
3858
3859    /// Gracefully remove one worker's registration through the worker plane.
3860    ///
3861    /// This operation is separate from operator-facing worker management. It
3862    /// uses worker-protocol authentication and returns the server's lease
3863    /// recovery result.
3864    pub async fn deregister_worker_registration(
3865        &self,
3866        worker_id: &str,
3867    ) -> Result<WorkerDeregistrationEnvelope> {
3868        let path = format!(
3869            "/worker/registrations/{}",
3870            percent_encode_path_segment(worker_id)
3871        );
3872        self.request_json(
3873            reqwest::Method::DELETE,
3874            &path,
3875            RequestProtocol::DefaultWorker,
3876            Option::<&Value>::None,
3877        )
3878        .await
3879    }
3880
3881    /// Long-poll for an ephemeral, read-only workflow query task.
3882    pub async fn poll_query_task(
3883        &self,
3884        worker_id: &str,
3885        task_queue: &str,
3886        timeout: Duration,
3887    ) -> Result<Option<QueryTask>> {
3888        Ok(self
3889            .poll_query_task_response(worker_id, task_queue, timeout)
3890            .await?
3891            .task)
3892    }
3893
3894    /// Poll a query task while preserving server stop and drain metadata.
3895    pub async fn poll_query_task_response(
3896        &self,
3897        worker_id: &str,
3898        task_queue: &str,
3899        timeout: Duration,
3900    ) -> Result<PollQueryTaskResponse> {
3901        let poll_request_id = unique_request_id("rust-query-poll");
3902        self.poll_query_task_response_with_request_id(
3903            worker_id,
3904            task_queue,
3905            timeout,
3906            &poll_request_id,
3907            1,
3908        )
3909        .await
3910    }
3911
3912    async fn poll_query_task_response_with_request_id(
3913        &self,
3914        worker_id: &str,
3915        task_queue: &str,
3916        timeout: Duration,
3917        poll_request_id: &str,
3918        transport_retries: usize,
3919    ) -> Result<PollQueryTaskResponse> {
3920        let timeout_seconds = long_poll_timeout_seconds(timeout);
3921        let body = json!({
3922            "worker_id": worker_id,
3923            "task_queue": task_queue,
3924            "poll_request_id": poll_request_id,
3925            "timeout_seconds": timeout_seconds,
3926        });
3927        self.poll_request_json(
3928            "/worker/query-tasks/poll",
3929            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3930            &body,
3931            timeout + Duration::from_secs(5),
3932            transport_retries,
3933        )
3934        .await
3935    }
3936
3937    /// Complete a query task without appending workflow history.
3938    pub async fn complete_query_task<T: Serialize>(
3939        &self,
3940        query_task_id: &str,
3941        lease_owner: &str,
3942        query_task_attempt: u64,
3943        result: T,
3944        codec: &str,
3945    ) -> Result<Value> {
3946        let typed_result = AvroValue::from_serialize(&result)?;
3947        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3948        self.complete_query_task_with_envelope(
3949            query_task_id,
3950            lease_owner,
3951            query_task_attempt,
3952            typed_result.into_json()?,
3953            result_envelope,
3954        )
3955        .await
3956    }
3957
3958    async fn complete_query_task_with_envelope(
3959        &self,
3960        query_task_id: &str,
3961        lease_owner: &str,
3962        query_task_attempt: u64,
3963        result: Value,
3964        result_envelope: Value,
3965    ) -> Result<Value> {
3966        let body = json!({
3967            "lease_owner": lease_owner,
3968            "query_task_attempt": query_task_attempt,
3969            "result": result,
3970            "result_envelope": result_envelope,
3971        });
3972        let path = format!("/worker/query-tasks/{query_task_id}/complete");
3973        let response = self
3974            .request_json(
3975                reqwest::Method::POST,
3976                &path,
3977                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3978                Some(&body),
3979            )
3980            .await;
3981        query_task_response(response)
3982    }
3983
3984    /// Report a stable machine-readable query-task failure.
3985    pub async fn fail_query_task(
3986        &self,
3987        query_task_id: &str,
3988        lease_owner: &str,
3989        query_task_attempt: u64,
3990        message: impl Into<String>,
3991        reason: impl Into<String>,
3992        failure_type: impl Into<String>,
3993    ) -> Result<Value> {
3994        let body = json!({
3995            "lease_owner": lease_owner,
3996            "query_task_attempt": query_task_attempt,
3997            "failure": {
3998                "message": message.into(),
3999                "reason": reason.into(),
4000                "type": failure_type.into(),
4001            }
4002        });
4003        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4004        let response = self
4005            .request_json(
4006                reqwest::Method::POST,
4007                &path,
4008                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4009                Some(&body),
4010            )
4011            .await;
4012        query_task_response(response)
4013    }
4014
4015    pub async fn heartbeat_worker(
4016        &self,
4017        worker_id: &str,
4018        workflow_available: usize,
4019        activity_available: usize,
4020    ) -> Result<Value> {
4021        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4022            .await
4023    }
4024
4025    async fn heartbeat_worker_with_sessions(
4026        &self,
4027        worker_id: &str,
4028        workflow_available: usize,
4029        activity_available: usize,
4030        session_available: Option<usize>,
4031    ) -> Result<Value> {
4032        let mut body = json!({
4033            "worker_id": worker_id,
4034            "task_slots": {
4035                "workflow_available": workflow_available,
4036                "activity_available": activity_available
4037            },
4038            "process_metrics": {
4039                "process_id": std::process::id(),
4040                "process_uptime_seconds": 0
4041            }
4042        });
4043
4044        if let Some(available) = session_available {
4045            body["task_slots"]["session_available"] = json!(available);
4046        }
4047
4048        self.request_json(
4049            reqwest::Method::POST,
4050            "/worker/heartbeat",
4051            RequestProtocol::DefaultWorker,
4052            Some(&body),
4053        )
4054        .await
4055    }
4056
4057    pub async fn poll_workflow_task(
4058        &self,
4059        worker_id: &str,
4060        task_queue: &str,
4061        timeout: Duration,
4062    ) -> Result<Option<WorkflowTask>> {
4063        Ok(self
4064            .poll_workflow_task_response(worker_id, task_queue, timeout)
4065            .await?
4066            .task)
4067    }
4068
4069    pub async fn poll_workflow_task_response(
4070        &self,
4071        worker_id: &str,
4072        task_queue: &str,
4073        timeout: Duration,
4074    ) -> Result<PollWorkflowTaskResponse> {
4075        let poll_request_id = unique_request_id("rust-workflow-poll");
4076        self.poll_workflow_task_response_with_request_id(
4077            worker_id,
4078            task_queue,
4079            timeout,
4080            &poll_request_id,
4081            1,
4082        )
4083        .await
4084    }
4085
4086    async fn poll_workflow_task_response_with_request_id(
4087        &self,
4088        worker_id: &str,
4089        task_queue: &str,
4090        timeout: Duration,
4091        poll_request_id: &str,
4092        transport_retries: usize,
4093    ) -> Result<PollWorkflowTaskResponse> {
4094        let body = json!({
4095            "worker_id": worker_id,
4096            "task_queue": task_queue,
4097            "poll_request_id": poll_request_id,
4098            "timeout_seconds": long_poll_timeout_seconds(timeout),
4099            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4100        });
4101        let mut wire: Value = self
4102            .poll_request_json_unresolved(
4103                "/worker/workflow-tasks/poll",
4104                RequestProtocol::DefaultWorker,
4105                &body,
4106                timeout + Duration::from_secs(5),
4107                transport_retries,
4108            )
4109            .await?;
4110        let claim =
4111            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4112        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4113            self.resolve_runtime_payloads(
4114                &mut wire,
4115                "/worker/workflow-tasks/poll",
4116                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4117            )
4118            .await?;
4119            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4120            if let Some(task) = data.task.as_mut() {
4121                self.fetch_remaining_workflow_history(worker_id, task)
4122                    .await?;
4123            }
4124            Ok(data)
4125        })
4126        .await?;
4127        Ok(data)
4128    }
4129
4130    async fn fetch_remaining_workflow_history(
4131        &self,
4132        worker_id: &str,
4133        task: &mut WorkflowTask,
4134    ) -> Result<()> {
4135        let mut next_token = task.next_history_page_token.clone();
4136        let mut seen = BTreeSet::new();
4137
4138        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4139            if seen.len() >= 128 || !seen.insert(token.clone()) {
4140                return Err(Error::Codec(
4141                    "workflow history pagination exceeded its page bound or repeated a token"
4142                        .into(),
4143                ));
4144            }
4145            let lease_owner = task
4146                .lease_owner
4147                .clone()
4148                .unwrap_or_else(|| worker_id.to_string());
4149            let page = self
4150                .workflow_task_history_page(
4151                    &task.task_id,
4152                    &lease_owner,
4153                    task.workflow_task_attempt,
4154                    &token,
4155                )
4156                .await?;
4157
4158            task.append_history_page(page);
4159
4160            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4161                return Err(Error::Codec(
4162                    "workflow history pagination returned the same page token".to_string(),
4163                ));
4164            }
4165
4166            next_token = task.next_history_page_token.clone();
4167        }
4168
4169        Ok(())
4170    }
4171
4172    async fn workflow_task_history_page(
4173        &self,
4174        task_id: &str,
4175        lease_owner: &str,
4176        workflow_task_attempt: u64,
4177        next_history_page_token: &str,
4178    ) -> Result<WorkflowTaskHistoryPage> {
4179        let body = json!({
4180            "lease_owner": lease_owner,
4181            "workflow_task_attempt": workflow_task_attempt,
4182            "next_history_page_token": next_history_page_token
4183        });
4184        let path = format!("/worker/workflow-tasks/{task_id}/history");
4185
4186        self.request_json(
4187            reqwest::Method::POST,
4188            &path,
4189            RequestProtocol::DefaultWorker,
4190            Some(&body),
4191        )
4192        .await
4193    }
4194
4195    pub async fn complete_workflow_task(
4196        &self,
4197        task_id: &str,
4198        lease_owner: &str,
4199        workflow_task_attempt: u64,
4200        commands: Vec<Value>,
4201    ) -> Result<Value> {
4202        self.complete_workflow_task_with_message_streams(
4203            task_id,
4204            lease_owner,
4205            workflow_task_attempt,
4206            commands,
4207            Vec::new(),
4208            Vec::new(),
4209            None,
4210        )
4211        .await
4212    }
4213
4214    #[allow(clippy::too_many_arguments)]
4215    async fn complete_workflow_task_with_message_streams(
4216        &self,
4217        task_id: &str,
4218        lease_owner: &str,
4219        workflow_task_attempt: u64,
4220        commands: Vec<Value>,
4221        message_stream_cursors: Vec<Value>,
4222        message_stream_waits: Vec<Value>,
4223        sticky_cache: Option<Value>,
4224    ) -> Result<Value> {
4225        validate_workflow_task_commands(&commands)?;
4226        let has_message_stream_metadata =
4227            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4228        if has_message_stream_metadata
4229            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4230        {
4231            return Err(Error::Codec(
4232                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4233                    .to_string(),
4234            ));
4235        }
4236        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4237            &commands,
4238            has_message_stream_metadata,
4239        );
4240        let protocol_version = if sticky_cache.is_some()
4241            && protocol_version
4242                .strip_prefix("1.")
4243                .and_then(|minor| minor.parse::<u64>().ok())
4244                .is_some_and(|minor| minor < 18)
4245        {
4246            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4247        } else {
4248            protocol_version
4249        };
4250        let mut body = json!({
4251            "lease_owner": lease_owner,
4252            "workflow_task_attempt": workflow_task_attempt,
4253            "commands": commands
4254        });
4255        if !message_stream_cursors.is_empty() {
4256            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4257        }
4258        if !message_stream_waits.is_empty() {
4259            body["message_stream_waits"] = Value::Array(message_stream_waits);
4260        }
4261        if let Some(claim) = sticky_cache {
4262            body["sticky_cache"] = claim;
4263        }
4264        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4265        self.request_json(
4266            reqwest::Method::POST,
4267            &path,
4268            RequestProtocol::Worker(protocol_version),
4269            Some(&body),
4270        )
4271        .await
4272    }
4273
4274    pub async fn fail_workflow_task(
4275        &self,
4276        task_id: &str,
4277        lease_owner: &str,
4278        workflow_task_attempt: u64,
4279        message: impl Into<String>,
4280    ) -> Result<Value> {
4281        self.fail_workflow_task_with_type(
4282            task_id,
4283            lease_owner,
4284            workflow_task_attempt,
4285            message,
4286            "RustWorkflowTaskFailure",
4287        )
4288        .await
4289    }
4290
4291    async fn fail_workflow_task_with_type(
4292        &self,
4293        task_id: &str,
4294        lease_owner: &str,
4295        workflow_task_attempt: u64,
4296        message: impl Into<String>,
4297        failure_type: &str,
4298    ) -> Result<Value> {
4299        let body = json!({
4300            "lease_owner": lease_owner,
4301            "workflow_task_attempt": workflow_task_attempt,
4302            "failure": {
4303                "message": message.into(),
4304                "type": failure_type
4305            }
4306        });
4307        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4308        self.request_json(
4309            reqwest::Method::POST,
4310            &path,
4311            RequestProtocol::DefaultWorker,
4312            Some(&body),
4313        )
4314        .await
4315    }
4316
4317    pub async fn poll_activity_task(
4318        &self,
4319        worker_id: &str,
4320        task_queue: &str,
4321        timeout: Duration,
4322    ) -> Result<Option<ActivityTask>> {
4323        Ok(self
4324            .poll_activity_task_response(worker_id, task_queue, timeout)
4325            .await?
4326            .task)
4327    }
4328
4329    /// Poll an activity task while preserving server stop and drain metadata.
4330    pub async fn poll_activity_task_response(
4331        &self,
4332        worker_id: &str,
4333        task_queue: &str,
4334        timeout: Duration,
4335    ) -> Result<PollActivityTaskResponse> {
4336        let poll_request_id = unique_request_id("rust-activity-poll");
4337        self.poll_activity_task_response_with_request_id(
4338            worker_id,
4339            task_queue,
4340            timeout,
4341            &poll_request_id,
4342            1,
4343        )
4344        .await
4345        .map(worker_session::SessionPollResponse::ordinary)
4346    }
4347
4348    async fn poll_activity_task_response_with_request_id(
4349        &self,
4350        worker_id: &str,
4351        task_queue: &str,
4352        timeout: Duration,
4353        poll_request_id: &str,
4354        transport_retries: usize,
4355    ) -> Result<worker_session::SessionPollResponse> {
4356        let body = json!({
4357            "worker_id": worker_id,
4358            "task_queue": task_queue,
4359            "poll_request_id": poll_request_id,
4360            "timeout_seconds": long_poll_timeout_seconds(timeout),
4361        });
4362        let mut wire: Value = self
4363            .poll_request_json_unresolved(
4364                "/worker/activity-tasks/poll",
4365                RequestProtocol::DefaultWorker,
4366                &body,
4367                timeout + Duration::from_secs(5),
4368                transport_retries,
4369            )
4370            .await?;
4371        let claim = activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?;
4372        let mut data: worker_session::SessionPollResponse =
4373            activity_hydration::HydrationClaim::protect(claim.as_ref(), self, async {
4374                self.resolve_runtime_payloads(
4375                    &mut wire,
4376                    "/worker/activity-tasks/poll",
4377                    RequestProtocol::DefaultWorker,
4378                )
4379                .await?;
4380                Ok(serde_json::from_value(wire)?)
4381            })
4382            .await?;
4383        if let Some(task) = data.task.as_mut() {
4384            task.hydration_claim = claim;
4385        }
4386        Ok(data)
4387    }
4388
4389    pub async fn complete_activity_task<T: Serialize>(
4390        &self,
4391        task_id: &str,
4392        activity_attempt_id: &str,
4393        lease_owner: &str,
4394        result: T,
4395        codec: &str,
4396    ) -> Result<Value> {
4397        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4398        let body = json!({
4399            "activity_attempt_id": activity_attempt_id,
4400            "lease_owner": lease_owner,
4401            "result": result
4402        });
4403        let path = format!("/worker/activity-tasks/{task_id}/complete");
4404        activity_task_response(
4405            self.request_json(
4406                reqwest::Method::POST,
4407                &path,
4408                RequestProtocol::DefaultWorker,
4409                Some(&body),
4410            )
4411            .await,
4412            "complete",
4413            task_id,
4414            activity_attempt_id,
4415        )
4416    }
4417
4418    pub async fn fail_activity_task(
4419        &self,
4420        task_id: &str,
4421        activity_attempt_id: &str,
4422        lease_owner: &str,
4423        message: impl Into<String>,
4424        non_retryable: bool,
4425    ) -> Result<Value> {
4426        let body = json!({
4427            "activity_attempt_id": activity_attempt_id,
4428            "lease_owner": lease_owner,
4429            "failure": {
4430                "message": message.into(),
4431                "type": "RustActivityFailure",
4432                "non_retryable": non_retryable
4433            }
4434        });
4435        let path = format!("/worker/activity-tasks/{task_id}/fail");
4436        activity_task_response(
4437            self.request_json(
4438                reqwest::Method::POST,
4439                &path,
4440                RequestProtocol::DefaultWorker,
4441                Some(&body),
4442            )
4443            .await,
4444            "fail",
4445            task_id,
4446            activity_attempt_id,
4447        )
4448    }
4449
4450    /// Record a flat map of scalar/null activity progress metadata.
4451    ///
4452    /// Heartbeat details use the Server's bounded JSON progress contract.
4453    /// They are not workflow payload envelopes.
4454    pub async fn heartbeat_activity_task<T: Serialize>(
4455        &self,
4456        task_id: &str,
4457        activity_attempt_id: &str,
4458        lease_owner: &str,
4459        details: T,
4460    ) -> Result<ActivityHeartbeatResponse> {
4461        serde_json::from_value(
4462            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4463                .await?,
4464        )
4465        .map_err(Error::from)
4466    }
4467
4468    async fn heartbeat_activity_task_value<T: Serialize>(
4469        &self,
4470        task_id: &str,
4471        activity_attempt_id: &str,
4472        lease_owner: &str,
4473        details: T,
4474    ) -> Result<Value> {
4475        let details = AvroValue::from_serialize(&details)?.into_json()?;
4476        let body = json!({
4477            "activity_attempt_id": activity_attempt_id,
4478            "lease_owner": lease_owner,
4479            "details": details
4480        });
4481        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4482        activity_task_response(
4483            self.request_json(
4484                reqwest::Method::POST,
4485                &path,
4486                RequestProtocol::DefaultWorker,
4487                Some(&body),
4488            )
4489            .await,
4490            "heartbeat",
4491            task_id,
4492            activity_attempt_id,
4493        )
4494    }
4495
4496    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4497        &self,
4498        method: reqwest::Method,
4499        path: &str,
4500        protocol: RequestProtocol,
4501        body: Option<&B>,
4502    ) -> Result<T> {
4503        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4504            .await
4505    }
4506
4507    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4508        &self,
4509        method: reqwest::Method,
4510        path: &str,
4511        protocol: RequestProtocol,
4512        body: Option<&B>,
4513        timeout: Duration,
4514    ) -> Result<T> {
4515        let mut value: Value = self
4516            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4517            .await?;
4518        let protocol = match protocol {
4519            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4520                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4521            }
4522            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4523        };
4524        self.resolve_runtime_payloads(&mut value, path, protocol)
4525            .await?;
4526        Ok(serde_json::from_value(value)?)
4527    }
4528
4529    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4530        &self,
4531        method: reqwest::Method,
4532        path: &str,
4533        protocol: RequestProtocol,
4534        body: Option<&B>,
4535        timeout: Duration,
4536    ) -> Result<T> {
4537        let protocol = match protocol {
4538            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4539                let selected = self.worker_protocol_version.as_str();
4540                if self.cooperative_worker_protocol
4541                    && !cooperative_cancellation::supports_protocol(selected)
4542                {
4543                    return Err(Error::CooperativeCancellationUnavailable(
4544                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4545                    ));
4546                }
4547                if let RequestProtocol::Worker(minimum) = protocol {
4548                    let supported = minimum
4549                        .strip_prefix("1.")
4550                        .and_then(|minor| minor.parse::<u64>().ok())
4551                        .zip(
4552                            selected
4553                                .strip_prefix("1.")
4554                                .and_then(|minor| minor.parse::<u64>().ok()),
4555                        )
4556                        .is_some_and(|(minimum, selected)| selected >= minimum);
4557                    if !supported {
4558                        return Err(Error::WorkerLoop(format!(
4559                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4560                        )));
4561                    }
4562                }
4563                RequestProtocol::Worker(selected)
4564            }
4565            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4566        };
4567        let auth_token = self.auth_token(protocol)?;
4568        let mut request = self
4569            .http
4570            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4571            .timeout(timeout)
4572            .header(reqwest::header::ACCEPT, "application/json")
4573            .header(reqwest::header::CONTENT_TYPE, "application/json")
4574            .header("X-Namespace", &self.namespace);
4575
4576        match protocol {
4577            RequestProtocol::DefaultWorker => {
4578                request = request.header(
4579                    "X-Durable-Workflow-Protocol-Version",
4580                    self.worker_protocol_version.as_str(),
4581                );
4582            }
4583            RequestProtocol::Worker(version) => {
4584                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4585            }
4586            RequestProtocol::ControlPlane => {
4587                request = request.header(
4588                    "X-Durable-Workflow-Control-Plane-Version",
4589                    CONTROL_PLANE_VERSION,
4590                );
4591            }
4592        }
4593
4594        if let Some(token) = auth_token {
4595            request = request.bearer_auth(token);
4596        }
4597
4598        if let Some(body) = body {
4599            let mut body = serde_json::to_value(body)?;
4600            if matches!(
4601                method,
4602                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4603            ) {
4604                self.externalize_runtime_payloads(&mut body, path, protocol)
4605                    .await?;
4606            }
4607            request = request.json(&body);
4608        }
4609
4610        let request = request.build()?;
4611        let request_body = request
4612            .body()
4613            .and_then(reqwest::Body::as_bytes)
4614            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4615        let poll_request_id = path.ends_with("/poll").then(|| {
4616            request_body
4617                .as_ref()
4618                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4619                .unwrap_or_default()
4620        });
4621        let mut storage_retries = 0_usize;
4622        let mut deferred_workflow_completion = false;
4623
4624        loop {
4625            // Keep the serialized body and lease/poll identity across admission pauses.
4626            let receive = async {
4627                let response = self
4628                    .http
4629                    .execute(request.try_clone().ok_or_else(|| {
4630                        Error::WorkerLoop("worker request body cannot be retried".to_string())
4631                    })?)
4632                    .await?;
4633                let status = response.status();
4634                Ok::<_, Error>((status, response.bytes().await?))
4635            };
4636            let retry_deadline = self
4637                .worker_storage_admission
4638                .as_ref()
4639                .and_then(|admission| admission.workflow_completion_retry_deadline);
4640            if deferred_workflow_completion
4641                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
4642            {
4643                return Err(Error::Timeout);
4644            }
4645            let (status, bytes) = match retry_deadline.filter(|_| deferred_workflow_completion) {
4646                Some(deadline) => tokio::time::timeout_at(deadline, receive)
4647                    .await
4648                    .map_err(|_| Error::Timeout)??,
4649                None => receive.await?,
4650            };
4651
4652            if !status.is_success() {
4653                let body = String::from_utf8_lossy(&bytes).to_string();
4654                if let Some(protocol) = protocol_failure(status, &body) {
4655                    return Err(Error::Protocol(protocol));
4656                }
4657                let error = Error::Http { status, body };
4658                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
4659                    &error,
4660                    path,
4661                    request_body.as_ref(),
4662                )
4663                .is_some();
4664                if self
4665                    .wait_for_storage_admission(
4666                        &error,
4667                        protocol,
4668                        Some(path),
4669                        poll_request_id.as_deref(),
4670                        request_body.as_ref(),
4671                        &mut storage_retries,
4672                    )
4673                    .await
4674                {
4675                    continue;
4676                }
4677                return Err(error);
4678            }
4679
4680            if bytes.is_empty() {
4681                return Ok(serde_json::from_value(Value::Null)?);
4682            }
4683
4684            return Ok(serde_json::from_slice(&bytes)?);
4685        }
4686    }
4687
4688    async fn wait_for_storage_admission(
4689        &self,
4690        error: &Error,
4691        protocol: RequestProtocol,
4692        path: Option<&str>,
4693        poll_request_id: Option<&str>,
4694        request_body: Option<&Value>,
4695        retries: &mut usize,
4696    ) -> bool {
4697        let Some(admission) = self
4698            .worker_storage_admission
4699            .as_ref()
4700            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4701        else {
4702            return false;
4703        };
4704        let completion_deferred = path.and_then(|path| {
4705            worker_deferred_workflow_completion_retry_after(error, path, request_body)
4706        });
4707        let Some(advertised_delay) = completion_deferred
4708            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
4709            .or_else(|| {
4710                path.and_then(|path| {
4711                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4712                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4713                })
4714            })
4715        else {
4716            return false;
4717        };
4718        *retries = retries.saturating_add(1);
4719        let delay = worker_retry_delay(admission.policy, *retries)
4720            .max(advertised_delay)
4721            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4722        let delay = if completion_deferred.is_some() {
4723            delay.max(advertised_delay)
4724        } else {
4725            delay
4726        };
4727        let wait_deadline = tokio::time::Instant::now() + delay;
4728        loop {
4729            if admission.stop.load(Ordering::SeqCst) {
4730                return false;
4731            }
4732            let now = tokio::time::Instant::now();
4733            if admission
4734                .workflow_completion_retry_deadline
4735                .is_some_and(|deadline| now >= deadline)
4736            {
4737                return false;
4738            }
4739            let remaining = wait_deadline.saturating_duration_since(now);
4740            if remaining.is_zero() {
4741                return true;
4742            }
4743            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4744        }
4745    }
4746
4747    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4748        &self,
4749        path: &str,
4750        protocol: RequestProtocol,
4751        body: &B,
4752        timeout: Duration,
4753        max_retries: usize,
4754    ) -> Result<T> {
4755        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
4756            .await
4757    }
4758
4759    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
4760        &self,
4761        path: &str,
4762        protocol: RequestProtocol,
4763        body: &B,
4764        timeout: Duration,
4765        max_retries: usize,
4766    ) -> Result<T> {
4767        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
4768            .await
4769    }
4770
4771    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
4772        &self,
4773        path: &str,
4774        protocol: RequestProtocol,
4775        body: &B,
4776        timeout: Duration,
4777        max_retries: usize,
4778        resolve: bool,
4779    ) -> Result<T> {
4780        let mut retries = 0;
4781
4782        loop {
4783            let response = if resolve {
4784                self.request_json_with_timeout(
4785                    reqwest::Method::POST,
4786                    path,
4787                    protocol,
4788                    Some(body),
4789                    timeout,
4790                )
4791                .await
4792            } else {
4793                self.request_json_unresolved_with_timeout(
4794                    reqwest::Method::POST,
4795                    path,
4796                    protocol,
4797                    Some(body),
4798                    timeout,
4799                )
4800                .await
4801            };
4802
4803            match response {
4804                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4805                response => return worker_poll_response(response),
4806            }
4807        }
4808    }
4809
4810    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4811        match protocol {
4812            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4813                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4814                    return Ok(Some(token));
4815                }
4816                if self.control_token.is_some() {
4817                    return Err(Error::MissingRoleCredentials {
4818                        role: "worker",
4819                        opposite_role: "control",
4820                    });
4821                }
4822                Ok(None)
4823            }
4824            RequestProtocol::ControlPlane => {
4825                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4826                    return Ok(Some(token));
4827                }
4828                if self.worker_token.is_some() {
4829                    return Err(Error::MissingRoleCredentials {
4830                        role: "control",
4831                        opposite_role: "worker",
4832                    });
4833                }
4834                Ok(None)
4835            }
4836        }
4837    }
4838}
4839
4840fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4841    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4842    let reason = body
4843        .get("reason")
4844        .and_then(Value::as_str)
4845        .unwrap_or("query_rejected")
4846        .to_string();
4847    let message = body
4848        .get("message")
4849        .or_else(|| body.get("error"))
4850        .and_then(Value::as_str)
4851        .unwrap_or("workflow query was rejected")
4852        .to_string();
4853
4854    QueryFailure {
4855        status: status.as_u16(),
4856        reason,
4857        message,
4858        body,
4859    }
4860}
4861
4862fn workflow_command_result(
4863    command: WorkflowCommandKind,
4864    data: Value,
4865    workflow_id: &str,
4866    run_id: Option<&str>,
4867) -> WorkflowCommandResult {
4868    WorkflowCommandResult {
4869        command,
4870        workflow_id: data
4871            .get("workflow_id")
4872            .and_then(Value::as_str)
4873            .unwrap_or(workflow_id)
4874            .to_string(),
4875        run_id: data
4876            .get("run_id")
4877            .and_then(Value::as_str)
4878            .or(run_id)
4879            .map(str::to_string),
4880        outcome: data
4881            .get("outcome")
4882            .and_then(Value::as_str)
4883            .map(str::to_string),
4884        reason: data
4885            .get("reason")
4886            .and_then(Value::as_str)
4887            .map(str::to_string),
4888        command_status: data
4889            .get("command_status")
4890            .and_then(Value::as_str)
4891            .map(str::to_string),
4892        raw: data,
4893    }
4894}
4895
4896fn workflow_command_rejection(
4897    command: WorkflowCommandKind,
4898    status: reqwest::StatusCode,
4899    raw_body: String,
4900    workflow_id: &str,
4901    run_id: Option<&str>,
4902) -> WorkflowCommandRejection {
4903    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4904    WorkflowCommandRejection {
4905        command,
4906        status: status.as_u16(),
4907        reason: body
4908            .get("reason")
4909            .and_then(Value::as_str)
4910            .unwrap_or("workflow_command_rejected")
4911            .to_string(),
4912        message: body
4913            .get("message")
4914            .or_else(|| body.get("error"))
4915            .and_then(Value::as_str)
4916            .unwrap_or("workflow lifecycle command was rejected")
4917            .to_string(),
4918        workflow_id: body
4919            .get("workflow_id")
4920            .and_then(Value::as_str)
4921            .unwrap_or(workflow_id)
4922            .to_string(),
4923        run_id: body
4924            .get("run_id")
4925            .and_then(Value::as_str)
4926            .or(run_id)
4927            .map(str::to_string),
4928        target_scope: body
4929            .get("target_scope")
4930            .and_then(Value::as_str)
4931            .map(str::to_string),
4932        body,
4933    }
4934}
4935
4936fn query_task_response(response: Result<Value>) -> Result<Value> {
4937    match response {
4938        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4939        response => response,
4940    }
4941}
4942
4943fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4944    match response {
4945        Err(Error::Http { status, body })
4946            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
4947        {
4948            Ok(serde_json::from_str(&body)?)
4949        }
4950        response => response,
4951    }
4952}
4953
4954fn worker_poll_body_is_stop(body: &str) -> bool {
4955    serde_json::from_str::<Value>(body)
4956        .ok()
4957        .is_some_and(|body| {
4958            worker_poll_is_stop(
4959                body.get("poll_status").and_then(Value::as_str),
4960                body.get("reason").and_then(Value::as_str),
4961            )
4962        })
4963}
4964
4965fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
4966    matches!(poll_status, Some("draining" | "stopped"))
4967        || matches!(reason, Some("worker_draining" | "worker_stopped"))
4968}
4969
4970fn query_task_rejection_is_final(error: &Error) -> bool {
4971    matches!(
4972        error,
4973        Error::QueryFailed(failure)
4974            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
4975    )
4976}
4977
4978fn activity_task_response<T>(
4979    response: Result<T>,
4980    operation: &str,
4981    task_id: &str,
4982    activity_attempt_id: &str,
4983) -> Result<T> {
4984    match response {
4985        Err(Error::Http { status, body }) => {
4986            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
4987            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
4988                operation: operation.to_string(),
4989                status: status.as_u16(),
4990                reason: body
4991                    .get("reason")
4992                    .and_then(Value::as_str)
4993                    .unwrap_or("activity_task_rejected")
4994                    .to_string(),
4995                task_id: body
4996                    .get("task_id")
4997                    .and_then(Value::as_str)
4998                    .unwrap_or(task_id)
4999                    .to_string(),
5000                activity_attempt_id: body
5001                    .get("activity_attempt_id")
5002                    .and_then(Value::as_str)
5003                    .unwrap_or(activity_attempt_id)
5004                    .to_string(),
5005                cancel_requested: body
5006                    .get("cancel_requested")
5007                    .and_then(Value::as_bool)
5008                    .unwrap_or(false),
5009                can_continue: body.get("can_continue").and_then(Value::as_bool),
5010                run_closed_reason: body
5011                    .get("run_closed_reason")
5012                    .and_then(Value::as_str)
5013                    .map(str::to_string),
5014                body,
5015            }))
5016        }
5017        response => response,
5018    }
5019}
5020
5021fn activity_task_rejection_is_final(error: &Error) -> bool {
5022    matches!(
5023        error,
5024        Error::ActivityTaskRejected(rejection)
5025            if matches!(
5026                rejection.reason.as_str(),
5027                "run_cancelled"
5028                    | "run_terminated"
5029                    | "attempt_closed"
5030                    | "stale_attempt"
5031                    | "activity_cancelled"
5032                    | "task_cancelled"
5033                    | "run_closed"
5034                    | "activity_not_running"
5035                    | "attempt_not_found"
5036            )
5037    )
5038}
5039
5040fn workflow_task_completion_is_terminal_timeout(
5041    error: &Error,
5042    task_id: &str,
5043    workflow_task_attempt: u64,
5044    run_id: Option<&str>,
5045) -> bool {
5046    let Error::Http { status, body } = error else {
5047        return false;
5048    };
5049    if *status != reqwest::StatusCode::CONFLICT {
5050        return false;
5051    }
5052
5053    let Some(run_id) = run_id else {
5054        return false;
5055    };
5056    let Ok(body) = serde_json::from_str::<Value>(body) else {
5057        return false;
5058    };
5059
5060    body.get("recorded").and_then(Value::as_bool) == Some(false)
5061        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5062        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5063        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5064        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5065        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5066}
5067
5068fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5069    let body: Value = serde_json::from_str(raw_body).ok()?;
5070    let reason = body.get("reason")?.as_str()?;
5071    if !matches!(
5072        reason,
5073        "missing_protocol_version"
5074            | "unsupported_protocol_version"
5075            | "missing_control_plane_version"
5076            | "unsupported_control_plane_version"
5077    ) {
5078        return None;
5079    }
5080
5081    Some(ProtocolFailure {
5082        status: status.as_u16(),
5083        reason: reason.to_string(),
5084        message: body
5085            .get("message")
5086            .or_else(|| body.get("error"))
5087            .and_then(Value::as_str)
5088            .unwrap_or("protocol version rejected")
5089            .to_string(),
5090        supported_version: body
5091            .get("supported_version")
5092            .and_then(Value::as_str)
5093            .map(str::to_string),
5094        requested_version: body
5095            .get("requested_version")
5096            .and_then(Value::as_str)
5097            .map(str::to_string),
5098        body,
5099    })
5100}
5101
5102fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5103    timeout
5104        .as_secs()
5105        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5106        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5107}
5108
5109fn worker_operation_is_retryable(error: &Error) -> bool {
5110    if worker_poll_capacity_retry_after(error).is_some()
5111        || worker_storage_admission_body(error).is_some()
5112        || worker_backend_unavailable_body(error).is_some()
5113        || worker_operation_is_explicitly_non_retryable(error)
5114    {
5115        return false;
5116    }
5117
5118    match error {
5119        Error::Transport(error) => {
5120            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5121        }
5122        Error::Http { status, .. } => {
5123            matches!(
5124                *status,
5125                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5126            ) || status.is_server_error()
5127        }
5128        _ => false,
5129    }
5130}
5131
5132fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5133    let body: Value = match error {
5134        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5135        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5136        _ => return None,
5137    };
5138    matches!(
5139        body.get("reason").and_then(Value::as_str),
5140        Some("storage_pressure" | "storage_admission_unavailable")
5141    )
5142    .then_some(body)
5143}
5144
5145fn worker_storage_admission_retry_after(
5146    error: &Error,
5147    poll_request_id: Option<&str>,
5148) -> Option<Duration> {
5149    let Error::Http { status, .. } = error else {
5150        return None;
5151    };
5152    let body = worker_storage_admission_body(error)?;
5153    let delay = body.get("retry_after_seconds")?.as_u64()?;
5154    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5155        || delay == 0
5156        || body.get("retryable") != Some(&Value::Bool(true))
5157        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5158        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5159        || body
5160            .get("request_admitted")
5161            .is_some_and(|admitted| admitted != &Value::Bool(false))
5162    {
5163        return None;
5164    }
5165    match poll_request_id {
5166        Some(id) => {
5167            if id.is_empty()
5168                || body.get("task") != Some(&Value::Null)
5169                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5170                || body.get("poll_status") != body.get("reason")
5171                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5172                || body.get("claim_admitted") != Some(&Value::Bool(false))
5173            {
5174                return None;
5175            }
5176        }
5177        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5178        None => {}
5179    }
5180    Some(Duration::from_secs(delay))
5181}
5182
5183fn worker_backend_unavailable_retry_after(
5184    error: &Error,
5185    path: &str,
5186    poll_request_id: Option<&str>,
5187) -> Option<Duration> {
5188    let operation = match path {
5189        "/worker/register" => "register_worker",
5190        "/worker/heartbeat" => "heartbeat_worker",
5191        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5192        "/worker/activity-tasks/poll" => "poll_activity_task",
5193        "/worker/query-tasks/poll" => "poll_query_task",
5194        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5195        _ => return None,
5196    };
5197    let body = worker_backend_unavailable_body(error)?;
5198    let delay = body.get("retry_after_seconds")?.as_u64()?;
5199    if delay == 0
5200        || body.get("operation")?.as_str()? != operation
5201        || body.get("outcome")?.as_str()? != "unknown"
5202        || body.get("retryable") != Some(&Value::Bool(true))
5203        || body.get("worker_id")?.as_str()?.is_empty()
5204    {
5205        return None;
5206    }
5207    if let Some(id) = poll_request_id {
5208        if id.is_empty()
5209            || body.get("task") != Some(&Value::Null)
5210            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5211            || body.get("poll_request_id")?.as_str()? != id
5212            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5213        {
5214            return None;
5215        }
5216    } else if path.ends_with("/poll") {
5217        return None;
5218    }
5219    Some(Duration::from_secs(delay))
5220}
5221
5222fn worker_fenced_completion_retry_after(
5223    error: &Error,
5224    path: &str,
5225    request_body: Option<&Value>,
5226) -> Option<Duration> {
5227    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5228        .strip_prefix("/worker/workflow-tasks/")
5229        .and_then(|tail| tail.strip_suffix("/complete"))
5230    {
5231        ("complete_workflow_task", task_id, "workflow_task_attempt")
5232    } else if let Some(task_id) = path
5233        .strip_prefix("/worker/activity-tasks/")
5234        .and_then(|tail| tail.strip_suffix("/complete"))
5235    {
5236        ("complete_activity_task", task_id, "activity_attempt_id")
5237    } else {
5238        return None;
5239    };
5240    if task_id.is_empty() || task_id.contains('/') {
5241        return None;
5242    }
5243
5244    let request = request_body?.as_object()?;
5245    let lease_owner = request.get("lease_owner")?.as_str()?;
5246    if lease_owner.is_empty() {
5247        return None;
5248    }
5249    let attempt = request.get(attempt_field)?;
5250    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5251        || (attempt_field == "activity_attempt_id"
5252            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5253    {
5254        return None;
5255    }
5256
5257    let body = worker_backend_unavailable_body(error)?;
5258    let delay = body.get("retry_after_seconds")?.as_u64()?;
5259    if delay == 0
5260        || body.get("operation")?.as_str()? != operation
5261        || body.get("outcome")?.as_str()? != "unknown"
5262        || body.get("retryable") != Some(&Value::Bool(true))
5263        || body.get("worker_id")?.as_str()? != lease_owner
5264        || body.get("task_queue") != Some(&Value::Null)
5265        || body.get("task_id")?.as_str()? != task_id
5266        || body.get("lease_owner")?.as_str()? != lease_owner
5267        || body.get(attempt_field) != Some(attempt)
5268    {
5269        return None;
5270    }
5271
5272    Some(Duration::from_secs(delay))
5273}
5274
5275fn worker_deferred_workflow_completion_retry_after(
5276    error: &Error,
5277    path: &str,
5278    request_body: Option<&Value>,
5279) -> Option<Duration> {
5280    let task_id = path
5281        .strip_prefix("/worker/workflow-tasks/")?
5282        .strip_suffix("/complete")?;
5283    if task_id.is_empty() || task_id.contains('/') {
5284        return None;
5285    }
5286    let request = request_body?.as_object()?;
5287    let owner = request.get("lease_owner")?.as_str()?;
5288    let attempt = request.get("workflow_task_attempt")?;
5289    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
5290        return None;
5291    }
5292    let Error::Http { status, body } = error else {
5293        return None;
5294    };
5295    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5296        return None;
5297    }
5298    let body: Value = serde_json::from_str(body).ok()?;
5299    let delay = body.get("retry_after_seconds")?.as_u64()?;
5300    if !(1..=5).contains(&delay)
5301        || body.get("reason")?.as_str()? != "backend_lock_pressure"
5302        || body.get("operation")?.as_str()? != "complete_workflow_task"
5303        || body.get("outcome")?.as_str()? != "deferred"
5304        || body.get("recorded") != Some(&Value::Bool(false))
5305        || body.get("retryable") != Some(&Value::Bool(true))
5306        || body.get("task_id")?.as_str()? != task_id
5307        || body.get("lease_owner")?.as_str()? != owner
5308        || body.get("workflow_task_attempt") != Some(attempt)
5309        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
5310    {
5311        return None;
5312    }
5313    Some(Duration::from_secs(delay))
5314}
5315
5316fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5317    let Error::Http { status, body } = error else {
5318        return None;
5319    };
5320    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5321        return None;
5322    }
5323    let body: Value = serde_json::from_str(body).ok()?;
5324    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5325}
5326
5327fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5328    let Error::Http { body, .. } = error else {
5329        return false;
5330    };
5331
5332    serde_json::from_str::<Value>(body)
5333        .ok()
5334        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5335        == Some(false)
5336}
5337
5338fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5339    let Error::Http { status, body } = error else {
5340        return None;
5341    };
5342    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5343        return None;
5344    }
5345
5346    let body = serde_json::from_str::<Value>(body).ok()?;
5347    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5348        == Some("long_poll_capacity_exhausted")
5349        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5350    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5351        return None;
5352    }
5353
5354    Some(Duration::from_secs(
5355        body.get("retry_after_seconds")
5356            .and_then(Value::as_u64)
5357            .unwrap_or_default(),
5358    ))
5359}
5360
5361fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5362    let exponent = retry.saturating_sub(1).min(31) as u32;
5363    policy
5364        .initial_backoff
5365        .saturating_mul(1_u32 << exponent)
5366        .min(policy.max_backoff)
5367}
5368
5369#[derive(Debug)]
5370pub struct ClientBuilder {
5371    base_url: String,
5372    token: Option<String>,
5373    control_token: Option<String>,
5374    worker_token: Option<String>,
5375    namespace: String,
5376    timeout: Duration,
5377    max_external_payload_bytes: usize,
5378    worker_protocol_version: WorkerProtocolVersion,
5379}
5380
5381impl ClientBuilder {
5382    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5383    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5384        self.worker_protocol_version = version;
5385        self
5386    }
5387
5388    pub fn token(mut self, token: Option<String>) -> Self {
5389        self.token = token;
5390        self
5391    }
5392
5393    pub fn control_token(mut self, token: Option<String>) -> Self {
5394        self.control_token = token;
5395        self
5396    }
5397
5398    pub fn worker_token(mut self, token: Option<String>) -> Self {
5399        self.worker_token = token;
5400        self
5401    }
5402
5403    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5404        self.namespace = namespace.into();
5405        self
5406    }
5407
5408    pub fn timeout(mut self, timeout: Duration) -> Self {
5409        self.timeout = timeout;
5410        self
5411    }
5412
5413    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5414    /// References are fetched only from this client's authenticated runtime.
5415    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5416        self.max_external_payload_bytes = bytes;
5417        self
5418    }
5419
5420    pub fn build(self) -> Result<Client> {
5421        let base_url = self.base_url.trim_end_matches('/').to_string();
5422        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5423            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5424            .unwrap_or_else(|_| base_url.ends_with("/api"));
5425
5426        if has_sdk_api_suffix {
5427            return Err(Error::InvalidBaseUrl);
5428        }
5429
5430        Ok(Client {
5431            http: reqwest::Client::builder()
5432                .timeout(self.timeout)
5433                .redirect(reqwest::redirect::Policy::none())
5434                .build()?,
5435            hydration_timeout: self.timeout,
5436            base_url,
5437            token: self.token,
5438            control_token: self.control_token,
5439            worker_token: self.worker_token,
5440            namespace: self.namespace,
5441            max_external_payload_bytes: self.max_external_payload_bytes,
5442            worker_storage_admission: None,
5443            cooperative_worker_protocol: false,
5444            worker_protocol_version: self.worker_protocol_version,
5445            local_activities_enabled: false,
5446            worker_sessions_enabled: false,
5447            max_concurrent_worker_sessions: 10,
5448            worker_build_id: None,
5449            sticky_cache: None,
5450            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5451        })
5452    }
5453}
5454
5455#[derive(Clone, Debug)]
5456pub struct WorkflowHandle {
5457    client: Client,
5458    pub workflow_id: String,
5459    pub run_id: Option<String>,
5460    pub workflow_type: String,
5461}
5462
5463impl WorkflowHandle {
5464    /// Describe whichever run is current for this stable workflow instance.
5465    pub async fn describe(&self) -> Result<WorkflowDescription> {
5466        self.client.describe_workflow(&self.workflow_id).await
5467    }
5468
5469    /// Describe the run identity originally selected by this handle.
5470    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5471        let run_id = self.run_id.as_deref().ok_or_else(|| {
5472            Error::Codec("run_id is required for selected-run description".to_string())
5473        })?;
5474        self.client
5475            .describe_workflow_run(&self.workflow_id, run_id)
5476            .await
5477    }
5478
5479    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5480        self.client
5481            .signal_workflow(&self.workflow_id, signal_name, input)
5482            .await
5483    }
5484
5485    pub async fn append_message<T: Serialize>(
5486        &self,
5487        stream_name: &str,
5488        message_id: &str,
5489        input: T,
5490    ) -> Result<Value> {
5491        self.client
5492            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5493            .await
5494    }
5495
5496    /// Signal only if this handle's selected run is still current.
5497    pub async fn signal_selected_run<T: Serialize>(
5498        &self,
5499        signal_name: &str,
5500        input: T,
5501    ) -> Result<Value> {
5502        let run_id = self.run_id.as_deref().ok_or_else(|| {
5503            Error::Codec("run_id is required for selected-run signaling".to_string())
5504        })?;
5505        self.client
5506            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5507            .await
5508    }
5509
5510    /// Close whichever run is current as cancelled, without workflow cleanup.
5511    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5512        self.client
5513            .cancel_workflow(&self.workflow_id, options)
5514            .await
5515    }
5516
5517    /// Request cancellation only if this handle's selected run is still current.
5518    pub async fn cancel_selected_run(
5519        &self,
5520        options: WorkflowCommandOptions,
5521    ) -> Result<WorkflowCommandResult> {
5522        let run_id = self.run_id.as_deref().ok_or_else(|| {
5523            Error::Codec("run_id is required for selected-run cancellation".to_string())
5524        })?;
5525        self.client
5526            .cancel_workflow_run(&self.workflow_id, run_id, options)
5527            .await
5528    }
5529
5530    /// Forcefully terminate whichever run is current.
5531    pub async fn terminate(
5532        &self,
5533        options: WorkflowCommandOptions,
5534    ) -> Result<WorkflowCommandResult> {
5535        self.client
5536            .terminate_workflow(&self.workflow_id, options)
5537            .await
5538    }
5539
5540    /// Terminate only if this handle's selected run is still current.
5541    pub async fn terminate_selected_run(
5542        &self,
5543        options: WorkflowCommandOptions,
5544    ) -> Result<WorkflowCommandResult> {
5545        let run_id = self.run_id.as_deref().ok_or_else(|| {
5546            Error::Codec("run_id is required for selected-run termination".to_string())
5547        })?;
5548        self.client
5549            .terminate_workflow_run(&self.workflow_id, run_id, options)
5550            .await
5551    }
5552
5553    /// Continue this handle's failed run without repeating completed activities.
5554    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5555        let run_id = self
5556            .run_id
5557            .as_deref()
5558            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5559        self.client
5560            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5561            .await
5562    }
5563
5564    /// Execute a named, read-only query against this workflow.
5565    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5566        self.client
5567            .query_workflow(&self.workflow_id, query_name, input)
5568            .await
5569    }
5570
5571    pub async fn query_avro_value<T: Serialize>(
5572        &self,
5573        query_name: &str,
5574        input: T,
5575    ) -> Result<AvroValue> {
5576        self.client
5577            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5578            .await
5579    }
5580
5581    pub async fn update<T: Serialize>(
5582        &self,
5583        update_name: &str,
5584        input: T,
5585        request_id: Option<&str>,
5586    ) -> Result<Value> {
5587        self.client
5588            .update_workflow(&self.workflow_id, update_name, input, request_id)
5589            .await
5590    }
5591
5592    pub async fn update_avro_value<T: Serialize>(
5593        &self,
5594        update_name: &str,
5595        input: T,
5596        request_id: Option<&str>,
5597    ) -> Result<AvroValue> {
5598        self.client
5599            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5600            .await
5601    }
5602
5603    /// Query only if this handle's selected run is still current.
5604    pub async fn query_selected_run<T: Serialize>(
5605        &self,
5606        query_name: &str,
5607        input: T,
5608    ) -> Result<Value> {
5609        let run_id = self
5610            .run_id
5611            .as_deref()
5612            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5613        self.client
5614            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5615            .await
5616    }
5617
5618    /// Await the final terminal outcome of the current continue-as-new chain.
5619    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5620        self.result_target(options, None).await
5621    }
5622
5623    /// Await the final result without projecting Avro bytes through JSON.
5624    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5625        self.result_avro_value_target(options, None).await
5626    }
5627
5628    /// Await the final result and decode it into a Serde application type.
5629    pub async fn result_typed<T: DeserializeOwned>(
5630        &self,
5631        options: WorkflowResultOptions,
5632    ) -> Result<T> {
5633        let result = self.result_avro_value(options).await?;
5634        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5635    }
5636
5637    /// Await only the run identity originally selected by this handle.
5638    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5639        let run_id = self.run_id.as_deref().ok_or_else(|| {
5640            Error::Codec("run_id is required for selected-run result".to_string())
5641        })?;
5642        self.result_target(options, Some(run_id)).await
5643    }
5644
5645    /// Await the selected run's result on the lossless Avro Value surface.
5646    pub async fn result_selected_run_avro_value(
5647        &self,
5648        options: WorkflowResultOptions,
5649    ) -> Result<AvroValue> {
5650        let run_id = self.run_id.as_deref().ok_or_else(|| {
5651            Error::Codec("run_id is required for selected-run result".to_string())
5652        })?;
5653        self.result_avro_value_target(options, Some(run_id)).await
5654    }
5655
5656    /// Await the selected run and decode its result into a Serde type.
5657    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5658        &self,
5659        options: WorkflowResultOptions,
5660    ) -> Result<T> {
5661        let result = self.result_selected_run_avro_value(options).await?;
5662        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5663    }
5664
5665    async fn result_avro_value_target(
5666        &self,
5667        options: WorkflowResultOptions,
5668        selected_run_id: Option<&str>,
5669    ) -> Result<AvroValue> {
5670        let started = Instant::now();
5671
5672        loop {
5673            let description = match selected_run_id {
5674                Some(run_id) => {
5675                    self.client
5676                        .describe_workflow_run(&self.workflow_id, run_id)
5677                        .await?
5678                }
5679                None => self.describe().await?,
5680            };
5681            if description.is_completed() {
5682                return description.output_avro_value.ok_or_else(|| {
5683                    Error::Codec(
5684                        "missing_payload_envelope: typed workflow result requires output_envelope"
5685                            .to_string(),
5686                    )
5687                });
5688            }
5689            if description.is_terminal() {
5690                let outcome =
5691                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5692                return Err(match outcome.kind {
5693                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5694                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5695                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5696                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5697                });
5698            }
5699            if started.elapsed() >= options.timeout {
5700                return Err(Error::Timeout);
5701            }
5702            tokio::time::sleep(options.poll_interval).await;
5703        }
5704    }
5705
5706    async fn result_target(
5707        &self,
5708        options: WorkflowResultOptions,
5709        selected_run_id: Option<&str>,
5710    ) -> Result<Value> {
5711        let started = Instant::now();
5712
5713        loop {
5714            let description = match selected_run_id {
5715                Some(run_id) => {
5716                    self.client
5717                        .describe_workflow_run(&self.workflow_id, run_id)
5718                        .await?
5719                }
5720                None => self.describe().await?,
5721            };
5722            if description.is_completed() {
5723                return Ok(description.output.unwrap_or(Value::Null));
5724            }
5725
5726            if description.is_terminal() {
5727                let outcome =
5728                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5729                return Err(match outcome.kind {
5730                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5731                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5732                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5733                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5734                });
5735            }
5736
5737            if started.elapsed() >= options.timeout {
5738                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5739                    kind: WorkflowTerminalKind::TimedOut,
5740                    workflow_id: description
5741                        .workflow_id
5742                        .clone()
5743                        .unwrap_or_else(|| self.workflow_id.clone()),
5744                    run_id: description
5745                        .run_id
5746                        .clone()
5747                        .or_else(|| selected_run_id.map(str::to_string)),
5748                    reason: "result_wait_timeout".to_string(),
5749                    failure_category: Some("client_timeout".to_string()),
5750                    failure_id: None,
5751                    exception_type: None,
5752                    exception_class: None,
5753                    non_retryable: None,
5754                    message: Some(format!(
5755                        "workflow result was not terminal within {:?}",
5756                        options.timeout
5757                    )),
5758                    exception: None,
5759                    raw: description.raw_value(),
5760                }));
5761            }
5762
5763            tokio::time::sleep(options.poll_interval).await;
5764        }
5765    }
5766}
5767
5768#[derive(Clone, Copy, Debug)]
5769pub struct WorkflowResultOptions {
5770    pub poll_interval: Duration,
5771    pub timeout: Duration,
5772}
5773
5774impl Default for WorkflowResultOptions {
5775    fn default() -> Self {
5776        Self {
5777            poll_interval: Duration::from_millis(500),
5778            timeout: Duration::from_secs(30),
5779        }
5780    }
5781}
5782
5783#[derive(Clone, Debug, Deserialize)]
5784pub struct WorkflowDescription {
5785    pub workflow_id: Option<String>,
5786    pub run_id: Option<String>,
5787    pub workflow_type: Option<String>,
5788    pub status: Option<String>,
5789    #[serde(default)]
5790    pub closed_reason: Option<String>,
5791    #[serde(default)]
5792    pub error: Option<String>,
5793    #[serde(default)]
5794    pub failure: Option<Value>,
5795    #[serde(default)]
5796    pub exception: Option<Value>,
5797    #[serde(default)]
5798    pub failures: Vec<Value>,
5799    #[serde(default)]
5800    pub output: Option<Value>,
5801    #[serde(default)]
5802    pub output_envelope: Option<Value>,
5803    #[serde(skip)]
5804    pub output_avro_value: Option<AvroValue>,
5805    #[serde(flatten)]
5806    pub raw: HashMap<String, Value>,
5807}
5808
5809/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5810#[derive(Clone, Debug, Deserialize)]
5811pub struct WorkflowStreamDescription {
5812    pub stream_name: String,
5813    pub status: String,
5814    pub last_offset: i64,
5815    pub total_items: u64,
5816    pub pending_items: u64,
5817    #[serde(default)]
5818    pub opened_at: Option<String>,
5819    #[serde(default)]
5820    pub last_appended_at: Option<String>,
5821    #[serde(default)]
5822    pub closed_at: Option<String>,
5823    #[serde(default)]
5824    pub error_reason: Option<String>,
5825    #[serde(default)]
5826    pub retention_seconds: Option<u64>,
5827    #[serde(flatten)]
5828    pub raw: HashMap<String, Value>,
5829}
5830
5831impl WorkflowStreamDescription {
5832    pub fn is_terminal(&self) -> bool {
5833        matches!(self.status.as_str(), "closed" | "errored")
5834    }
5835}
5836
5837/// One item for direct or replay-safe append.
5838#[derive(Clone, Debug, Default)]
5839pub struct WorkflowStreamAppendItem {
5840    pub payload_envelope: Option<Value>,
5841    pub payload_reference: Option<String>,
5842    pub item_type: Option<String>,
5843    pub content_type: Option<String>,
5844    pub idempotency_key: Option<String>,
5845}
5846
5847impl WorkflowStreamAppendItem {
5848    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5849    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5850        let value = AvroValue::from_serialize(&payload)?;
5851        Ok(Self {
5852            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5853            ..Self::default()
5854        })
5855    }
5856
5857    /// Preserve an external payload URI as an opaque service-contract reference.
5858    pub fn from_reference(reference: impl Into<String>) -> Self {
5859        Self {
5860            payload_reference: Some(reference.into()),
5861            ..Self::default()
5862        }
5863    }
5864
5865    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5866        self.item_type = Some(item_type.into());
5867        self
5868    }
5869
5870    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5871        self.content_type = Some(content_type.into());
5872        self
5873    }
5874
5875    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5876        self.idempotency_key = Some(idempotency_key.into());
5877        self
5878    }
5879
5880    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5881        let mut item = serde_json::Map::new();
5882        if let Some(payload) = &self.payload_envelope {
5883            item.insert("payload".to_string(), payload.clone());
5884            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5885        }
5886        if let Some(reference) = &self.payload_reference {
5887            item.insert("payload_reference".to_string(), json!(reference));
5888        }
5889        if let Some(item_type) = &self.item_type {
5890            item.insert("item_type".to_string(), json!(item_type));
5891        }
5892        if let Some(content_type) = &self.content_type {
5893            item.insert("content_type".to_string(), json!(content_type));
5894        }
5895        if let Some(key) = derived_idempotency_key
5896            .as_ref()
5897            .or(self.idempotency_key.as_ref())
5898        {
5899            item.insert("idempotency_key".to_string(), json!(key));
5900        }
5901        Value::Object(item)
5902    }
5903}
5904
5905/// One durable item at its stable zero-based offset.
5906#[derive(Clone, Debug)]
5907pub struct WorkflowStreamItem {
5908    pub offset: u64,
5909    pub payload: Option<Value>,
5910    pub payload_envelope: Option<Value>,
5911    pub payload_reference: Option<String>,
5912    pub payload_codec: Option<String>,
5913    pub idempotency_key: Option<String>,
5914    pub item_type: Option<String>,
5915    pub content_type: Option<String>,
5916    pub origin: Option<String>,
5917    pub origin_reference: Option<String>,
5918    pub emitted_at: Option<String>,
5919    pub raw: Value,
5920}
5921
5922/// One bounded at-least-once subscription page.
5923#[derive(Clone, Debug)]
5924pub struct WorkflowStreamPage {
5925    pub stream: WorkflowStreamDescription,
5926    pub items: Vec<WorkflowStreamItem>,
5927    pub next_offset: u64,
5928    pub terminal: bool,
5929}
5930
5931/// Durable acceptance and deduplication outcome for an append request.
5932#[derive(Clone, Debug)]
5933pub struct WorkflowStreamAppendResult {
5934    pub stream: WorkflowStreamDescription,
5935    pub accepted_offsets: Vec<u64>,
5936    pub accepted: u64,
5937    pub deduped: u64,
5938}
5939
5940#[derive(Deserialize)]
5941struct WorkflowStreamListResponse {
5942    #[serde(default)]
5943    streams: Vec<WorkflowStreamDescription>,
5944}
5945
5946#[derive(Deserialize)]
5947struct WorkflowStreamDescriptionResponse {
5948    stream: WorkflowStreamDescription,
5949}
5950
5951#[derive(Deserialize)]
5952struct WorkflowStreamPageResponse {
5953    stream: WorkflowStreamDescription,
5954    #[serde(default)]
5955    items: Vec<Value>,
5956    next_offset: u64,
5957    terminal: bool,
5958}
5959
5960#[derive(Deserialize)]
5961struct WorkflowStreamAppendResponse {
5962    stream: WorkflowStreamDescription,
5963    #[serde(default)]
5964    accepted_offsets: Vec<u64>,
5965    accepted: u64,
5966    deduped: u64,
5967}
5968
5969impl WorkflowDescription {
5970    pub fn is_completed(&self) -> bool {
5971        matches!(self.status.as_deref(), Some("completed" | "Completed"))
5972    }
5973
5974    pub fn is_terminal(&self) -> bool {
5975        matches!(
5976            self.status.as_deref(),
5977            Some(
5978                "completed"
5979                    | "Completed"
5980                    | "failed"
5981                    | "Failed"
5982                    | "cancelled"
5983                    | "Cancelled"
5984                    | "terminated"
5985                    | "Terminated"
5986                    | "timed_out"
5987                    | "TimedOut",
5988            )
5989        )
5990    }
5991
5992    fn decode_payloads(&mut self) -> Result<()> {
5993        if let Some(envelope) = &self.output_envelope {
5994            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
5995            self.output = Some(value.clone().into_json()?);
5996            self.output_avro_value = Some(value);
5997        }
5998
5999        Ok(())
6000    }
6001
6002    fn raw_value(&self) -> Value {
6003        let mut data = self.raw.clone();
6004        data.insert(
6005            "workflow_id".to_string(),
6006            self.workflow_id
6007                .clone()
6008                .map(Value::String)
6009                .unwrap_or(Value::Null),
6010        );
6011        data.insert(
6012            "run_id".to_string(),
6013            self.run_id
6014                .clone()
6015                .map(Value::String)
6016                .unwrap_or(Value::Null),
6017        );
6018        data.insert(
6019            "workflow_type".to_string(),
6020            self.workflow_type
6021                .clone()
6022                .map(Value::String)
6023                .unwrap_or(Value::Null),
6024        );
6025        data.insert(
6026            "status".to_string(),
6027            self.status
6028                .clone()
6029                .map(Value::String)
6030                .unwrap_or(Value::Null),
6031        );
6032        data.insert(
6033            "closed_reason".to_string(),
6034            self.closed_reason
6035                .clone()
6036                .map(Value::String)
6037                .unwrap_or(Value::Null),
6038        );
6039        if let Some(failure) = &self.failure {
6040            data.insert("failure".to_string(), failure.clone());
6041        }
6042        if let Some(exception) = &self.exception {
6043            data.insert("exception".to_string(), exception.clone());
6044        }
6045        Value::Object(data.into_iter().collect())
6046    }
6047}
6048
6049fn workflow_terminal_outcome(
6050    description: &WorkflowDescription,
6051    workflow_id: &str,
6052    run_id: Option<&str>,
6053) -> WorkflowTerminalOutcome {
6054    let terminal_kind = description
6055        .closed_reason
6056        .as_deref()
6057        .or(description.status.as_deref())
6058        .unwrap_or("failed")
6059        .to_ascii_lowercase();
6060    let kind = match terminal_kind.as_str() {
6061        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6062        "terminated" => WorkflowTerminalKind::Terminated,
6063        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6064        _ => WorkflowTerminalKind::Failed,
6065    };
6066    let default_reason = match kind {
6067        WorkflowTerminalKind::Failed => "workflow_failed",
6068        WorkflowTerminalKind::Cancelled => "cancelled",
6069        WorkflowTerminalKind::Terminated => "terminated",
6070        WorkflowTerminalKind::TimedOut => "timed_out",
6071    };
6072    let failure = description
6073        .failure
6074        .as_ref()
6075        .filter(|value| value.is_object());
6076    let nested_failure = failure
6077        .and_then(|value| value.get("failures"))
6078        .and_then(Value::as_array)
6079        .and_then(|failures| failures.last())
6080        .or_else(|| description.failures.last());
6081    let exception = description
6082        .exception
6083        .clone()
6084        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6085        .or_else(|| {
6086            nested_failure
6087                .and_then(|value| value.get("exception_payload"))
6088                .cloned()
6089        });
6090    let string_field = |name: &str| {
6091        failure
6092            .and_then(|value| value.get(name))
6093            .and_then(Value::as_str)
6094            .or_else(|| {
6095                nested_failure
6096                    .and_then(|value| value.get(name))
6097                    .and_then(Value::as_str)
6098            })
6099            .map(str::to_string)
6100    };
6101    let exception_field = |name: &str| {
6102        exception
6103            .as_ref()
6104            .and_then(|value| value.get(name))
6105            .and_then(Value::as_str)
6106            .map(str::to_string)
6107    };
6108    let message = description
6109        .error
6110        .clone()
6111        .or_else(|| string_field("message"))
6112        .or_else(|| exception_field("message"));
6113    let reason = description
6114        .raw
6115        .get("reason")
6116        .and_then(Value::as_str)
6117        .map(str::to_string)
6118        .or_else(|| {
6119            failure
6120                .and_then(|value| value.get("reason"))
6121                .and_then(Value::as_str)
6122                .map(str::to_string)
6123        })
6124        .or_else(|| description.closed_reason.clone())
6125        .unwrap_or_else(|| default_reason.to_string());
6126    let failure_id = string_field("failure_id").or_else(|| {
6127        nested_failure
6128            .and_then(|value| value.get("id"))
6129            .and_then(Value::as_str)
6130            .map(str::to_string)
6131    });
6132
6133    WorkflowTerminalOutcome {
6134        kind,
6135        workflow_id: description
6136            .workflow_id
6137            .clone()
6138            .unwrap_or_else(|| workflow_id.to_string()),
6139        run_id: description
6140            .run_id
6141            .clone()
6142            .or_else(|| run_id.map(str::to_string)),
6143        reason,
6144        failure_category: string_field("failure_category")
6145            .or_else(|| Some(default_reason.to_string())),
6146        failure_id,
6147        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6148        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6149        non_retryable: failure
6150            .and_then(|value| value.get("non_retryable"))
6151            .and_then(Value::as_bool)
6152            .or_else(|| {
6153                nested_failure
6154                    .and_then(|value| value.get("non_retryable"))
6155                    .and_then(Value::as_bool)
6156            }),
6157        message,
6158        exception,
6159        raw: description.raw_value(),
6160    }
6161}
6162
6163#[derive(Clone, Debug, Deserialize)]
6164pub struct RegisterWorkerResponse {
6165    pub worker_id: String,
6166    pub registered: bool,
6167    #[serde(default)]
6168    pub heartbeat_interval_seconds: Option<u64>,
6169    #[serde(default)]
6170    pub protocol_version: Option<String>,
6171    #[serde(default)]
6172    pub server_capabilities: Option<Value>,
6173}
6174
6175/// Result of gracefully removing a worker-plane registration.
6176#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6177pub struct WorkerDeregistrationEnvelope {
6178    pub worker_id: String,
6179    pub outcome: String,
6180    pub recovered_workflow_task_count: u64,
6181}
6182
6183#[derive(Clone, Debug, Deserialize)]
6184pub struct PollWorkflowTaskResponse {
6185    #[serde(default)]
6186    pub task: Option<WorkflowTask>,
6187    #[serde(default)]
6188    pub poll_status: Option<String>,
6189    #[serde(default)]
6190    pub reason: Option<String>,
6191    #[serde(default)]
6192    pub protocol_version: Option<String>,
6193    #[serde(default)]
6194    pub server_capabilities: Option<Value>,
6195}
6196
6197impl PollWorkflowTaskResponse {
6198    /// Classify this response without parsing server display text.
6199    pub fn outcome(&self) -> WorkerPollOutcome {
6200        worker_poll_outcome(
6201            self.task.is_some(),
6202            self.poll_status.as_deref(),
6203            self.reason.as_deref(),
6204        )
6205    }
6206}
6207
6208fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6209    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6210        return false;
6211    };
6212    let supported = capabilities
6213        .get("workflow_memo_updates")
6214        .and_then(Value::as_object)
6215        .and_then(|memo| memo.get("supported"))
6216        .and_then(Value::as_bool)
6217        == Some(true);
6218    let command_advertised = capabilities
6219        .get("supported_workflow_task_commands")
6220        .and_then(Value::as_array)
6221        .is_some_and(|commands| {
6222            commands
6223                .iter()
6224                .any(|command| command.as_str() == Some("upsert_memo"))
6225        });
6226    supported && command_advertised
6227}
6228
6229fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6230    commands
6231        .iter()
6232        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6233}
6234
6235#[derive(Clone, Debug, Deserialize)]
6236pub struct PollActivityTaskResponse {
6237    #[serde(default)]
6238    pub task: Option<ActivityTask>,
6239    #[serde(default)]
6240    pub poll_status: Option<String>,
6241    #[serde(default)]
6242    pub reason: Option<String>,
6243}
6244
6245impl PollActivityTaskResponse {
6246    /// Classify this response without parsing server display text.
6247    pub fn outcome(&self) -> WorkerPollOutcome {
6248        worker_poll_outcome(
6249            self.task.is_some(),
6250            self.poll_status.as_deref(),
6251            self.reason.as_deref(),
6252        )
6253    }
6254}
6255
6256#[derive(Clone, Debug, Deserialize)]
6257pub struct PollQueryTaskResponse {
6258    #[serde(default)]
6259    pub task: Option<QueryTask>,
6260    #[serde(default)]
6261    pub poll_status: Option<String>,
6262    #[serde(default)]
6263    pub reason: Option<String>,
6264}
6265
6266impl PollQueryTaskResponse {
6267    /// Classify this response without parsing server display text.
6268    pub fn outcome(&self) -> WorkerPollOutcome {
6269        worker_poll_outcome(
6270            self.task.is_some(),
6271            self.poll_status.as_deref(),
6272            self.reason.as_deref(),
6273        )
6274    }
6275}
6276
6277/// Stable classification for worker poll responses.
6278#[derive(Clone, Debug, PartialEq, Eq)]
6279pub enum WorkerPollOutcome {
6280    /// A task was leased and is available on the response.
6281    Task,
6282    /// No task was leased, but the worker should continue polling.
6283    Idle {
6284        poll_status: Option<String>,
6285        reason: Option<String>,
6286    },
6287    /// The server asked this worker to stop claiming new work.
6288    Stop {
6289        poll_status: Option<String>,
6290        reason: Option<String>,
6291    },
6292}
6293
6294impl WorkerPollOutcome {
6295    pub fn should_stop(&self) -> bool {
6296        matches!(self, Self::Stop { .. })
6297    }
6298}
6299
6300fn worker_poll_outcome(
6301    has_task: bool,
6302    poll_status: Option<&str>,
6303    reason: Option<&str>,
6304) -> WorkerPollOutcome {
6305    if worker_poll_is_stop(poll_status, reason) {
6306        return WorkerPollOutcome::Stop {
6307            poll_status: poll_status.map(str::to_string),
6308            reason: reason.map(str::to_string),
6309        };
6310    }
6311
6312    if has_task {
6313        WorkerPollOutcome::Task
6314    } else {
6315        WorkerPollOutcome::Idle {
6316            poll_status: poll_status.map(str::to_string),
6317            reason: reason.map(str::to_string),
6318        }
6319    }
6320}
6321
6322/// An ephemeral server-routed query task.
6323#[derive(Clone, Debug, Deserialize)]
6324pub struct QueryTask {
6325    pub query_task_id: String,
6326    #[serde(default = "default_workflow_task_attempt")]
6327    pub query_task_attempt: u64,
6328    #[serde(default)]
6329    pub lease_owner: Option<String>,
6330    #[serde(default)]
6331    pub workflow_id: Option<String>,
6332    #[serde(default)]
6333    pub run_id: Option<String>,
6334    pub workflow_type: String,
6335    pub query_name: String,
6336    #[serde(
6337        default = "missing_task_payload_codec",
6338        deserialize_with = "deserialize_task_payload_codec"
6339    )]
6340    pub payload_codec: String,
6341    #[serde(default)]
6342    pub workflow_arguments: Option<Value>,
6343    #[serde(default)]
6344    pub query_arguments: Option<Value>,
6345    #[serde(default)]
6346    pub history_events: Vec<HistoryEvent>,
6347    #[serde(default)]
6348    pub history_export: Option<Value>,
6349    #[serde(default)]
6350    pub run_status: Option<String>,
6351}
6352
6353#[derive(Clone, Debug, Deserialize)]
6354pub struct WorkflowTask {
6355    pub task_id: String,
6356    #[serde(default)]
6357    pub workflow_command_id: Option<String>,
6358    #[serde(default)]
6359    pub workflow_id: Option<String>,
6360    #[serde(default)]
6361    pub run_id: Option<String>,
6362    pub workflow_type: String,
6363    #[serde(default)]
6364    pub cancel_requested: bool,
6365    #[serde(
6366        default = "missing_task_payload_codec",
6367        deserialize_with = "deserialize_task_payload_codec"
6368    )]
6369    pub payload_codec: String,
6370    #[serde(default)]
6371    pub arguments: Option<Value>,
6372    #[serde(default)]
6373    pub history_events: Vec<HistoryEvent>,
6374    #[serde(default)]
6375    pub total_history_events: Option<u64>,
6376    #[serde(default)]
6377    pub history_size_bytes: Option<u64>,
6378    #[serde(default)]
6379    pub continue_as_new_recommended: Option<bool>,
6380    #[serde(default)]
6381    pub history_budget_pressure: Option<String>,
6382    #[serde(default)]
6383    pub next_history_page_token: Option<String>,
6384    #[serde(default = "default_workflow_task_attempt")]
6385    pub workflow_task_attempt: u64,
6386    #[serde(default)]
6387    pub workflow_signal_id: Option<String>,
6388    #[serde(default)]
6389    pub signal_name: Option<String>,
6390    #[serde(default)]
6391    pub signal_arguments: Option<Value>,
6392    #[serde(default)]
6393    pub workflow_update_id: Option<String>,
6394    #[serde(default)]
6395    pub update_name: Option<String>,
6396    #[serde(default)]
6397    pub lease_owner: Option<String>,
6398}
6399
6400impl WorkflowTask {
6401    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6402        self.history_events.extend(page.history_events);
6403
6404        if page.total_history_events.is_some() {
6405            self.total_history_events = page.total_history_events;
6406        }
6407
6408        self.next_history_page_token = page
6409            .next_history_page_token
6410            .filter(|token| !token.is_empty());
6411    }
6412}
6413
6414#[derive(Clone, Debug, Deserialize)]
6415struct WorkflowTaskHistoryPage {
6416    #[serde(default)]
6417    history_events: Vec<HistoryEvent>,
6418    #[serde(default)]
6419    total_history_events: Option<u64>,
6420    #[serde(default)]
6421    next_history_page_token: Option<String>,
6422}
6423
6424#[derive(Clone, Debug, Deserialize)]
6425pub struct ActivityTask {
6426    pub task_id: String,
6427    #[serde(default)]
6428    pub activity_attempt_id: Option<String>,
6429    #[serde(default)]
6430    pub attempt_id: Option<String>,
6431    pub activity_type: String,
6432    #[serde(
6433        default = "missing_task_payload_codec",
6434        deserialize_with = "deserialize_task_payload_codec"
6435    )]
6436    pub payload_codec: String,
6437    #[serde(default)]
6438    pub arguments: Option<Value>,
6439    #[serde(default = "default_attempt_number")]
6440    pub attempt_number: u64,
6441    #[serde(default)]
6442    pub lease_owner: Option<String>,
6443}
6444
6445#[derive(Clone, Debug, Serialize, Deserialize)]
6446pub struct HistoryEvent {
6447    #[serde(alias = "type")]
6448    pub event_type: String,
6449    #[serde(default)]
6450    pub payload: Value,
6451    #[serde(flatten)]
6452    pub raw: HashMap<String, Value>,
6453}
6454
6455/// One decoded signal in the committed workflow-history snapshot.
6456#[derive(Clone, Debug, PartialEq)]
6457pub struct QuerySignal {
6458    pub id: Option<String>,
6459    pub name: String,
6460    pub arguments: Vec<Value>,
6461    avro_arguments: Vec<AvroValue>,
6462    pub workflow_sequence: Option<u64>,
6463}
6464
6465impl QuerySignal {
6466    /// Lossless fixed Avro Value arguments for this committed signal.
6467    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6468        &self.avro_arguments
6469    }
6470}
6471
6472/// Immutable state supplied to a registered query handler.
6473///
6474/// This context intentionally exposes no activity, signal-wait, or command
6475/// APIs. Query handlers inspect committed history and return a value; query
6476/// completion does not append an event or advance deterministic execution.
6477#[derive(Clone, Debug)]
6478pub struct QueryContext {
6479    pub workflow_id: Option<String>,
6480    pub run_id: Option<String>,
6481    pub workflow_type: String,
6482    pub run_status: Option<String>,
6483    workflow_input: Value,
6484    workflow_input_avro_value: AvroValue,
6485    history_events: Arc<Vec<HistoryEvent>>,
6486    signal_events: Arc<Vec<QuerySignal>>,
6487}
6488
6489impl QueryContext {
6490    /// The normalized argument list used to start the workflow.
6491    pub fn workflow_input(&self) -> &Value {
6492        &self.workflow_input
6493    }
6494
6495    /// The lossless fixed Avro Value argument list used to start the workflow.
6496    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6497        &self.workflow_input_avro_value
6498    }
6499
6500    /// The immutable committed history used for this query snapshot.
6501    pub fn history_events(&self) -> &[HistoryEvent] {
6502        self.history_events.as_slice()
6503    }
6504
6505    /// All decoded signals in committed workflow order.
6506    pub fn signal_events(&self) -> &[QuerySignal] {
6507        self.signal_events.as_slice()
6508    }
6509
6510    /// Decoded argument lists for each committed signal with `signal_name`.
6511    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6512        self.signal_events
6513            .iter()
6514            .filter(|signal| signal.name == signal_name)
6515            .map(|signal| signal.arguments.clone())
6516            .collect()
6517    }
6518
6519    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6520    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6521        self.signal_events
6522            .iter()
6523            .filter(|signal| signal.name == signal_name)
6524            .map(|signal| signal.avro_arguments.clone())
6525            .collect()
6526    }
6527}
6528
6529#[derive(Clone, Debug, Deserialize)]
6530pub struct ActivityHeartbeatResponse {
6531    #[serde(default)]
6532    pub cancel_requested: bool,
6533    #[serde(default)]
6534    pub heartbeat_recorded: bool,
6535    #[serde(default)]
6536    pub can_continue: Option<bool>,
6537    #[serde(default)]
6538    pub reason: Option<String>,
6539    #[serde(default)]
6540    pub run_closed_reason: Option<String>,
6541    #[serde(default)]
6542    pub run_closed_at: Option<String>,
6543    #[serde(default)]
6544    pub lease_expires_at: Option<String>,
6545    #[serde(default)]
6546    pub last_heartbeat_at: Option<String>,
6547}
6548
6549impl ActivityHeartbeatResponse {
6550    /// Whether the activity should stop instead of attempting completion.
6551    pub fn should_stop(&self) -> bool {
6552        self.cancel_requested || self.can_continue == Some(false)
6553    }
6554}
6555
6556fn missing_task_payload_codec() -> String {
6557    MISSING_TASK_PAYLOAD_CODEC.to_string()
6558}
6559
6560fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6561where
6562    D: Deserializer<'de>,
6563{
6564    Ok(match Value::deserialize(deserializer)? {
6565        Value::String(codec) => codec,
6566        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6567        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6568    })
6569}
6570
6571fn default_workflow_task_attempt() -> u64 {
6572    1
6573}
6574
6575fn default_attempt_number() -> u64 {
6576    1
6577}
6578
6579type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6580type WorkflowHandler = Arc<dyn Fn(WorkflowContext, AvroValue) -> WorkflowFuture + Send + Sync>;
6581type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6582type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6583type ReplayedWorkflowHandler =
6584    Arc<dyn Fn(WorkflowContext, AvroValue) -> ReplayedWorkflowInvocation + Send + Sync>;
6585type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6586type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6587type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6588type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6589type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6590type ReplayedQueryHandler = Arc<
6591    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6592        + Send
6593        + Sync,
6594>;
6595type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6596
6597struct ReplayedWorkflowInvocation {
6598    future: WorkflowFuture,
6599    snapshot: WorkflowStateSnapshot,
6600}
6601
6602#[derive(Clone)]
6603struct RegisteredWorkflow {
6604    execute: WorkflowHandler,
6605    replay: Option<ReplayedWorkflowHandler>,
6606    state_type: Option<TypeId>,
6607    definition_fingerprint: Option<String>,
6608}
6609
6610fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
6611    names
6612        .iter()
6613        .map(|name| {
6614            json!({
6615                "name": name,
6616                "parameters": [{
6617                    "name": "args",
6618                    "position": 0,
6619                    "required": false,
6620                    "variadic": true,
6621                    "type": null,
6622                    "allows_null": true,
6623                    "default_available": false,
6624                    "default": null,
6625                }],
6626            })
6627        })
6628        .collect()
6629}
6630
6631#[derive(Debug)]
6632struct WorkflowTaskDecision {
6633    commands: Vec<Value>,
6634    message_stream_cursors: Vec<Value>,
6635    message_stream_waits: Vec<Value>,
6636    cancellation_delivery: Option<CancellationDelivery>,
6637    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6638    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6639}
6640
6641enum PreparedWorkflowTask {
6642    Decision(WorkflowTaskDecision),
6643    Execution {
6644        task: WorkflowTask,
6645        context: WorkflowContext,
6646        future: WorkflowFuture,
6647    },
6648}
6649
6650impl WorkflowTaskDecision {
6651    fn without_message_streams(commands: Vec<Value>) -> Self {
6652        Self {
6653            commands,
6654            message_stream_cursors: Vec::new(),
6655            message_stream_waits: Vec::new(),
6656            cancellation_delivery: None,
6657            cancellation_scope_opening: None,
6658            cancellation_scope_delivery: None,
6659        }
6660    }
6661}
6662
6663#[derive(Clone)]
6664enum RegisteredQuery {
6665    Snapshot(QueryHandler),
6666    Replayed {
6667        state_type: TypeId,
6668        handler: ReplayedQueryHandler,
6669    },
6670}
6671
6672#[derive(Clone, Debug)]
6673pub struct WorkerHeartbeatObservation {
6674    pub worker_id: String,
6675    pub task_queue: String,
6676    pub acknowledged_at_unix_millis: u64,
6677    pub acknowledgement: Value,
6678}
6679
6680/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6681///
6682/// Expected empty long polls and explicit Server capacity backpressure are
6683/// normal worker states. Capacity backpressure honors the advertised retry
6684/// delay without consuming this retry budget. Other transport failures,
6685/// retryable HTTP 408/429 responses, and server errors are retried with capped
6686/// exponential backoff. Authentication, protocol, codec, and handler failures
6687/// are never retried by the worker.
6688/// Explicit storage admission pauses also preserve the already-serialized worker
6689/// request without consuming this budget or rerunning its handler. The delay is
6690/// capped by `max_backoff`, except an explicit completion deferral must honor
6691/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
6692/// completion retries remain bounded by the original cleanup deadline.
6693/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6694/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6695/// and `max_retries = 0` disables ordinary retries in either mode.
6696#[derive(Clone, Copy, Debug)]
6697pub struct WorkerRetryPolicy {
6698    /// Number of retries after the initial request fails.
6699    pub max_retries: usize,
6700    /// Delay before the first retry.
6701    pub initial_backoff: Duration,
6702    /// Maximum delay between retries.
6703    pub max_backoff: Duration,
6704}
6705
6706impl Default for WorkerRetryPolicy {
6707    fn default() -> Self {
6708        Self {
6709            max_retries: 5,
6710            initial_backoff: Duration::from_millis(100),
6711            max_backoff: Duration::from_secs(5),
6712        }
6713    }
6714}
6715
6716#[derive(Clone, Debug)]
6717struct WorkerStorageAdmission {
6718    policy: WorkerRetryPolicy,
6719    stop: Arc<AtomicBool>,
6720    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
6721}
6722
6723struct StopWorkerOnDrop(Arc<AtomicBool>);
6724
6725impl Drop for StopWorkerOnDrop {
6726    fn drop(&mut self) {
6727        self.0.store(true, Ordering::SeqCst);
6728    }
6729}
6730
6731async fn wait_for_worker_stop(stop: &AtomicBool) {
6732    while !stop.load(Ordering::SeqCst) {
6733        tokio::time::sleep(Duration::from_millis(100)).await;
6734    }
6735}
6736
6737#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6738enum ManagedPollOutcome {
6739    Idle,
6740    Handled,
6741    Stop,
6742}
6743
6744#[derive(Clone)]
6745pub struct Worker {
6746    client: Client,
6747    worker_id: String,
6748    task_queue: String,
6749    workflows: HashMap<String, RegisteredWorkflow>,
6750    activities: HashMap<String, ActivityHandler>,
6751    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6752    signals: HashMap<String, Vec<String>>,
6753    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6754    registration_definitions:
6755        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
6756    registration_error: Option<DuplicateRegistrationError>,
6757    max_concurrent_workflow_tasks: usize,
6758    max_concurrent_activity_tasks: usize,
6759    poll_timeout: Duration,
6760    heartbeat_interval: Duration,
6761    retry_policy: WorkerRetryPolicy,
6762    recover_transient_outages: bool,
6763    run_stop: Option<Arc<AtomicBool>>,
6764    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6765    cooperative_cancellation_enabled: bool,
6766    allow_cancellation_scope_authoring: bool,
6767    allow_cancellation_scope_delivery: bool,
6768    cooperative_registration_confirmed: Arc<AtomicBool>,
6769    local_registration_confirmed: Arc<AtomicBool>,
6770    session_registration_confirmed: Arc<AtomicBool>,
6771    sticky_registration_confirmed: Arc<AtomicBool>,
6772    resource_capabilities: Vec<String>,
6773    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6774}
6775
6776impl Worker {
6777    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6778        Self {
6779            client,
6780            worker_id: default_worker_id(),
6781            task_queue: task_queue.into(),
6782            workflows: HashMap::new(),
6783            activities: HashMap::new(),
6784            queries: HashMap::new(),
6785            signals: HashMap::new(),
6786            updates: HashMap::new(),
6787            registration_definitions: HashMap::new(),
6788            registration_error: None,
6789            max_concurrent_workflow_tasks: 10,
6790            max_concurrent_activity_tasks: 10,
6791            poll_timeout: Duration::from_secs(30),
6792            heartbeat_interval: Duration::from_secs(60),
6793            retry_policy: WorkerRetryPolicy::default(),
6794            recover_transient_outages: false,
6795            run_stop: None,
6796            heartbeat_observer: None,
6797            cooperative_cancellation_enabled: false,
6798            allow_cancellation_scope_authoring: false,
6799            allow_cancellation_scope_delivery: false,
6800            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6801            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6802            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6803            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
6804            resource_capabilities: Vec::new(),
6805            sessions: Arc::new(Mutex::new(HashMap::new())),
6806        }
6807    }
6808
6809    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6810        self.worker_id = worker_id.into();
6811        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6812        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6813        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6814        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
6815        self.client.reset_sticky_cache();
6816        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6817        self
6818    }
6819
6820    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6821        self.poll_timeout = timeout;
6822        self
6823    }
6824
6825    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6826        self.heartbeat_interval = interval;
6827        self
6828    }
6829
6830    /// Explicitly enable inline local activities in this workflow worker.
6831    ///
6832    /// The worker advertises the capability to Server only when enabled.
6833    /// These callbacks must yield to Tokio and have idempotent side effects.
6834    /// Cooperative prepared local supervision is a separate capability.
6835    pub fn local_activities(mut self, enabled: bool) -> Self {
6836        self.client.local_activities_enabled = enabled;
6837        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6838        self
6839    }
6840
6841    /// Opt in to separate cooperative workflow cancellation requests.
6842    ///
6843    /// Registration requires the Server to acknowledge this exact worker,
6844    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6845    /// processing uses canonical delivery and activity ownership fences.
6846    /// Existing terminal cancel and terminate operations remain terminal.
6847    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
6848    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6849    /// and [`Worker::run_until`] register automatically.
6850    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6851        self.cooperative_cancellation_enabled = enabled;
6852        self.client.cooperative_worker_protocol = enabled;
6853        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6854        self
6855    }
6856
6857    /// Enable candidate scope authoring without advertising scoped execution.
6858    #[doc(hidden)]
6859    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6860        self.allow_cancellation_scope_authoring = enabled;
6861        self
6862    }
6863
6864    /// Enable the candidate scoped call consumer with canonical authoring.
6865    #[doc(hidden)]
6866    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6867        self.allow_cancellation_scope_delivery = enabled;
6868        self
6869    }
6870
6871    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6872    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6873        self.retry_policy = policy;
6874        self
6875    }
6876
6877    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6878    ///
6879    /// Retries preserve the poll request identity and use capped exponential
6880    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6881    /// An in-flight poll is allowed to finish so leased work is not discarded.
6882    /// Authentication, protocol, codec, handler and task settlement failures
6883    /// remain errors. Registration and deregistration are not retried here.
6884    ///
6885    /// The default is disabled, preserving the bounded retry contract.
6886    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6887    /// even when this option is enabled.
6888    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6889        self.recover_transient_outages = enabled;
6890        self
6891    }
6892
6893    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6894    where
6895        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6896    {
6897        self.heartbeat_observer = Some(Arc::new(observer));
6898        self
6899    }
6900
6901    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6902        self.max_concurrent_workflow_tasks = count.max(1);
6903        self
6904    }
6905
6906    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6907        self.max_concurrent_activity_tasks = count.max(1);
6908        self
6909    }
6910
6911    /// Validate local handler admission without making a Server request.
6912    ///
6913    /// Registration methods retain their existing signatures. A duplicate keeps
6914    /// the original handler and makes this Worker invalid, including its clones.
6915    /// `register`, `run`, `run_until` and `run_once` enforce this check before
6916    /// any network request. Build a new Worker to correct an invalid configuration.
6917    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
6918        match &self.registration_error {
6919            Some(error) => Err(error.clone()),
6920            None => Ok(()),
6921        }
6922    }
6923
6924    #[track_caller]
6925    fn admit_registration<F>(
6926        &mut self,
6927        handler_kind: RegistrationKind,
6928        workflow_type: Option<&str>,
6929        handler_name: &str,
6930        method: &'static str,
6931    ) -> bool {
6932        let location = std::panic::Location::caller();
6933        let definition = HandlerRegistration {
6934            method,
6935            handler_type: type_name::<F>(),
6936            file: location.file(),
6937            line: location.line(),
6938            column: location.column(),
6939        };
6940        let key = (
6941            handler_kind,
6942            workflow_type.map(str::to_owned),
6943            handler_name.to_owned(),
6944        );
6945        if let Some(first_definition) = self.registration_definitions.get(&key) {
6946            if self.registration_error.is_none() {
6947                self.registration_error = Some(DuplicateRegistrationError {
6948                    handler_kind,
6949                    workflow_type: key.1.clone(),
6950                    handler_name: key.2.clone(),
6951                    first_definition: first_definition.clone(),
6952                    second_definition: definition,
6953                });
6954            }
6955            return false;
6956        }
6957        self.registration_definitions.insert(key, definition);
6958        true
6959    }
6960
6961    /// Register a workflow handler.
6962    ///
6963    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6964    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6965    /// while acquiring or decoding a worker task remain worker-operation
6966    /// failures and do not get converted into workflow outcomes.
6967    #[track_caller]
6968    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6969    where
6970        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6971        Fut: Future<Output = Result<Value>> + Send + 'static,
6972    {
6973        let workflow_type = workflow_type.into();
6974        if !self.admit_registration::<F>(
6975            RegistrationKind::Workflow,
6976            None,
6977            &workflow_type,
6978            "register_workflow",
6979        ) {
6980            return;
6981        }
6982        let handler = Arc::new(handler);
6983        self.workflows.insert(
6984            workflow_type,
6985            RegisteredWorkflow {
6986                execute: Arc::new(move |ctx, input| {
6987                    let handler = Arc::clone(&handler);
6988                    Box::pin(async move {
6989                        let result = handler(ctx, input.into_json()?).await?;
6990                        AvroValue::from_serialize(&result)
6991                    })
6992                }),
6993                replay: None,
6994                state_type: None,
6995                definition_fingerprint: None,
6996            },
6997        );
6998    }
6999
7000    /// Register a workflow with one Serde request value and a Serde result.
7001    ///
7002    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
7003    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
7004    /// workflow-specific schema. A task must contain zero arguments for a unit
7005    /// request or exactly one argument for every other request type.
7006    ///
7007    /// See the runnable
7008    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
7009    /// for typed workflow and activity contracts with retry and timeout policy.
7010    #[track_caller]
7011    pub fn register_typed_workflow<I, O, F, Fut>(
7012        &mut self,
7013        workflow_type: impl Into<String>,
7014        handler: F,
7015    ) where
7016        I: DeserializeOwned + Send + 'static,
7017        O: Serialize + Send + 'static,
7018        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
7019        Fut: Future<Output = Result<O>> + Send + 'static,
7020    {
7021        let workflow_type = workflow_type.into();
7022        if !self.admit_registration::<F>(
7023            RegistrationKind::Workflow,
7024            None,
7025            &workflow_type,
7026            "register_typed_workflow",
7027        ) {
7028            return;
7029        }
7030        let handler_name = workflow_type.clone();
7031        let handler = Arc::new(handler);
7032        self.workflows.insert(
7033            workflow_type,
7034            RegisteredWorkflow {
7035                execute: Arc::new(move |ctx, input| {
7036                    let handler = Arc::clone(&handler);
7037                    let handler_name = handler_name.clone();
7038                    Box::pin(async move {
7039                        let input =
7040                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7041                        let result = handler(ctx, input).await?;
7042                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7043                    })
7044                }),
7045                replay: None,
7046                state_type: None,
7047                definition_fingerprint: None,
7048            },
7049        );
7050    }
7051
7052    /// Register a workflow on the lossless fixed Avro Value surface.
7053    #[track_caller]
7054    pub fn register_workflow_avro_value<F, Fut>(
7055        &mut self,
7056        workflow_type: impl Into<String>,
7057        handler: F,
7058    ) where
7059        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
7060        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7061    {
7062        let workflow_type = workflow_type.into();
7063        if !self.admit_registration::<F>(
7064            RegistrationKind::Workflow,
7065            None,
7066            &workflow_type,
7067            "register_workflow_avro_value",
7068        ) {
7069            return;
7070        }
7071        self.workflows.insert(
7072            workflow_type,
7073            RegisteredWorkflow {
7074                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
7075                replay: None,
7076                state_type: None,
7077                definition_fingerprint: None,
7078            },
7079        );
7080    }
7081
7082    /// Register a workflow whose typed instance state can be reconstructed for queries.
7083    ///
7084    /// `state_factory` creates a fresh instance for every normal workflow task and
7085    /// query replay. The workflow handler is the single source of truth for state
7086    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7087    /// resolve. Query replay runs this same handler over committed history and
7088    /// discards any commands it would emit.
7089    #[track_caller]
7090    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7091        &mut self,
7092        workflow_type: impl Into<String>,
7093        state_factory: Factory,
7094        handler: F,
7095    ) where
7096        S: Clone + Send + Sync + 'static,
7097        Factory: Fn() -> S + Send + Sync + 'static,
7098        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7099        Fut: Future<Output = Result<Value>> + Send + 'static,
7100    {
7101        let workflow_type = workflow_type.into();
7102        if !self.admit_registration::<F>(
7103            RegistrationKind::Workflow,
7104            None,
7105            &workflow_type,
7106            "register_replayed_workflow",
7107        ) {
7108            return;
7109        }
7110        let state_factory = Arc::new(state_factory);
7111        let handler = Arc::new(handler);
7112
7113        let execute_factory = Arc::clone(&state_factory);
7114        let execute_handler = Arc::clone(&handler);
7115        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7116            let state = WorkflowInstance::new(execute_factory());
7117            let handler = Arc::clone(&execute_handler);
7118            Box::pin(async move {
7119                let result = handler(ctx, input.into_json()?, state).await?;
7120                AvroValue::from_serialize(&result)
7121            }) as WorkflowFuture
7122        });
7123
7124        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7125            let state = WorkflowInstance::new(state_factory());
7126            let snapshot_state = state.clone();
7127            let snapshot: WorkflowStateSnapshot =
7128                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7129            let replay_handler = Arc::clone(&handler);
7130            let future = async move {
7131                let result = replay_handler(ctx, input.into_json()?, state).await?;
7132                AvroValue::from_serialize(&result)
7133            };
7134            ReplayedWorkflowInvocation {
7135                future: Box::pin(future),
7136                snapshot,
7137            }
7138        });
7139
7140        self.workflows.insert(
7141            workflow_type,
7142            RegisteredWorkflow {
7143                execute,
7144                replay: Some(replay),
7145                state_type: Some(TypeId::of::<S>()),
7146                definition_fingerprint: None,
7147            },
7148        );
7149    }
7150
7151    /// Register a replayable workflow with one Serde request value and result.
7152    ///
7153    /// Normal task execution and instance-state query replay both decode and
7154    /// encode through the fixed Avro Value codec. The state factory and handler
7155    /// otherwise follow [`Worker::register_replayed_workflow`].
7156    #[track_caller]
7157    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7158        &mut self,
7159        workflow_type: impl Into<String>,
7160        state_factory: Factory,
7161        handler: F,
7162    ) where
7163        I: DeserializeOwned + Send + 'static,
7164        O: Serialize + Send + 'static,
7165        S: Clone + Send + Sync + 'static,
7166        Factory: Fn() -> S + Send + Sync + 'static,
7167        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7168        Fut: Future<Output = Result<O>> + Send + 'static,
7169    {
7170        let workflow_type = workflow_type.into();
7171        if !self.admit_registration::<F>(
7172            RegistrationKind::Workflow,
7173            None,
7174            &workflow_type,
7175            "register_typed_replayed_workflow",
7176        ) {
7177            return;
7178        }
7179        let state_factory = Arc::new(state_factory);
7180        let handler = Arc::new(handler);
7181
7182        let execute_name = workflow_type.clone();
7183        let execute_factory = Arc::clone(&state_factory);
7184        let execute_handler = Arc::clone(&handler);
7185        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7186            let state = WorkflowInstance::new(execute_factory());
7187            let handler = Arc::clone(&execute_handler);
7188            let handler_name = execute_name.clone();
7189            Box::pin(async move {
7190                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7191                let result = handler(ctx, input, state).await?;
7192                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7193            }) as WorkflowFuture
7194        });
7195
7196        let replay_name = workflow_type.clone();
7197        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7198            let state = WorkflowInstance::new(state_factory());
7199            let snapshot_state = state.clone();
7200            let snapshot: WorkflowStateSnapshot =
7201                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7202            let handler = Arc::clone(&handler);
7203            let handler_name = replay_name.clone();
7204            let future = async move {
7205                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7206                let result = handler(ctx, input, state).await?;
7207                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7208            };
7209            ReplayedWorkflowInvocation {
7210                future: Box::pin(future),
7211                snapshot,
7212            }
7213        });
7214
7215        self.workflows.insert(
7216            workflow_type,
7217            RegisteredWorkflow {
7218                execute,
7219                replay: Some(replay),
7220                state_type: Some(TypeId::of::<S>()),
7221                definition_fingerprint: None,
7222            },
7223        );
7224    }
7225
7226    /// Declare the signal names consumed by a registered workflow.
7227    ///
7228    /// Call this after registering the workflow and before starting the worker.
7229    /// Names read through `wait_signal` or `signals` need a declaration for
7230    /// Server command admission. Arguments remain arbitrary positional values,
7231    /// including lossless Avro values. This replaces the previous declaration;
7232    /// an empty slice declares no signals. Names are sorted and deduplicated.
7233    /// Existing runs retain the declarations captured when they started.
7234    pub fn declare_workflow_signals(
7235        &mut self,
7236        workflow_type: &str,
7237        signal_names: &[&str],
7238    ) -> Result<()> {
7239        if !self.workflows.contains_key(workflow_type) {
7240            return Err(Error::Codec(format!(
7241                "workflow type {workflow_type:?} is not registered"
7242            )));
7243        }
7244        if signal_names
7245            .iter()
7246            .any(|name| name.is_empty() || *name != name.trim())
7247        {
7248            return Err(Error::Codec(
7249                "signal names must be non-empty and have no surrounding whitespace".into(),
7250            ));
7251        }
7252        let mut names = signal_names
7253            .iter()
7254            .map(|name| (*name).to_string())
7255            .collect::<Vec<_>>();
7256        names.sort();
7257        names.dedup();
7258        self.signals.insert(workflow_type.to_string(), names);
7259        Ok(())
7260    }
7261
7262    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7263    ///
7264    /// Supply `include_str!` values for the workflow body and every helper whose
7265    /// behavior can affect replay. Register the workflow once, then set its
7266    /// identity before starting the worker. Duplicate registrations are invalid. The server
7267    /// rejects reusing a worker ID when its prior fingerprint disappears.
7268    /// Workflows without source identity remain runnable but cannot be safely redriven.
7269    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7270    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7271    pub fn set_workflow_definition_sources(
7272        &mut self,
7273        workflow_type: &str,
7274        sources: &[&str],
7275    ) -> Result<()> {
7276        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7277            return Err(Error::Codec(
7278                "workflow definition sources must be non-empty".to_string(),
7279            ));
7280        }
7281        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7282            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7283        })?;
7284        let mut hasher = Sha256::new();
7285        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7286        hasher.update((workflow_type.len() as u64).to_be_bytes());
7287        hasher.update(workflow_type.as_bytes());
7288        for source in sources {
7289            hasher.update((source.len() as u64).to_be_bytes());
7290            hasher.update(source.as_bytes());
7291        }
7292        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7293        Ok(())
7294    }
7295
7296    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7297    #[track_caller]
7298    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7299        &mut self,
7300        workflow_type: impl Into<String>,
7301        state_factory: Factory,
7302        handler: F,
7303    ) where
7304        S: Clone + Send + Sync + 'static,
7305        Factory: Fn() -> S + Send + Sync + 'static,
7306        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7307        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7308    {
7309        let workflow_type = workflow_type.into();
7310        if !self.admit_registration::<F>(
7311            RegistrationKind::Workflow,
7312            None,
7313            &workflow_type,
7314            "register_replayed_workflow_avro_value",
7315        ) {
7316            return;
7317        }
7318        let state_factory = Arc::new(state_factory);
7319        let handler = Arc::new(handler);
7320
7321        let execute_factory = Arc::clone(&state_factory);
7322        let execute_handler = Arc::clone(&handler);
7323        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7324            let state = WorkflowInstance::new(execute_factory());
7325            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
7326        });
7327
7328        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7329            let state = WorkflowInstance::new(state_factory());
7330            let snapshot_state = state.clone();
7331            let snapshot: WorkflowStateSnapshot =
7332                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7333            ReplayedWorkflowInvocation {
7334                future: Box::pin(handler(ctx, input, state)),
7335                snapshot,
7336            }
7337        });
7338
7339        self.workflows.insert(
7340            workflow_type,
7341            RegisteredWorkflow {
7342                execute,
7343                replay: Some(replay),
7344                state_type: Some(TypeId::of::<S>()),
7345                definition_fingerprint: None,
7346            },
7347        );
7348    }
7349
7350    #[track_caller]
7351    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7352    where
7353        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7354        Fut: Future<Output = Result<Value>> + Send + 'static,
7355    {
7356        let activity_type = activity_type.into();
7357        if !self.admit_registration::<F>(
7358            RegistrationKind::Activity,
7359            None,
7360            &activity_type,
7361            "register_activity",
7362        ) {
7363            return;
7364        }
7365        let handler = Arc::new(handler);
7366        self.activities.insert(
7367            activity_type,
7368            Arc::new(move |ctx, args| {
7369                let handler = Arc::clone(&handler);
7370                Box::pin(async move {
7371                    let result = handler(ctx, args.into_json()?).await?;
7372                    AvroValue::from_serialize(&result)
7373                })
7374            }),
7375        );
7376    }
7377
7378    /// Register an activity with one Serde request value and a Serde result.
7379    ///
7380    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7381    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7382    /// with the activity name and Rust type.
7383    #[track_caller]
7384    pub fn register_typed_activity<I, O, F, Fut>(
7385        &mut self,
7386        activity_type: impl Into<String>,
7387        handler: F,
7388    ) where
7389        I: DeserializeOwned + Send + 'static,
7390        O: Serialize + Send + 'static,
7391        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
7392        Fut: Future<Output = Result<O>> + Send + 'static,
7393    {
7394        let activity_type = activity_type.into();
7395        if !self.admit_registration::<F>(
7396            RegistrationKind::Activity,
7397            None,
7398            &activity_type,
7399            "register_typed_activity",
7400        ) {
7401            return;
7402        }
7403        let handler_name = activity_type.clone();
7404        let handler = Arc::new(handler);
7405        self.activities.insert(
7406            activity_type,
7407            Arc::new(move |ctx, input| {
7408                let handler = Arc::clone(&handler);
7409                let handler_name = handler_name.clone();
7410                Box::pin(async move {
7411                    let input =
7412                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
7413                    let result = handler(ctx, input).await?;
7414                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
7415                })
7416            }),
7417        );
7418    }
7419
7420    /// Register an activity on the lossless fixed Avro Value surface.
7421    #[track_caller]
7422    pub fn register_activity_avro_value<F, Fut>(
7423        &mut self,
7424        activity_type: impl Into<String>,
7425        handler: F,
7426    ) where
7427        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
7428        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7429    {
7430        let activity_type = activity_type.into();
7431        if !self.admit_registration::<F>(
7432            RegistrationKind::Activity,
7433            None,
7434            &activity_type,
7435            "register_activity_avro_value",
7436        ) {
7437            return;
7438        }
7439        self.activities.insert(
7440            activity_type,
7441            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7442        );
7443    }
7444
7445    /// Register a named, read-only query handler for a workflow type.
7446    ///
7447    /// The workflow type must also be registered with [`Worker::register_workflow`]
7448    /// before the worker runs. The handler receives only an immutable committed
7449    /// state snapshot and normalized query arguments.
7450    #[track_caller]
7451    pub fn register_query<F, Fut>(
7452        &mut self,
7453        workflow_type: impl Into<String>,
7454        query_name: impl Into<String>,
7455        handler: F,
7456    ) where
7457        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7458        Fut: Future<Output = Result<Value>> + Send + 'static,
7459    {
7460        let workflow_type = workflow_type.into();
7461        let query_name = query_name.into();
7462        if !self.admit_registration::<F>(
7463            RegistrationKind::Query,
7464            Some(&workflow_type),
7465            &query_name,
7466            "register_query",
7467        ) {
7468            return;
7469        }
7470        let handler = Arc::new(handler);
7471        self.queries.entry(workflow_type).or_default().insert(
7472            query_name,
7473            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
7474                let handler = Arc::clone(&handler);
7475                Box::pin(async move {
7476                    let result = handler(ctx, args.into_json()?).await?;
7477                    AvroValue::from_serialize(&result)
7478                })
7479            })),
7480        );
7481    }
7482
7483    /// Register a query handler on the lossless fixed Avro Value surface.
7484    #[track_caller]
7485    pub fn register_query_avro_value<F, Fut>(
7486        &mut self,
7487        workflow_type: impl Into<String>,
7488        query_name: impl Into<String>,
7489        handler: F,
7490    ) where
7491        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7492        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7493    {
7494        let workflow_type = workflow_type.into();
7495        let query_name = query_name.into();
7496        if !self.admit_registration::<F>(
7497            RegistrationKind::Query,
7498            Some(&workflow_type),
7499            &query_name,
7500            "register_query_avro_value",
7501        ) {
7502            return;
7503        }
7504        self.queries.entry(workflow_type).or_default().insert(
7505            query_name,
7506            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
7507        );
7508    }
7509
7510    /// Register a named query against deterministically replayed instance state.
7511    ///
7512    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
7513    /// same state type `S`. The handler receives an immutable, detached state
7514    /// clone, so successful and failed queries cannot affect workflow execution
7515    /// or the state reconstructed by a later query.
7516    #[track_caller]
7517    pub fn register_replayed_query<S, F, Fut>(
7518        &mut self,
7519        workflow_type: impl Into<String>,
7520        query_name: impl Into<String>,
7521        handler: F,
7522    ) where
7523        S: Clone + Send + Sync + 'static,
7524        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
7525        Fut: Future<Output = Result<Value>> + Send + 'static,
7526    {
7527        let workflow_type = workflow_type.into();
7528        let query_name = query_name.into();
7529        if !self.admit_registration::<F>(
7530            RegistrationKind::Query,
7531            Some(&workflow_type),
7532            &query_name,
7533            "register_replayed_query",
7534        ) {
7535            return;
7536        }
7537        let handler = Arc::new(handler);
7538        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7539            let state = state.downcast::<S>().map_err(|_| {
7540                "registered query state type does not match the replayed workflow state".to_string()
7541            })?;
7542            let handler = Arc::clone(&handler);
7543            Ok(Box::pin(async move {
7544                let result = handler(ctx, state, args.into_json()?).await?;
7545                AvroValue::from_serialize(&result)
7546            }))
7547        });
7548
7549        self.queries.entry(workflow_type).or_default().insert(
7550            query_name,
7551            RegisteredQuery::Replayed {
7552                state_type: TypeId::of::<S>(),
7553                handler: erased_handler,
7554            },
7555        );
7556    }
7557
7558    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7559    #[track_caller]
7560    pub fn register_replayed_query_avro_value<S, F, Fut>(
7561        &mut self,
7562        workflow_type: impl Into<String>,
7563        query_name: impl Into<String>,
7564        handler: F,
7565    ) where
7566        S: Clone + Send + Sync + 'static,
7567        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7568        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7569    {
7570        let workflow_type = workflow_type.into();
7571        let query_name = query_name.into();
7572        if !self.admit_registration::<F>(
7573            RegistrationKind::Query,
7574            Some(&workflow_type),
7575            &query_name,
7576            "register_replayed_query_avro_value",
7577        ) {
7578            return;
7579        }
7580        let handler = Arc::new(handler);
7581        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7582            let state = state.downcast::<S>().map_err(|_| {
7583                "registered query state type does not match the replayed workflow state".to_string()
7584            })?;
7585            Ok(Box::pin(handler(ctx, state, args)))
7586        });
7587
7588        self.queries.entry(workflow_type).or_default().insert(
7589            query_name,
7590            RegisteredQuery::Replayed {
7591                state_type: TypeId::of::<S>(),
7592                handler: erased_handler,
7593            },
7594        );
7595    }
7596
7597    /// Register a synchronous workflow update handler.
7598    #[track_caller]
7599    pub fn register_update<F, Fut>(
7600        &mut self,
7601        workflow_type: impl Into<String>,
7602        update_name: impl Into<String>,
7603        handler: F,
7604    ) where
7605        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7606        Fut: Future<Output = Result<Value>> + Send + 'static,
7607    {
7608        let workflow_type = workflow_type.into();
7609        let update_name = update_name.into();
7610        if !self.admit_registration::<F>(
7611            RegistrationKind::Update,
7612            Some(&workflow_type),
7613            &update_name,
7614            "register_update",
7615        ) {
7616            return;
7617        }
7618        let handler = Arc::new(handler);
7619        self.updates.entry(workflow_type).or_default().insert(
7620            update_name,
7621            Arc::new(move |ctx, args| {
7622                let handler = Arc::clone(&handler);
7623                Box::pin(async move {
7624                    let result = handler(ctx, args.into_json()?).await?;
7625                    AvroValue::from_serialize(&result)
7626                })
7627            }),
7628        );
7629    }
7630
7631    /// Register an update handler on the lossless fixed Avro Value surface.
7632    #[track_caller]
7633    pub fn register_update_avro_value<F, Fut>(
7634        &mut self,
7635        workflow_type: impl Into<String>,
7636        update_name: impl Into<String>,
7637        handler: F,
7638    ) where
7639        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7640        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7641    {
7642        let workflow_type = workflow_type.into();
7643        let update_name = update_name.into();
7644        if !self.admit_registration::<F>(
7645            RegistrationKind::Update,
7646            Some(&workflow_type),
7647            &update_name,
7648            "register_update_avro_value",
7649        ) {
7650            return;
7651        }
7652        self.updates.entry(workflow_type).or_default().insert(
7653            update_name,
7654            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7655        );
7656    }
7657
7658    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7659        self.validate_registration()?;
7660        self.sticky_registration_confirmed
7661            .store(false, Ordering::SeqCst);
7662        self.session_registration_confirmed
7663            .store(false, Ordering::SeqCst);
7664        for capability in &self.resource_capabilities {
7665            worker_session::validate_resource_capability(capability)?;
7666        }
7667        self.local_registration_confirmed
7668            .store(false, Ordering::SeqCst);
7669        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7670            return Err(Error::CooperativeCancellationUnavailable(
7671                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7672            ));
7673        }
7674        let mut command_contracts = serde_json::Map::new();
7675        for workflow_type in self.workflows.keys() {
7676            let mut queries = self
7677                .queries
7678                .get(workflow_type)
7679                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7680                .unwrap_or_default();
7681            queries.sort();
7682            let mut updates = self
7683                .updates
7684                .get(workflow_type)
7685                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7686                .unwrap_or_default();
7687            updates.sort();
7688            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
7689            command_contracts.insert(
7690                workflow_type.clone(),
7691                json!({
7692                    "queries": queries,
7693                    "query_contracts": argument_vector_contracts(&queries),
7694                    "signals": signals,
7695                    "signal_contracts": argument_vector_contracts(&signals),
7696                    "updates": updates,
7697                    "update_contracts": argument_vector_contracts(&updates),
7698                    "update_validators": [],
7699                }),
7700            );
7701        }
7702
7703        self.cooperative_registration_confirmed
7704            .store(false, Ordering::SeqCst);
7705        let response = self
7706            .client
7707            .register_worker_with_definition_fingerprints(
7708                &self.worker_id,
7709                &self.task_queue,
7710                self.workflows.keys().cloned().collect(),
7711                self.activities.keys().cloned().collect(),
7712                self.max_concurrent_workflow_tasks,
7713                self.max_concurrent_activity_tasks,
7714                [
7715                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7716                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7717                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7718                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7719                    self.client
7720                        .local_activities_enabled
7721                        .then(|| "local_activities".to_string()),
7722                    self.client
7723                        .worker_sessions_enabled
7724                        .then(|| "worker_sessions".to_string()),
7725                    self.client
7726                        .sticky_cache
7727                        .is_some()
7728                        .then(|| "sticky_execution".to_string()),
7729                    self.cooperative_cancellation_enabled
7730                        .then(|| "cooperative_cancellation".to_string()),
7731                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7732                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7733                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7734                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7735                ]
7736                .into_iter()
7737                .flatten()
7738                .chain(self.resource_capabilities.iter().cloned())
7739                .collect(),
7740                Value::Object(command_contracts),
7741                Some(
7742                    self.workflows
7743                        .iter()
7744                        .filter_map(|(workflow_type, workflow)| {
7745                            workflow
7746                                .definition_fingerprint
7747                                .as_ref()
7748                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7749                        })
7750                        .collect(),
7751                ),
7752            )
7753            .await?;
7754        if self.cooperative_cancellation_enabled && response.registered {
7755            self.cooperative_registration_confirmed
7756                .store(true, Ordering::SeqCst);
7757        }
7758        if self.client.local_activities_enabled && response.registered {
7759            self.local_registration_confirmed
7760                .store(true, Ordering::SeqCst);
7761        }
7762        if self.client.worker_sessions_enabled && response.registered {
7763            self.session_registration_confirmed
7764                .store(true, Ordering::SeqCst);
7765        }
7766        if self.client.sticky_cache.is_some() && response.registered {
7767            self.sticky_registration_confirmed
7768                .store(true, Ordering::SeqCst);
7769        }
7770        Ok(response)
7771    }
7772
7773    /// Run until shutdown or a terminal worker error occurs.
7774    ///
7775    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7776    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7777    /// authentication, protocol, and other non-retryable failures are returned.
7778    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7779    /// poll and heartbeat outages beyond the ordinary retry budget.
7780    pub async fn run(&self) -> Result<()> {
7781        self.run_until(std::future::pending::<()>()).await
7782    }
7783
7784    /// Run until `shutdown` resolves or a terminal worker error occurs.
7785    ///
7786    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7787    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7788    where
7789        F: Future<Output = ()>,
7790    {
7791        let _clear_cache_on_drop =
7792            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
7793        let stop = Arc::new(AtomicBool::new(false));
7794        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7795        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7796        worker.run_stop = Some(Arc::clone(&stop));
7797        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7798        tokio::pin!(run);
7799        tokio::pin!(shutdown);
7800        tokio::select! {
7801            result = &mut run => result,
7802            _ = &mut shutdown => {
7803                stop.store(true, Ordering::SeqCst);
7804                run.await
7805            }
7806        }
7807    }
7808
7809    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7810        let mut worker = self.clone();
7811        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7812            policy: self.retry_policy,
7813            stop,
7814            workflow_completion_retry_deadline: None,
7815        });
7816        worker
7817    }
7818
7819    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7820        let registration = self.register().await?;
7821        if !registration.registered {
7822            return Err(Error::WorkerLoop(format!(
7823                "worker registration for {:?} was not accepted",
7824                self.worker_id
7825            )));
7826        }
7827        let registered_worker_id = registration.worker_id.clone();
7828        let primary = self.run_registered_until(stop, registration).await;
7829        let primary = match (primary, self.close_worker_sessions().await) {
7830            (Ok(()), result) => result,
7831            (Err(error), Ok(())) => Err(error),
7832            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7833                primary: Box::new(primary),
7834                deregistration: Box::new(close),
7835            }),
7836        };
7837        self.session_registration_confirmed
7838            .store(false, Ordering::SeqCst);
7839        self.cooperative_registration_confirmed
7840            .store(false, Ordering::SeqCst);
7841        self.local_registration_confirmed
7842            .store(false, Ordering::SeqCst);
7843        let deregistration = self
7844            .client
7845            .deregister_worker_registration(&registered_worker_id)
7846            .await;
7847        self.sticky_registration_confirmed
7848            .store(false, Ordering::SeqCst);
7849        self.client.clear_sticky_cache()?;
7850
7851        match (primary, deregistration) {
7852            (Ok(()), Ok(_)) => Ok(()),
7853            (Ok(()), Err(deregistration)) => Err(deregistration),
7854            (Err(primary), Ok(_)) => Err(primary),
7855            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7856                primary: Box::new(primary),
7857                deregistration: Box::new(deregistration),
7858            }),
7859        }
7860    }
7861
7862    async fn run_registered_until(
7863        &self,
7864        stop: Arc<AtomicBool>,
7865        registration: RegisterWorkerResponse,
7866    ) -> Result<()> {
7867        let heartbeat_interval = Duration::from_secs(
7868            registration
7869                .heartbeat_interval_seconds
7870                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7871        );
7872        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7873        // from the completion of the preceding attempt, including its bounded
7874        // retries. A fixed-epoch interval can leave an already-due tick queued
7875        // while an acknowledgement is slow, producing a catch-up heartbeat as
7876        // soon as that request completes.
7877        let heartbeat = tokio::time::sleep(Duration::ZERO);
7878        tokio::pin!(heartbeat);
7879        // Poll responses may already have leased server-side work by the time
7880        // they become ready, so each poller owns its responses through
7881        // completion or failure instead of racing raw polls in this select.
7882        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7883            let worker = self.clone();
7884            let stop = Arc::clone(&stop);
7885            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7886        });
7887        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7888            let worker = self.clone();
7889            let stop = Arc::clone(&stop);
7890            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7891        });
7892        let mut query_poller = (!self.queries.is_empty()).then(|| {
7893            let worker = self.clone();
7894            let stop = Arc::clone(&stop);
7895            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7896        });
7897
7898        loop {
7899            tokio::select! {
7900                _ = wait_for_worker_stop(&stop) => {
7901                    stop.store(true, Ordering::SeqCst);
7902                    break;
7903                }
7904                _ = &mut heartbeat => {
7905                    let result = self.retry_worker_operation(|| {
7906                        self.client.heartbeat_worker_with_sessions(
7907                            &self.worker_id,
7908                            self.max_concurrent_workflow_tasks,
7909                            self.max_concurrent_activity_tasks,
7910                            self.client.worker_sessions_enabled.then(|| self.session_available()),
7911                        )
7912                    }).await;
7913                    heartbeat
7914                        .as_mut()
7915                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7916                    match result {
7917                        Ok(Some(acknowledgement)) => {
7918                            if let Some(observer) = &self.heartbeat_observer {
7919                                observer(&WorkerHeartbeatObservation {
7920                                    worker_id: self.worker_id.clone(),
7921                                    task_queue: self.task_queue.clone(),
7922                                    acknowledged_at_unix_millis: SystemTime::now()
7923                                        .duration_since(UNIX_EPOCH)
7924                                        .unwrap_or_default()
7925                                        .as_millis()
7926                                        .min(u64::MAX as u128)
7927                                        as u64,
7928                                    acknowledgement,
7929                                });
7930                            }
7931                        }
7932                        Ok(None) => break,
7933                        Err(error) => {
7934                            stop.store(true, Ordering::SeqCst);
7935                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7936                            return Err(error);
7937                        }
7938                    }
7939                }
7940                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
7941                    workflow_poller = None;
7942                    let stopped_by_server = stop.load(Ordering::SeqCst);
7943                    stop.store(true, Ordering::SeqCst);
7944                    let poller_result = optional_poller_result("workflow", result);
7945                    let join_result =
7946                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7947                    poller_result?;
7948                    join_result?;
7949                    if stopped_by_server {
7950                        return Ok(());
7951                    }
7952                    return Err(Error::WorkerLoop(
7953                        "workflow poller stopped unexpectedly".to_string(),
7954                    ));
7955                }
7956                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
7957                    activity_poller = None;
7958                    let stopped_by_server = stop.load(Ordering::SeqCst);
7959                    stop.store(true, Ordering::SeqCst);
7960                    let poller_result = optional_poller_result("activity", result);
7961                    let join_result =
7962                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7963                    poller_result?;
7964                    join_result?;
7965                    if stopped_by_server {
7966                        return Ok(());
7967                    }
7968                    return Err(Error::WorkerLoop(
7969                        "activity poller stopped unexpectedly".to_string(),
7970                    ));
7971                }
7972                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
7973                    query_poller = None;
7974                    let stopped_by_server = stop.load(Ordering::SeqCst);
7975                    stop.store(true, Ordering::SeqCst);
7976                    let poller_result = optional_poller_result("query", result);
7977                    let join_result =
7978                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7979                    poller_result?;
7980                    join_result?;
7981                    if stopped_by_server {
7982                        return Ok(());
7983                    }
7984                    return Err(Error::WorkerLoop(
7985                        "query poller stopped unexpectedly".to_string(),
7986                    ));
7987                }
7988            }
7989        }
7990
7991        join_pollers(
7992            workflow_poller.take(),
7993            activity_poller.take(),
7994            query_poller.take(),
7995        )
7996        .await
7997    }
7998
7999    /// Poll and settle at most one task from each enabled task family.
8000    ///
8001    /// A workflow may reach its server-enforced run deadline while this worker
8002    /// holds a task. When the completion endpoint authoritatively rejects that
8003    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
8004    /// terminal `run_status=failed`, the workflow tick is considered settled:
8005    /// the late command was not recorded and cannot replace the terminal run.
8006    /// Every other completion rejection remains an error. This worker-level
8007    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
8008    /// only bounds how long a client waits for a result.
8009    ///
8010    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
8011    /// the original [`Error::Http`] status and response body.
8012    pub async fn run_once(&self) -> Result<usize> {
8013        self.validate_registration()?;
8014        if self.client.worker_sessions_enabled {
8015            self.require_session_registration()?;
8016        }
8017        if self.cooperative_cancellation_enabled
8018            && !self
8019                .cooperative_registration_confirmed
8020                .load(Ordering::SeqCst)
8021        {
8022            return Err(Error::CooperativeCancellationUnavailable(
8023                "register this cooperative worker before polling tasks".into(),
8024            ));
8025        }
8026        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
8027        let mut handled = 0;
8028        match worker.poll_workflow_once().await? {
8029            ManagedPollOutcome::Handled => handled += 1,
8030            ManagedPollOutcome::Stop => return Ok(handled),
8031            ManagedPollOutcome::Idle => {}
8032        }
8033        match worker.poll_activity_once().await? {
8034            ManagedPollOutcome::Handled => handled += 1,
8035            ManagedPollOutcome::Stop => return Ok(handled),
8036            ManagedPollOutcome::Idle => {}
8037        }
8038        if !self.queries.is_empty() {
8039            match worker.poll_query_once().await? {
8040                ManagedPollOutcome::Handled => handled += 1,
8041                ManagedPollOutcome::Stop => return Ok(handled),
8042                ManagedPollOutcome::Idle => {}
8043            }
8044        }
8045        Ok(handled)
8046    }
8047
8048    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
8049        if self.client.sticky_cache.is_some()
8050            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
8051        {
8052            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
8053        }
8054        if self.client.local_activities_enabled
8055            && !self.local_registration_confirmed.load(Ordering::SeqCst)
8056        {
8057            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
8058        }
8059        if self.cooperative_cancellation_enabled {
8060            return self.poll_cooperative_workflow_once().await;
8061        }
8062        let poll_request_id = unique_request_id("rust-workflow-poll");
8063        let response = self
8064            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
8065            .await;
8066        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
8067            return Ok(ManagedPollOutcome::Idle);
8068        };
8069        if response.outcome().should_stop() {
8070            return Ok(ManagedPollOutcome::Stop);
8071        }
8072        let memo_updates_supported =
8073            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
8074        let Some(task) = response.task else {
8075            return Ok(ManagedPollOutcome::Idle);
8076        };
8077
8078        let task_id = task.task_id.clone();
8079        let attempt = task.workflow_task_attempt;
8080        let run_id = task.run_id.clone();
8081        let lease_owner = task
8082            .lease_owner
8083            .clone()
8084            .unwrap_or_else(|| self.worker_id.clone());
8085
8086        let decision = match self.execute_workflow_with_local_activities(task).await {
8087            Ok(Some(decision)) => Ok(decision),
8088            Ok(None) => return Ok(ManagedPollOutcome::Handled),
8089            Err(error) => Err(error),
8090        };
8091        self.settle_workflow_task_decision(
8092            &task_id,
8093            &lease_owner,
8094            attempt,
8095            run_id.as_deref(),
8096            decision,
8097            memo_updates_supported,
8098            snapshot,
8099        )
8100        .await
8101    }
8102
8103    #[allow(clippy::too_many_arguments)]
8104    async fn settle_workflow_task_decision(
8105        &self,
8106        task_id: &str,
8107        lease_owner: &str,
8108        attempt: u64,
8109        run_id: Option<&str>,
8110        decision: Result<WorkflowTaskDecision>,
8111        memo_updates_supported: bool,
8112        snapshot: Option<sticky_worker::StickySnapshot>,
8113    ) -> Result<ManagedPollOutcome> {
8114        match decision {
8115            Ok(decision)
8116                if decision.cancellation_delivery.is_some()
8117                    || decision.cancellation_scope_delivery.is_some()
8118                    || decision.cancellation_scope_opening.is_some() =>
8119            {
8120                return Err(Error::CooperativeCancellationUnavailable(
8121                    "worker cancellation delivery has not been negotiated".into(),
8122                ));
8123            }
8124            Ok(decision)
8125                if commands_use_workflow_memo_updates(&decision.commands)
8126                    && !memo_updates_supported =>
8127            {
8128                self.client
8129                    .fail_workflow_task(
8130                        task_id,
8131                        lease_owner,
8132                        attempt,
8133                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8134                    )
8135                    .await?;
8136            }
8137            Ok(decision) if decision.commands.is_empty() => {
8138                // A replay can consume a recorded pending durable command
8139                // without producing a new command. The standalone protocol
8140                // acknowledges that state through the typed waiting outcome;
8141                // an empty completion is rejected by servers that require at
8142                // least one executable command.
8143                self.client
8144                    .fail_workflow_task_with_type(
8145                        task_id,
8146                        lease_owner,
8147                        attempt,
8148                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8149                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8150                    )
8151                    .await?;
8152            }
8153            Ok(decision) => {
8154                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8155                let completion = self
8156                    .client
8157                    .complete_workflow_task_with_message_streams(
8158                        task_id,
8159                        lease_owner,
8160                        attempt,
8161                        decision.commands,
8162                        decision.message_stream_cursors,
8163                        decision.message_stream_waits,
8164                        sticky_claim,
8165                    )
8166                    .await;
8167                if let Err(error) = completion {
8168                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8169                    if !workflow_task_completion_is_terminal_timeout(
8170                        &error, task_id, attempt, run_id,
8171                    ) {
8172                        return Err(error);
8173                    }
8174                }
8175            }
8176            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8177            Err(error) => {
8178                self.discard_sticky_snapshot(snapshot.as_ref())?;
8179                self.client
8180                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8181                    .await?;
8182            }
8183        }
8184
8185        Ok(ManagedPollOutcome::Handled)
8186    }
8187
8188    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8189        while !stop.load(Ordering::SeqCst) {
8190            match self.poll_workflow_once().await {
8191                Ok(ManagedPollOutcome::Stop) => {
8192                    stop.store(true, Ordering::SeqCst);
8193                    break;
8194                }
8195                Err(error) => {
8196                    stop.store(true, Ordering::SeqCst);
8197                    return Err(error);
8198                }
8199                _ => {}
8200            }
8201        }
8202
8203        Ok(())
8204    }
8205
8206    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
8207        if self.client.worker_sessions_enabled {
8208            self.require_session_registration()?;
8209        }
8210        if self.cooperative_cancellation_enabled {
8211            return self.poll_cooperative_activity_once().await;
8212        }
8213        let poll_request_id = unique_request_id("rust-activity-poll");
8214        let response = self
8215            .retry_worker_operation(|| {
8216                self.client.poll_activity_task_response_with_request_id(
8217                    &self.worker_id,
8218                    &self.task_queue,
8219                    self.poll_timeout,
8220                    &poll_request_id,
8221                    0,
8222                )
8223            })
8224            .await;
8225        let response = match response {
8226            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8227            response => response,
8228        };
8229        let Some(response) = self.settle_worker_poll_response(response).await? else {
8230            return Ok(ManagedPollOutcome::Idle);
8231        };
8232        if response.outcome().should_stop() {
8233            return Ok(ManagedPollOutcome::Stop);
8234        }
8235        let Some(task) = response.task else {
8236            return Ok(ManagedPollOutcome::Idle);
8237        };
8238
8239        let session = self.track_session_task(task.worker_session.as_ref())?;
8240        let hydration_claim = task.hydration_claim;
8241        let task = task.task;
8242
8243        let task_id = task.task_id.clone();
8244        let attempt_id = task
8245            .activity_attempt_id
8246            .clone()
8247            .or(task.attempt_id.clone())
8248            .unwrap_or_default();
8249        let lease_owner = task
8250            .lease_owner
8251            .clone()
8252            .unwrap_or_else(|| self.worker_id.clone());
8253        let codec = task.payload_codec.clone();
8254        let result = self
8255            .execute_session_activity_task(task, session, hydration_claim.as_ref())
8256            .await;
8257        match result {
8258            Err(Error::ActivityExecutionAbandoned(_)) => {}
8259            Err(error) if activity_hydration::stopped(&error) => {}
8260            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
8261            Ok(value) => {
8262                let completion = self
8263                    .client
8264                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
8265                    .await;
8266                if let Err(error) = completion {
8267                    if !activity_task_rejection_is_final(&error) {
8268                        return Err(error);
8269                    }
8270                }
8271            }
8272            Err(error) => {
8273                let failure = self
8274                    .client
8275                    .fail_activity_task(
8276                        &task_id,
8277                        &attempt_id,
8278                        &lease_owner,
8279                        error.to_string(),
8280                        false,
8281                    )
8282                    .await;
8283                if let Err(error) = failure {
8284                    if !activity_task_rejection_is_final(&error) {
8285                        return Err(error);
8286                    }
8287                }
8288            }
8289        }
8290
8291        Ok(ManagedPollOutcome::Handled)
8292    }
8293
8294    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8295        // Each lane retains its leased response through callback settlement.
8296        // A bounded independent activity must not occupy the cleanup lane too.
8297        // Preserve the existing serial loop unless cooperation is enabled.
8298        let lane_count = if self.cooperative_cancellation_enabled {
8299            self.max_concurrent_activity_tasks
8300        } else {
8301            1
8302        };
8303        let mut lanes = FuturesUnordered::new();
8304        for _ in 0..lane_count {
8305            let worker = self.clone();
8306            let stop = Arc::clone(&stop);
8307            lanes.push(async move {
8308                while !stop.load(Ordering::SeqCst) {
8309                    match worker.poll_activity_once().await {
8310                        Ok(ManagedPollOutcome::Stop) => {
8311                            stop.store(true, Ordering::SeqCst);
8312                            break;
8313                        }
8314                        Err(error) => {
8315                            stop.store(true, Ordering::SeqCst);
8316                            return Err(error);
8317                        }
8318                        _ => {}
8319                    }
8320                }
8321                Ok(())
8322            });
8323        }
8324        // Join every lane before deregistration, including after one fails.
8325        let mut first_error = None;
8326        while let Some(result) = lanes.next().await {
8327            if let Err(error) = result {
8328                first_error.get_or_insert(error);
8329            }
8330        }
8331        first_error.map_or(Ok(()), Err)
8332    }
8333
8334    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
8335        let poll_request_id = unique_request_id("rust-query-poll");
8336        let response = self
8337            .retry_worker_operation(|| {
8338                self.client.poll_query_task_response_with_request_id(
8339                    &self.worker_id,
8340                    &self.task_queue,
8341                    self.poll_timeout,
8342                    &poll_request_id,
8343                    0,
8344                )
8345            })
8346            .await;
8347        let Some(response) = self.settle_worker_poll_response(response).await? else {
8348            return Ok(ManagedPollOutcome::Idle);
8349        };
8350        if response.outcome().should_stop() {
8351            return Ok(ManagedPollOutcome::Stop);
8352        }
8353        let Some(task) = response.task else {
8354            return Ok(ManagedPollOutcome::Idle);
8355        };
8356
8357        let query_task_id = task.query_task_id.clone();
8358        let attempt = task.query_task_attempt;
8359        let lease_owner = task
8360            .lease_owner
8361            .clone()
8362            .unwrap_or_else(|| self.worker_id.clone());
8363        let codec = task.payload_codec.clone();
8364
8365        match self.execute_query_task(task).await {
8366            Ok(value) => {
8367                let result_envelope = match encode_typed_envelope(&value, &codec) {
8368                    Ok(result_envelope) => result_envelope,
8369                    Err(error) => {
8370                        let failure = self
8371                            .client
8372                            .fail_query_task(
8373                                &query_task_id,
8374                                &lease_owner,
8375                                attempt,
8376                                error.to_string(),
8377                                "query_result_encode_failed",
8378                                "QueryResultEncodeFailed",
8379                            )
8380                            .await;
8381                        if let Err(error) = failure {
8382                            if !query_task_rejection_is_final(&error) {
8383                                return Err(error);
8384                            }
8385                        }
8386                        return Ok(ManagedPollOutcome::Handled);
8387                    }
8388                };
8389
8390                if let Err(error) = self
8391                    .client
8392                    .complete_query_task_with_envelope(
8393                        &query_task_id,
8394                        &lease_owner,
8395                        attempt,
8396                        value.clone().into_json()?,
8397                        result_envelope,
8398                    )
8399                    .await
8400                {
8401                    if !query_task_rejection_is_final(&error) {
8402                        return Err(error);
8403                    }
8404                }
8405            }
8406            Err(failure) => {
8407                let result = self
8408                    .client
8409                    .fail_query_task(
8410                        &query_task_id,
8411                        &lease_owner,
8412                        attempt,
8413                        failure.message,
8414                        failure.reason,
8415                        failure.failure_type,
8416                    )
8417                    .await;
8418                if let Err(error) = result {
8419                    if !query_task_rejection_is_final(&error) {
8420                        return Err(error);
8421                    }
8422                }
8423            }
8424        }
8425
8426        Ok(ManagedPollOutcome::Handled)
8427    }
8428
8429    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8430        while !stop.load(Ordering::SeqCst) {
8431            match self.poll_query_once().await {
8432                Ok(ManagedPollOutcome::Stop) => {
8433                    stop.store(true, Ordering::SeqCst);
8434                    break;
8435                }
8436                Err(error) => {
8437                    stop.store(true, Ordering::SeqCst);
8438                    return Err(error);
8439                }
8440                _ => {}
8441            }
8442        }
8443
8444        Ok(())
8445    }
8446
8447    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
8448    where
8449        F: FnMut() -> Fut,
8450        Fut: Future<Output = Result<T>>,
8451    {
8452        let mut retries = 0;
8453
8454        loop {
8455            if self
8456                .run_stop
8457                .as_ref()
8458                .is_some_and(|stop| stop.load(Ordering::SeqCst))
8459            {
8460                return Ok(None);
8461            }
8462            match operation().await {
8463                Err(error)
8464                    if (workflow_hydration::stopped(&error)
8465                        || activity_hydration::stopped(&error))
8466                        && self
8467                            .run_stop
8468                            .as_ref()
8469                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
8470                {
8471                    return Ok(None);
8472                }
8473                Err(error)
8474                    if worker_operation_is_retryable(&error)
8475                        && (retries < self.retry_policy.max_retries
8476                            || (self.recover_transient_outages
8477                                && self.run_stop.is_some()
8478                                && self.retry_policy.max_retries > 0)) =>
8479                {
8480                    retries = retries.saturating_add(1);
8481                    let delay = worker_retry_delay(self.retry_policy, retries)
8482                        .max(Duration::from_millis(1));
8483                    if let Some(stop) = &self.run_stop {
8484                        tokio::select! {
8485                            _ = tokio::time::sleep(delay) => {}
8486                            _ = wait_for_worker_stop(stop) => return Ok(None),
8487                        }
8488                    } else {
8489                        tokio::time::sleep(delay).await;
8490                    }
8491                }
8492                result => return result.map(Some),
8493            }
8494        }
8495    }
8496
8497    async fn settle_worker_poll_response<T>(
8498        &self,
8499        response: Result<Option<T>>,
8500    ) -> Result<Option<T>> {
8501        match response {
8502            Ok(response) => Ok(response),
8503            Err(error) => {
8504                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
8505                    return Err(error);
8506                };
8507                let minimum_delay = self
8508                    .retry_policy
8509                    .initial_backoff
8510                    .max(Duration::from_millis(1));
8511                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
8512                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
8513                Ok(None)
8514            }
8515        }
8516    }
8517
8518    async fn execute_query_task(
8519        &self,
8520        mut task: QueryTask,
8521    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8522        validate_query_task_payloads(&task).map_err(|error| {
8523            QueryTaskExecutionFailure::new(
8524                "query_payload_decode_failed",
8525                error.to_string(),
8526                "QueryPayloadDecodeFailed",
8527            )
8528        })?;
8529
8530        if !self.workflows.contains_key(&task.workflow_type) {
8531            return Err(QueryTaskExecutionFailure::new(
8532                "query_workflow_type_not_registered",
8533                format!("no workflow registered for type {:?}", task.workflow_type),
8534                "WorkflowTypeNotRegistered",
8535            ));
8536        }
8537
8538        let Some(handlers) = self.queries.get(&task.workflow_type) else {
8539            return Err(QueryTaskExecutionFailure::new(
8540                "query_handler_unavailable",
8541                format!(
8542                    "query handlers are unavailable for workflow type {:?}",
8543                    task.workflow_type
8544                ),
8545                "QueryHandlerUnavailable",
8546            ));
8547        };
8548        let Some(query) = handlers.get(&task.query_name) else {
8549            return Err(QueryTaskExecutionFailure::new(
8550                "rejected_unknown_query",
8551                format!("unknown query {:?}", task.query_name),
8552                "QueryFailed",
8553            ));
8554        };
8555
8556        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
8557            .map_err(|error| {
8558            QueryTaskExecutionFailure::new(
8559                "query_payload_decode_failed",
8560                format!("cannot decode query arguments: {error}"),
8561                "QueryPayloadDecodeFailed",
8562            )
8563        })?;
8564        let workflow_input_typed =
8565            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
8566                .map_err(|error| {
8567                    QueryTaskExecutionFailure::new(
8568                        "query_workflow_state_unavailable",
8569                        format!("cannot decode workflow start input: {error}"),
8570                        "QueryWorkflowStateUnavailable",
8571                    )
8572                })?;
8573        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
8574            QueryTaskExecutionFailure::new(
8575                "query_workflow_state_unavailable",
8576                format!("cannot project workflow start input: {error}"),
8577                "QueryWorkflowStateUnavailable",
8578            )
8579        })?;
8580        hydrate_query_history_from_export(&mut task).map_err(|error| {
8581            QueryTaskExecutionFailure::new(
8582                "query_workflow_state_unavailable",
8583                format!("cannot restore query history snapshot: {error}"),
8584                "QueryWorkflowStateUnavailable",
8585            )
8586        })?;
8587        enrich_query_history_from_export(&mut task).map_err(|error| {
8588            QueryTaskExecutionFailure::new(
8589                "query_workflow_state_unavailable",
8590                format!("cannot restore compact query history payloads: {error}"),
8591                "QueryWorkflowStateUnavailable",
8592            )
8593        })?;
8594        let signal_events = query_signal_events(&task).map_err(|error| {
8595            QueryTaskExecutionFailure::new(
8596                "query_workflow_state_unavailable",
8597                format!("cannot decode committed workflow signals: {error}"),
8598                "QueryWorkflowStateUnavailable",
8599            )
8600        })?;
8601        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8602        let context = QueryContext {
8603            workflow_id: task.workflow_id,
8604            run_id: task.run_id,
8605            workflow_type: task.workflow_type.clone(),
8606            run_status: task.run_status,
8607            workflow_input,
8608            workflow_input_avro_value: workflow_input_typed.clone(),
8609            history_events: Arc::clone(&history_events),
8610            signal_events: Arc::new(signal_events),
8611        };
8612
8613        let future = match query {
8614            RegisteredQuery::Snapshot(handler) => handler(context, args),
8615            RegisteredQuery::Replayed {
8616                state_type,
8617                handler,
8618            } => {
8619                let workflow = self
8620                    .workflows
8621                    .get(&task.workflow_type)
8622                    .expect("workflow registration was checked above");
8623                if workflow.state_type != Some(*state_type) {
8624                    return Err(QueryTaskExecutionFailure::new(
8625                        "query_workflow_state_unavailable",
8626                        "replayed query state type does not match its workflow registration",
8627                        "QueryWorkflowStateUnavailable",
8628                    ));
8629                }
8630                let replay = workflow.replay.as_ref().ok_or_else(|| {
8631                    QueryTaskExecutionFailure::new(
8632                        "query_workflow_state_unavailable",
8633                        format!(
8634                            "workflow type {:?} is not registered for instance-state replay",
8635                            task.workflow_type
8636                        ),
8637                        "QueryWorkflowStateUnavailable",
8638                    )
8639                })?;
8640                let workflow_state = Arc::new(Mutex::new(
8641                    WorkflowState::new_with_identity(
8642                        history_events.as_ref().clone(),
8643                        context.workflow_id.clone(),
8644                        context.run_id.clone(),
8645                        self.task_queue.clone(),
8646                        task.payload_codec,
8647                        None,
8648                    )
8649                    .map_err(|error| {
8650                        QueryTaskExecutionFailure::new(
8651                            "query_workflow_state_unavailable",
8652                            format!("workflow replay failed before query: {error}"),
8653                            "QueryWorkflowStateUnavailable",
8654                        )
8655                    })?,
8656                ));
8657                let workflow_context = WorkflowContext {
8658                    state: workflow_state,
8659                    cancellation_scope_id: "root".into(),
8660                };
8661                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
8662                let mut cx = TaskContext::from_waker(noop_waker_ref());
8663                let outcome = {
8664                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8665                        .map_err(|error| {
8666                            QueryTaskExecutionFailure::new(
8667                                "query_workflow_state_unavailable",
8668                                error.to_string(),
8669                                "QueryWorkflowStateUnavailable",
8670                            )
8671                        })?;
8672                    invocation.future.as_mut().poll(&mut cx)
8673                };
8674                match outcome {
8675                    Poll::Ready(Ok(_)) => {
8676                        workflow_context
8677                            .ensure_history_consumed()
8678                            .map_err(|error| {
8679                                QueryTaskExecutionFailure::new(
8680                                    "query_workflow_state_unavailable",
8681                                    format!("workflow replay failed before query: {error}"),
8682                                    "QueryWorkflowStateUnavailable",
8683                                )
8684                            })?;
8685                    }
8686                    Poll::Ready(Err(error)) => {
8687                        return Err(QueryTaskExecutionFailure::new(
8688                            "query_workflow_state_unavailable",
8689                            format!("workflow replay failed before query: {error}"),
8690                            "QueryWorkflowStateUnavailable",
8691                        ));
8692                    }
8693                    Poll::Pending => {
8694                        let commands = workflow_context.take_commands().map_err(|error| {
8695                            QueryTaskExecutionFailure::new(
8696                                "query_workflow_state_unavailable",
8697                                format!("workflow replay failed before query: {error}"),
8698                                "QueryWorkflowStateUnavailable",
8699                            )
8700                        })?;
8701                        if commands.is_empty()
8702                            && !workflow_context
8703                                .matched_recorded_pending()
8704                                .map_err(|error| {
8705                                    QueryTaskExecutionFailure::new(
8706                                        "query_workflow_state_unavailable",
8707                                        format!("workflow replay failed before query: {error}"),
8708                                        "QueryWorkflowStateUnavailable",
8709                                    )
8710                                })?
8711                        {
8712                            return Err(QueryTaskExecutionFailure::new(
8713                                "query_workflow_state_unavailable",
8714                                "workflow replay yielded without a durable command",
8715                                "QueryWorkflowStateUnavailable",
8716                            ));
8717                        }
8718                    }
8719                }
8720                let state = (invocation.snapshot)().map_err(|error| {
8721                    QueryTaskExecutionFailure::new(
8722                        "query_workflow_state_unavailable",
8723                        format!("cannot snapshot replayed workflow state: {error}"),
8724                        "QueryWorkflowStateUnavailable",
8725                    )
8726                })?;
8727                handler(context, state, args).map_err(|message| {
8728                    QueryTaskExecutionFailure::new(
8729                        "query_workflow_state_unavailable",
8730                        message,
8731                        "QueryWorkflowStateUnavailable",
8732                    )
8733                })?
8734            }
8735        };
8736
8737        future.await.map_err(|error| {
8738            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8739        })
8740    }
8741
8742    #[cfg(test)]
8743    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8744        Ok(self.execute_workflow_task_decision(task)?.commands)
8745    }
8746
8747    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8748        self.execute_workflow_task_decision_with_cancellation(task, None)
8749    }
8750
8751    fn execute_workflow_task_decision_with_cancellation(
8752        &self,
8753        task: WorkflowTask,
8754        observation: Option<&CancellationRequest>,
8755    ) -> Result<WorkflowTaskDecision> {
8756        match self.prepare_workflow_task_execution(task, observation)? {
8757            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8758            PreparedWorkflowTask::Execution {
8759                task,
8760                context,
8761                mut future,
8762            } => {
8763                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8764                self.finish_workflow_task_execution(&task, &context, outcome)
8765            }
8766        }
8767    }
8768
8769    fn prepare_workflow_task_execution(
8770        &self,
8771        task: WorkflowTask,
8772        observation: Option<&CancellationRequest>,
8773    ) -> Result<PreparedWorkflowTask> {
8774        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8775            && !self.cooperative_cancellation_enabled
8776        {
8777            return Err(Error::CancellationScopeExecutionUnavailable);
8778        }
8779        validate_workflow_task_payloads(&task)?;
8780        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8781            &task.history_events,
8782            self.allow_cancellation_scope_authoring,
8783            self.allow_cancellation_scope_delivery,
8784        )?;
8785        let cancellation_history = if let Some(observation) = observation {
8786            observation.validate_observation()?;
8787            cooperative_cancellation::cancellation_claim(&task)?;
8788            let canonical = CancellationHistory::from_events(
8789                &task.history_events,
8790                task.run_id.as_deref().unwrap_or_default(),
8791                Some(observation),
8792            )?;
8793            if canonical.request_index >= task.history_events.len() {
8794                return Err(Error::InvalidCooperativeCancellation(
8795                    "workflow replay requires the observed canonical request".into(),
8796                ));
8797            }
8798            Some(canonical)
8799        } else {
8800            None
8801        };
8802        if let Some(update_id) = task
8803            .workflow_update_id
8804            .as_deref()
8805            .filter(|update_id| !update_id.is_empty())
8806        {
8807            if self.allow_cancellation_scope_delivery {
8808                return Err(Error::CancellationScopeExecutionUnavailable);
8809            }
8810            CancellationHistory::from_events(
8811                &task.history_events,
8812                task.run_id.as_deref().unwrap_or_default(),
8813                None,
8814            )?;
8815            return self
8816                .execute_update_task(&task, update_id)
8817                .map(WorkflowTaskDecision::without_message_streams)
8818                .map(PreparedWorkflowTask::Decision);
8819        }
8820
8821        let workflow = self
8822            .workflows
8823            .get(&task.workflow_type)
8824            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
8825        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8826        let resume_signal = decode_resume_signal(&task)?;
8827        let history_budget = WorkflowHistoryBudget {
8828            event_count: task
8829                .total_history_events
8830                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
8831            size_bytes: task.history_size_bytes,
8832            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
8833            pressure: task.history_budget_pressure.clone(),
8834        };
8835        let workflow_command_identity = task
8836            .workflow_command_id
8837            .clone()
8838            .filter(|identity| !identity.is_empty())
8839            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
8840            .unwrap_or_default();
8841        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
8842            task.history_events.clone(),
8843            task.workflow_id.clone(),
8844            task.run_id.clone(),
8845            self.task_queue.clone(),
8846            task.payload_codec.clone(),
8847            resume_signal,
8848            self.allow_cancellation_scope_authoring,
8849            self.allow_cancellation_scope_delivery,
8850        )?;
8851        workflow_state.history_budget = history_budget;
8852        workflow_state.workflow_command_identity = workflow_command_identity;
8853        if let Some(canonical) = cancellation_history {
8854            workflow_state.cancellation_history = canonical;
8855            workflow_state.cancellation_delivery_enabled = true;
8856        }
8857        if workflow_state.cancellation_history.request.is_none() {
8858            workflow_state.cancel_requested = task.cancel_requested;
8859        }
8860        let state = Arc::new(Mutex::new(workflow_state));
8861        let ctx = WorkflowContext {
8862            state,
8863            cancellation_scope_id: "root".into(),
8864        };
8865        let future = (workflow.execute)(ctx.clone(), input);
8866        Ok(PreparedWorkflowTask::Execution {
8867            task,
8868            context: ctx,
8869            future,
8870        })
8871    }
8872
8873    fn poll_workflow_future(
8874        ctx: &WorkflowContext,
8875        future: &mut WorkflowFuture,
8876    ) -> Result<Poll<Result<AvroValue>>> {
8877        let mut cx = TaskContext::from_waker(noop_waker_ref());
8878        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
8879        Ok(future.as_mut().poll(&mut cx))
8880    }
8881
8882    fn finish_workflow_task_execution(
8883        &self,
8884        task: &WorkflowTask,
8885        ctx: &WorkflowContext,
8886        outcome: Poll<Result<AvroValue>>,
8887    ) -> Result<WorkflowTaskDecision> {
8888        if !ctx
8889            .state
8890            .lock()
8891            .map_err(|_| Error::WorkflowStatePoisoned)?
8892            .local_activity_requests
8893            .is_empty()
8894        {
8895            return Err(Error::CooperativeCancellationUnavailable(
8896                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
8897            ));
8898        }
8899        let awaiting_canonical_boundary = {
8900            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8901            state.cancellation_delivery_intent.is_some()
8902                || state.cancellation_scope_opening.is_some()
8903                || state
8904                    .scope_delivery
8905                    .as_ref()
8906                    .is_some_and(|replay| replay.intent.is_some())
8907        };
8908        if awaiting_canonical_boundary {
8909            // A private delivery intent never becomes an application error.
8910            // Even a custom future which ignores a pending durable call cannot
8911            // publish terminal commands before canonical delivery and replay.
8912            if let Poll::Ready(Err(error)) = outcome {
8913                if workflow_task_integrity_error(&error) {
8914                    return Err(error);
8915                }
8916            }
8917            return self.message_stream_decision(&ctx, ctx.take_commands()?);
8918        }
8919
8920        match outcome {
8921            Poll::Ready(Ok(result)) => {
8922                ctx.ensure_history_consumed()?;
8923                let result = encode_typed_envelope(&result, &task.payload_codec)?;
8924                let mut commands = ctx.take_commands()?;
8925                commands.push(json!({
8926                    "type": "complete_workflow",
8927                    "result": result
8928                }));
8929                self.message_stream_decision(&ctx, commands)
8930            }
8931            Poll::Ready(Err(error)) => {
8932                if let Error::ContinueAsNew(request) = error {
8933                    let mut commands = ctx.take_commands()?;
8934                    if let Some(command) = ctx.continue_as_new_command(request)? {
8935                        commands.push(command);
8936                    }
8937                    ctx.ensure_history_consumed()?;
8938                    return self.message_stream_decision(&ctx, commands);
8939                }
8940                if workflow_task_integrity_error(&error) {
8941                    // Replay and protocol failures describe the workflow-task
8942                    // decision itself. Preserve their specific failure reason
8943                    // instead of replacing it with the derivative fact that
8944                    // recorded commands remain unconsumed.
8945                    return Err(error);
8946                }
8947                // A handler error must not hide a committed durable command that
8948                // upgraded workflow code no longer consumes.
8949                ctx.ensure_history_consumed()?;
8950                let mut commands = ctx.take_commands()?;
8951                commands.push(workflow_failure_command(
8952                    &error,
8953                    recorded_activity_failure_boundary(&ctx, &error),
8954                ));
8955                self.message_stream_decision(&ctx, commands)
8956            }
8957            Poll::Pending => {
8958                let commands = ctx.take_commands()?;
8959                if commands.is_empty() && !ctx.matched_recorded_pending()? {
8960                    Err(Error::WorkflowYieldedWithoutCommand)
8961                } else {
8962                    self.message_stream_decision(&ctx, commands)
8963                }
8964            }
8965        }
8966    }
8967
8968    fn message_stream_decision(
8969        &self,
8970        ctx: &WorkflowContext,
8971        commands: Vec<Value>,
8972    ) -> Result<WorkflowTaskDecision> {
8973        if !self.cooperative_cancellation_enabled
8974            && commands.iter().any(|command| {
8975                command["type"] == "schedule_activity"
8976                    && command.get("cancellation_policy").is_some()
8977            })
8978        {
8979            return Err(Error::CooperativeCancellationUnavailable(format!(
8980                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8981                self.worker_id,
8982            )));
8983        }
8984        if !self.cooperative_cancellation_enabled
8985            && commands.iter().any(|command| {
8986                command["type"] == "start_child_workflow"
8987                    && (command["parent_close_policy"] == "request_cancellation"
8988                        || matches!(
8989                            command["cancellation_policy"].as_str(),
8990                            Some("try_cancel" | "wait_cancellation_completed")
8991                        ))
8992            })
8993        {
8994            return Err(Error::CooperativeCancellationUnavailable(format!(
8995                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8996                self.worker_id,
8997            )));
8998        }
8999        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
9000        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9001        let scope_delivery = state
9002            .scope_delivery
9003            .as_ref()
9004            .and_then(|replay| replay.intent.clone());
9005        if scope_delivery
9006            .as_ref()
9007            .is_some_and(|intent| commands.len() != intent.command_count)
9008        {
9009            return Err(invalid_recorded_history(
9010                "cancellation_scope_pending_call_escaped",
9011                scope_delivery.as_ref().unwrap().boundary.sequence,
9012                "commands preceding the pending scoped call",
9013                "commands after suspension",
9014                "workflow cannot publish beyond an uncommitted scope delivery",
9015            ));
9016        }
9017        if let Some(opening) = &state.cancellation_scope_opening {
9018            if commands.len() != opening.command_count {
9019                return Err(invalid_recorded_history(
9020                    "cancellation_scope_pending_call_escaped",
9021                    opening.sequence,
9022                    "commands before original scope opening",
9023                    "commands after suspended opening",
9024                    "workflow cannot publish beyond an uncommitted scope opening",
9025                ));
9026            }
9027        }
9028        if state.cancellation_delivery_intent.is_some()
9029            && commands.len() != state.cancellation_delivery_command_count
9030        {
9031            return Err(invalid_recorded_history(
9032                "cooperative_cancellation_pending_call_escaped",
9033                state
9034                    .cancellation_delivery_intent
9035                    .as_ref()
9036                    .expect("pending delivery")
9037                    .sequence,
9038                "only commands preceding the pending cancellation call",
9039                "commands authored after a suspended call",
9040                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
9041            ));
9042        }
9043        Ok(WorkflowTaskDecision {
9044            commands,
9045            message_stream_cursors,
9046            message_stream_waits,
9047            cancellation_delivery: state.cancellation_delivery_intent.clone(),
9048            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
9049            cancellation_scope_delivery: scope_delivery,
9050        })
9051    }
9052
9053    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
9054        if !self.workflows.contains_key(&task.workflow_type) {
9055            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
9056        }
9057
9058        let accepted = task.history_events.iter().rev().find_map(|event| {
9059            (event.event_type == "UpdateAccepted"
9060                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
9061            .then_some(&event.payload)
9062        });
9063        let update_name = accepted
9064            .and_then(|payload| payload.get("update_name"))
9065            .and_then(Value::as_str)
9066            .or(task.update_name.as_deref())
9067            .unwrap_or_default();
9068        let Some(handler) = self
9069            .updates
9070            .get(&task.workflow_type)
9071            .and_then(|handlers| handlers.get(update_name))
9072        else {
9073            return Ok(vec![json!({
9074                "type": "fail_update",
9075                "update_id": update_id,
9076                "message": format!(
9077                    "no update handler is registered for {}.{update_name}",
9078                    task.workflow_type
9079                ),
9080                "exception_type": "UnknownUpdate",
9081                "non_retryable": true,
9082            })]);
9083        };
9084        let arguments = accepted
9085            .and_then(|payload| payload.get("arguments"))
9086            .or(task.arguments.as_ref());
9087        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9088        let workflow_input_avro_value =
9089            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9090        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9091        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9092        let context = QueryContext {
9093            workflow_id: task.workflow_id.clone(),
9094            run_id: task.run_id.clone(),
9095            workflow_type: task.workflow_type.clone(),
9096            run_status: Some("running".to_string()),
9097            workflow_input,
9098            workflow_input_avro_value,
9099            history_events: Arc::new(task.history_events.clone()),
9100            signal_events: Arc::new(signal_events),
9101        };
9102        let mut future = handler(context, arguments);
9103        let mut cx = TaskContext::from_waker(noop_waker_ref());
9104
9105        match future.as_mut().poll(&mut cx) {
9106            Poll::Ready(Ok(result)) => Ok(vec![json!({
9107                "type": "complete_update",
9108                "update_id": update_id,
9109                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9110            })]),
9111            Poll::Ready(Err(error)) => Ok(vec![json!({
9112                "type": "fail_update",
9113                "update_id": update_id,
9114                "message": error.to_string(),
9115                "exception_type": "UpdateFailed",
9116                "non_retryable": true,
9117            })]),
9118            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9119        }
9120    }
9121
9122    #[cfg(test)]
9123    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9124        self.execute_session_activity_task(task, None, None).await
9125    }
9126
9127    async fn execute_session_activity_task(
9128        &self,
9129        task: ActivityTask,
9130        worker_session: Option<WorkerSession>,
9131        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9132    ) -> Result<AvroValue> {
9133        validate_activity_task_payloads(&task)?;
9134        if worker_session.is_some() {
9135            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
9136                || task
9137                    .activity_attempt_id
9138                    .as_deref()
9139                    .or(task.attempt_id.as_deref())
9140                    .is_none_or(str::is_empty)
9141                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
9142            {
9143                return Err(Error::ActivityExecutionAbandoned(
9144                    "session activity requires this worker's exact immutable claim".into(),
9145                ));
9146            }
9147        }
9148
9149        let handler = self
9150            .activities
9151            .get(&task.activity_type)
9152            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
9153        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9154        let attempt_id = task
9155            .activity_attempt_id
9156            .clone()
9157            .or(task.attempt_id.clone())
9158            .unwrap_or_default();
9159        let lease_owner = task
9160            .lease_owner
9161            .clone()
9162            .unwrap_or_else(|| self.worker_id.clone());
9163        let session = worker_session.clone();
9164        let ctx = ActivityContext {
9165            client: self.client.clone(),
9166            task_id: task.task_id,
9167            activity_attempt_id: attempt_id,
9168            lease_owner,
9169            activity_type: task.activity_type,
9170            attempt_number: task.attempt_number,
9171            task_queue: self.task_queue.clone(),
9172            worker_id: self.worker_id.clone(),
9173            claim_guard: None,
9174            local_heartbeats: None,
9175            worker_session,
9176        };
9177
9178        if let Some(claim) = hydration_claim {
9179            claim.confirm(&self.client).await?;
9180        }
9181        let callback = handler(ctx, args);
9182        if let Some(session) = session {
9183            tokio::select! {
9184                biased;
9185                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
9186                result = callback => if session.active() { result } else {
9187                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
9188                },
9189            }
9190        } else {
9191            callback.await
9192        }
9193    }
9194}
9195
9196fn poller_result(
9197    kind: &str,
9198    result: std::result::Result<Result<()>, tokio::task::JoinError>,
9199) -> Result<()> {
9200    match result {
9201        Ok(result) => result,
9202        Err(error) => Err(Error::WorkerLoop(format!(
9203            "{kind} poller join error: {error}"
9204        ))),
9205    }
9206}
9207
9208fn optional_poller_result(
9209    kind: &str,
9210    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
9211) -> Result<()> {
9212    match result {
9213        Some(result) => poller_result(kind, result),
9214        None => Ok(()),
9215    }
9216}
9217
9218async fn join_pollers(
9219    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9220    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9221    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9222) -> Result<()> {
9223    let mut first_error = None;
9224
9225    if let Some(handle) = workflow_poller {
9226        if let Err(error) = poller_result("workflow", handle.await) {
9227            first_error.get_or_insert(error);
9228        }
9229    }
9230
9231    if let Some(handle) = activity_poller {
9232        if let Err(error) = poller_result("activity", handle.await) {
9233            first_error.get_or_insert(error);
9234        }
9235    }
9236
9237    if let Some(handle) = query_poller {
9238        if let Err(error) = poller_result("query", handle.await) {
9239            first_error.get_or_insert(error);
9240        }
9241    }
9242
9243    if let Some(error) = first_error {
9244        Err(error)
9245    } else {
9246        Ok(())
9247    }
9248}
9249
9250fn default_worker_id() -> String {
9251    let millis = SystemTime::now()
9252        .duration_since(UNIX_EPOCH)
9253        .unwrap_or_default()
9254        .as_millis();
9255    format!("rust-worker-{}-{millis}", std::process::id())
9256}
9257
9258fn percent_encode_path_segment(segment: &str) -> String {
9259    const HEX: &[u8; 16] = b"0123456789ABCDEF";
9260    let mut encoded = String::with_capacity(segment.len());
9261
9262    for byte in segment.bytes() {
9263        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
9264            encoded.push(char::from(byte));
9265        } else {
9266            encoded.push('%');
9267            encoded.push(char::from(HEX[(byte >> 4) as usize]));
9268            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
9269        }
9270    }
9271
9272    encoded
9273}
9274
9275fn unique_request_id(prefix: &str) -> String {
9276    let nanos = SystemTime::now()
9277        .duration_since(UNIX_EPOCH)
9278        .unwrap_or_default()
9279        .as_nanos();
9280    format!("{prefix}-{}-{nanos}", std::process::id())
9281}
9282
9283#[derive(Debug)]
9284struct QueryTaskExecutionFailure {
9285    reason: String,
9286    message: String,
9287    failure_type: String,
9288}
9289
9290impl QueryTaskExecutionFailure {
9291    fn new(
9292        reason: impl Into<String>,
9293        message: impl Into<String>,
9294        failure_type: impl Into<String>,
9295    ) -> Self {
9296        Self {
9297            reason: reason.into(),
9298            message: message.into(),
9299            failure_type: failure_type.into(),
9300        }
9301    }
9302}
9303
9304/// Typed local state owned by one deterministic workflow invocation.
9305///
9306/// Use [`WorkflowInstance::update`] for the same state transitions during
9307/// ordinary execution and replay. A replayed query receives a detached
9308/// immutable `Arc<S>` rather than this mutation-capable handle.
9309#[derive(Clone, Debug)]
9310pub struct WorkflowInstance<S> {
9311    state: Arc<Mutex<S>>,
9312}
9313
9314impl<S> WorkflowInstance<S> {
9315    fn new(state: S) -> Self {
9316        Self {
9317            state: Arc::new(Mutex::new(state)),
9318        }
9319    }
9320
9321    /// Read the current workflow-instance state without changing it.
9322    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
9323        let state = self
9324            .state
9325            .lock()
9326            .map_err(|_| Error::WorkflowStatePoisoned)?;
9327        Ok(reader(&state))
9328    }
9329
9330    /// Apply one deterministic workflow-instance state transition.
9331    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
9332        let mut state = self
9333            .state
9334            .lock()
9335            .map_err(|_| Error::WorkflowStatePoisoned)?;
9336        Ok(transition(&mut state))
9337    }
9338}
9339
9340impl<S: Clone> WorkflowInstance<S> {
9341    fn snapshot(&self) -> Result<S> {
9342        self.read(Clone::clone)
9343    }
9344}
9345
9346#[derive(Clone, Debug, PartialEq)]
9347pub struct MessageStreamMessage {
9348    pub stream_name: String,
9349    pub message_id: String,
9350    pub position: u64,
9351    pub arguments: Vec<AvroValue>,
9352}
9353
9354#[derive(Clone, Debug)]
9355pub struct MessageStream {
9356    ctx: WorkflowContext,
9357    name: String,
9358}
9359
9360impl MessageStream {
9361    /// Wait for one message, then return a bounded currently-available batch.
9362    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
9363        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
9364            return Err(Error::Codec(format!(
9365                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
9366            )));
9367        }
9368        loop {
9369            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
9370                return Ok(batch);
9371            }
9372
9373            self.ctx.record_message_stream_wait(&self.name)?;
9374            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
9375            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
9376            self.ctx.buffer_message_stream_delivery(arguments)?;
9377            if let Some(sequence) = replay_wait_sequence {
9378                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
9379            }
9380        }
9381    }
9382
9383    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
9384        self.receive(1)
9385            .await?
9386            .into_iter()
9387            .next()
9388            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
9389    }
9390}
9391
9392#[derive(Clone, Debug)]
9393pub struct WorkflowContext {
9394    state: Arc<Mutex<WorkflowState>>,
9395    cancellation_scope_id: String,
9396}
9397
9398fn valid_memo_key(key: &str) -> bool {
9399    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
9400
9401    !key.is_empty()
9402        && key.len() <= 64
9403        && (numeric_candidate.is_empty()
9404            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
9405        && key
9406            .bytes()
9407            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
9408}
9409
9410fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
9411    BASE64
9412        .decode(encode_avro_value(value)?.blob)
9413        .map(|bytes| bytes.len())
9414        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
9415}
9416
9417fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
9418    let AvroValue::Map(entries) = value else {
9419        return Err(Error::InvalidMemoUpdate(
9420            "entries must serialize to an Avro string-keyed map".to_string(),
9421        ));
9422    };
9423    if require_entries && entries.is_empty() {
9424        return Err(Error::InvalidMemoUpdate(
9425            "at least one entry is required".to_string(),
9426        ));
9427    }
9428    if entries.len() > MAX_MEMO_ENTRIES {
9429        return Err(Error::InvalidMemoUpdate(format!(
9430            "at most {MAX_MEMO_ENTRIES} entries are allowed"
9431        )));
9432    }
9433
9434    for (key, value) in &entries {
9435        if !valid_memo_key(&key) {
9436            return Err(Error::InvalidMemoUpdate(
9437                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
9438            ));
9439        }
9440        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
9441            return Err(Error::InvalidMemoUpdate(format!(
9442                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
9443            )));
9444        }
9445    }
9446
9447    let value = AvroValue::Map(entries);
9448    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
9449        return Err(Error::InvalidMemoUpdate(format!(
9450            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
9451        )));
9452    }
9453    Ok(value)
9454}
9455
9456fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
9457    let object = envelope.as_object().ok_or_else(|| {
9458        Error::InvalidMemoUpdate(
9459            "history field must use the public {codec, blob} payload envelope".to_string(),
9460        )
9461    })?;
9462    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
9463        return Err(Error::InvalidMemoUpdate(
9464            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
9465        ));
9466    }
9467
9468    canonical_memo_entries(
9469        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
9470        require_entries,
9471    )
9472}
9473
9474impl WorkflowContext {
9475    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
9476        let name = name.into();
9477        if name.is_empty()
9478            || name.len() > 128
9479            || !name.bytes().all(|byte| {
9480                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
9481            })
9482        {
9483            return Err(Error::Codec(
9484                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
9485                    .to_string(),
9486            ));
9487        }
9488        Ok(MessageStream {
9489            ctx: self.clone(),
9490            name,
9491        })
9492    }
9493
9494    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
9495        let mut state = self
9496            .state
9497            .lock()
9498            .map_err(|_| Error::WorkflowStatePoisoned)?;
9499        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9500        state
9501            .message_stream_waits
9502            .insert(name.to_string(), position);
9503        Ok(())
9504    }
9505
9506    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
9507        let mut state = self
9508            .state
9509            .lock()
9510            .map_err(|_| Error::WorkflowStatePoisoned)?;
9511        let cursor = state
9512            .message_stream_cursors
9513            .get(&message.stream_name)
9514            .copied()
9515            .unwrap_or(0);
9516        if message.position <= cursor {
9517            return Ok(());
9518        }
9519        let pending = state
9520            .message_stream_messages
9521            .entry(message.stream_name.clone())
9522            .or_default();
9523        if pending.iter().any(|candidate| {
9524            candidate.position == message.position || candidate.message_id == message.message_id
9525        }) {
9526            return Ok(());
9527        }
9528        pending.push(message);
9529        pending.sort_by_key(|candidate| candidate.position);
9530        Ok(())
9531    }
9532
9533    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
9534        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
9535            match delivery {
9536                MessageStreamDelivery::Message(message) => {
9537                    let stream_name = message.stream_name.clone();
9538                    self.buffer_message_stream(message)?;
9539                    return Ok(Some(stream_name));
9540                }
9541                MessageStreamDelivery::Cursor {
9542                    stream_name,
9543                    through_position,
9544                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
9545            }
9546        }
9547        Ok(None)
9548    }
9549
9550    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
9551        let state = self
9552            .state
9553            .lock()
9554            .map_err(|_| Error::WorkflowStatePoisoned)?;
9555        Ok(match state.recorded_commands.get(state.command_cursor) {
9556            Some(RecordedCommand::SignalWait {
9557                sequence,
9558                signal_name,
9559                ..
9560            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
9561            _ => None,
9562        })
9563    }
9564
9565    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
9566        let (history, payload_codec) = {
9567            let state = self
9568                .state
9569                .lock()
9570                .map_err(|_| Error::WorkflowStatePoisoned)?;
9571            (
9572                Arc::clone(&state.history_events),
9573                state.payload_codec.clone(),
9574            )
9575        };
9576
9577        let Some(opened_index) = history.iter().position(|event| {
9578            event.event_type == "SignalWaitOpened"
9579                && durable_event_sequence(event) == Some(wait_sequence)
9580                && event.payload.get("signal_name").and_then(Value::as_str)
9581                    == Some(MESSAGE_STREAM_SIGNAL)
9582        }) else {
9583            return Ok(());
9584        };
9585        let boundary_index = history
9586            .iter()
9587            .enumerate()
9588            .skip(opened_index + 1)
9589            .find_map(|(index, event)| {
9590                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
9591                    && is_authored_command_open_event(event))
9592                .then_some(index)
9593            })
9594            .unwrap_or(history.len());
9595
9596        for event in history[opened_index + 1..boundary_index]
9597            .iter()
9598            .filter(|event| {
9599                event.event_type == "SignalReceived"
9600                    && event.payload.get("signal_name").and_then(Value::as_str)
9601                        == Some(MESSAGE_STREAM_SIGNAL)
9602            })
9603        {
9604            let arguments = decode_signal_event_arguments(event, &payload_codec)?
9605                .into_iter()
9606                .map(AvroValue::into_json)
9607                .collect::<Result<Vec<_>>>()?;
9608            self.buffer_message_stream_delivery(arguments)?;
9609        }
9610        Ok(())
9611    }
9612
9613    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9614        let mut state = self
9615            .state
9616            .lock()
9617            .map_err(|_| Error::WorkflowStatePoisoned)?;
9618        let cursor = state
9619            .message_stream_cursors
9620            .entry(name.to_string())
9621            .or_default();
9622        *cursor = (*cursor).max(through_position);
9623        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9624            pending.retain(|message| message.position > through_position);
9625        }
9626        Ok(())
9627    }
9628
9629    fn take_message_stream_batch(
9630        &self,
9631        name: &str,
9632        max_items: usize,
9633    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9634        let mut state = self
9635            .state
9636            .lock()
9637            .map_err(|_| Error::WorkflowStatePoisoned)?;
9638        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9639        let pending = state
9640            .message_stream_messages
9641            .entry(name.to_string())
9642            .or_default();
9643        let count = contiguous_message_stream_count(pending, cursor, max_items);
9644        if count == 0 {
9645            return Ok(None);
9646        }
9647        let batch = pending.drain(..count).collect::<Vec<_>>();
9648        let position = batch.last().map(|message| message.position).unwrap_or(0);
9649        state
9650            .message_stream_cursors
9651            .insert(name.to_string(), position);
9652        state.message_stream_waits.remove(name);
9653        Ok(Some(batch))
9654    }
9655
9656    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9657        let state = self
9658            .state
9659            .lock()
9660            .map_err(|_| Error::WorkflowStatePoisoned)?;
9661        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9662        cursors.sort_by_key(|(name, _)| *name);
9663        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9664        waits.sort_by_key(|(name, _)| *name);
9665        Ok((
9666            cursors
9667                .into_iter()
9668                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9669                .collect(),
9670            waits
9671                .into_iter()
9672                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9673                .collect(),
9674        ))
9675    }
9676    /// Identity of the parent workflow currently being replayed.
9677    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9678        let state = self
9679            .state
9680            .lock()
9681            .map_err(|_| Error::WorkflowStatePoisoned)?;
9682        Ok(WorkflowIdentity {
9683            workflow_id: state.workflow_id.clone(),
9684            run_id: state.run_id.clone(),
9685        })
9686    }
9687
9688    /// Return the server-published history budget for this workflow task.
9689    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9690        let state = self
9691            .state
9692            .lock()
9693            .map_err(|_| Error::WorkflowStatePoisoned)?;
9694        Ok(state.history_budget.clone())
9695    }
9696
9697    /// Continue this workflow instance as a fresh run with replacement arguments.
9698    ///
9699    /// Return this value directly from the workflow handler. The worker converts
9700    /// it to the terminal protocol command only after replay has consumed every
9701    /// recorded durable command.
9702    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9703        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9704    }
9705
9706    /// Continue as new with optional workflow-type and task-queue overrides.
9707    pub fn continue_as_new_with_options<T: Serialize>(
9708        &self,
9709        options: ContinueAsNewOptions,
9710        args: T,
9711    ) -> Result<Value> {
9712        options.validate()?;
9713        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9714            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9715            options,
9716        }))
9717    }
9718
9719    pub fn activity<T: Serialize>(
9720        &self,
9721        activity_type: impl Into<String>,
9722        args: T,
9723    ) -> ActivityCall {
9724        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9725    }
9726
9727    pub fn activity_on_queue<T, Q>(
9728        &self,
9729        activity_type: impl Into<String>,
9730        task_queue: Option<Q>,
9731        args: T,
9732    ) -> ActivityCall
9733    where
9734        T: Serialize,
9735        Q: Into<String>,
9736    {
9737        let mut options = ActivityOptions::new();
9738        options.task_queue = task_queue.map(Into::into);
9739        self.activity_with_options(activity_type, options, args)
9740    }
9741
9742    /// Schedule one durable activity with retry, routing, and timeout options.
9743    ///
9744    /// Options are validated before the command is emitted. Once the command is
9745    /// recorded, replay consumes the same activity lifecycle at this command
9746    /// position and never emits a duplicate schedule.
9747    ///
9748    /// ```no_run
9749    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9750    /// # use std::time::Duration;
9751    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9752    /// let result = ctx
9753    ///     .activity_with_options(
9754    ///         "charge-card",
9755    ///         ActivityOptions::new()
9756    ///             .task_queue("payments")
9757    ///             .retry_policy(
9758    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9759    ///                     Duration::from_secs(1),
9760    ///                     2,
9761    ///                     Some(Duration::from_secs(30)),
9762    ///                 ),
9763    ///             )
9764    ///             .start_to_close_timeout(Duration::from_secs(60))
9765    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9766    ///             .heartbeat_timeout(Duration::from_secs(15)),
9767    ///         json!([{"order_id": "order-42"}]),
9768    ///     )
9769    ///     .await;
9770    /// match result {
9771    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9772    ///         "reason": failure.reason,
9773    ///         "timeout_kind": failure.timeout_kind,
9774    ///     })),
9775    ///     other => other,
9776    /// }
9777    /// # }
9778    /// ```
9779    pub fn activity_with_options<T: Serialize>(
9780        &self,
9781        activity_type: impl Into<String>,
9782        options: ActivityOptions,
9783        args: T,
9784    ) -> ActivityCall {
9785        ActivityCall {
9786            ctx: self.clone(),
9787            activity_type: activity_type.into(),
9788            options,
9789            worker_session: None,
9790            args: Some(AvroValue::from_serialize(&args)),
9791            scheduled: false,
9792            local: false,
9793            local_result: None,
9794            parallel_group_path: Vec::new(),
9795        }
9796    }
9797
9798    pub async fn activity_avro_value<T: Serialize>(
9799        &self,
9800        activity_type: impl Into<String>,
9801        args: T,
9802    ) -> Result<AvroValue> {
9803        let mut call = self.activity(activity_type, args);
9804        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9805    }
9806
9807    pub async fn activity_avro_value_with_options<T: Serialize>(
9808        &self,
9809        activity_type: impl Into<String>,
9810        options: ActivityOptions,
9811        args: T,
9812    ) -> Result<AvroValue> {
9813        let mut call = self.activity_with_options(activity_type, options, args);
9814        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9815    }
9816
9817    /// Schedule an activity with a Serde request and decode its Serde result.
9818    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
9819    where
9820        I: Serialize,
9821        O: DeserializeOwned,
9822    {
9823        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
9824            .await
9825    }
9826
9827    /// Schedule an activity with options and decode its result into `O`.
9828    ///
9829    /// Both directions use the fixed Avro Value codec. In particular, this
9830    /// method does not deserialize the JSON-safe inspection projection returned
9831    /// by the dynamic [`ActivityCall`] future.
9832    pub async fn activity_typed_with_options<I, O>(
9833        &self,
9834        activity_type: impl Into<String>,
9835        options: ActivityOptions,
9836        args: I,
9837    ) -> Result<O>
9838    where
9839        I: Serialize,
9840        O: DeserializeOwned,
9841    {
9842        let activity_type = activity_type.into();
9843        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
9844            handler_type_error::<I>(
9845                HandlerKind::Activity,
9846                &activity_type,
9847                HandlerValueKind::Input,
9848                error.to_string(),
9849            )
9850        });
9851        let mut call = ActivityCall {
9852            ctx: self.clone(),
9853            activity_type: activity_type.clone(),
9854            options,
9855            worker_session: None,
9856            args: Some(encoded),
9857            scheduled: false,
9858            local: false,
9859            local_result: None,
9860            parallel_group_path: Vec::new(),
9861        };
9862        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
9863        decode_handler_result(result, HandlerKind::Activity, &activity_type)
9864    }
9865
9866    /// Schedule and join a deterministic activity/child/timer group.
9867    ///
9868    /// Nested groups retain their input shape. Every durable leaf is scheduled
9869    /// before this future yields, results are assembled by declaration order,
9870    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
9871    /// declaration path, stable group metadata, and completed siblings.
9872    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9873        ParallelCall::new(self.clone(), operations)
9874    }
9875
9876    /// Alias for [`WorkflowContext::parallel`].
9877    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9878        self.parallel(operations)
9879    }
9880
9881    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
9882    pub async fn parallel_avro_value(
9883        &self,
9884        operations: Vec<ParallelOperation>,
9885    ) -> Result<Vec<ParallelAvroResult>> {
9886        let mut call = self.parallel(operations);
9887        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9888    }
9889
9890    /// Start every durable operation and resume from the one winner persisted
9891    /// by Server. Non-winning operations continue and remain addressable.
9892    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
9893        let operations = operations
9894            .into_iter()
9895            .enumerate()
9896            .map(|(index, operation)| (SelectionKey::Index(index), operation))
9897            .collect();
9898        SelectCall::new(self.clone(), operations)
9899    }
9900
9901    /// Named-key variant of [`WorkflowContext::select`].
9902    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
9903    where
9904        K: Into<SelectionKey>,
9905    {
9906        SelectCall::new(
9907            self.clone(),
9908            operations
9909                .into_iter()
9910                .map(|(key, operation)| (key.into(), operation))
9911                .collect(),
9912        )
9913    }
9914
9915    /// Create a workflow-local deterministic compensation registry.
9916    pub fn saga(&self) -> Saga {
9917        Saga::new(self.clone())
9918    }
9919
9920    /// Whether cancellation has reached this replay's authored boundary.
9921    ///
9922    /// Server's current `/cancel` route is terminal and does not set this flag.
9923    /// A canonical service request remains pending until its committed delivery
9924    /// is consumed. Request observation alone does not authorize an exception.
9925    pub fn is_cancellation_requested(&self) -> Result<bool> {
9926        let state = self
9927            .state
9928            .lock()
9929            .map_err(|_| Error::WorkflowStatePoisoned)?;
9930        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9931            return Ok(state
9932                .scope_delivery
9933                .as_ref()
9934                .unwrap()
9935                .contexts
9936                .contains_key(&self.cancellation_scope_id));
9937        }
9938        Ok(state.cancel_requested
9939            || state
9940                .scope_delivery
9941                .as_ref()
9942                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
9943    }
9944
9945    /// Raise a typed cooperative cancellation at an author-controlled point.
9946    ///
9947    /// Passing this result to [`Saga::finish`] compensates already registered
9948    /// forward steps before the cancellation remains the initiating outcome.
9949    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
9950        let mut state = self
9951            .state
9952            .lock()
9953            .map_err(|_| Error::WorkflowStatePoisoned)?;
9954        if state.cancellation_shield_depth == 0 {
9955            if let Some(replay) = &state.scope_delivery {
9956                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
9957                    let delivered = replay
9958                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
9959                        .ok_or_else(|| {
9960                            Error::InvalidCooperativeCancellation(
9961                                "scoped request lacks its consumed original delivery".into(),
9962                            )
9963                        })?;
9964                    return Err(Error::CancellationScopeRequested(
9965                        CancellationScopeRequested {
9966                            context: context
9967                                .clone()
9968                                .with_replay(Some(Arc::downgrade(&self.state))),
9969                            delivery: delivered.boundary.clone(),
9970                        },
9971                    ));
9972                }
9973            }
9974        }
9975        if state.cancel_requested && state.cancellation_shield_depth == 0 {
9976            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9977                return Ok(());
9978            }
9979            return Err(state.cancellation_error());
9980        }
9981        Ok(())
9982    }
9983
9984    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9985        SignalCall {
9986            ctx: self.clone(),
9987            signal_name: signal_name.into(),
9988            runtime_reserved_allowed: false,
9989            opened_wait: false,
9990            matched_pending: false,
9991            parallel_group_path: Vec::new(),
9992        }
9993    }
9994
9995    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9996        SignalCall {
9997            ctx: self.clone(),
9998            signal_name: signal_name.into(),
9999            runtime_reserved_allowed: true,
10000            opened_wait: false,
10001            matched_pending: false,
10002            parallel_group_path: Vec::new(),
10003        }
10004    }
10005
10006    pub async fn wait_signal_avro_value(
10007        &self,
10008        signal_name: impl Into<String>,
10009    ) -> Result<Vec<AvroValue>> {
10010        let mut call = self.wait_signal(signal_name);
10011        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10012    }
10013
10014    /// Return every committed signal argument list with the given name.
10015    ///
10016    /// This history-backed view is deterministic and is intended for
10017    /// condition predicates that must be re-evaluated after a signal while the
10018    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10019    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10020        self.signals_avro_value(signal_name)?
10021            .into_iter()
10022            .map(|arguments| {
10023                arguments
10024                    .into_iter()
10025                    .map(AvroValue::into_json)
10026                    .collect::<Result<Vec<_>>>()
10027            })
10028            .collect()
10029    }
10030
10031    /// Lossless fixed Avro Value view of committed signals with the given name.
10032    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10033        let state = self
10034            .state
10035            .lock()
10036            .map_err(|_| Error::WorkflowStatePoisoned)?;
10037        state
10038            .history_events
10039            .iter()
10040            .filter(|event| {
10041                event.event_type == "SignalReceived"
10042                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10043            })
10044            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10045            .collect()
10046    }
10047
10048    /// Return every committed update argument list with the given name.
10049    ///
10050    /// Accepted and applied records for the same update ID are de-duplicated.
10051    /// A Server task created after an update therefore replays the workflow and
10052    /// re-evaluates an open condition without application polling.
10053    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10054        self.updates_avro_value(update_name)?
10055            .into_iter()
10056            .map(|arguments| {
10057                arguments
10058                    .into_iter()
10059                    .map(AvroValue::into_json)
10060                    .collect::<Result<Vec<_>>>()
10061            })
10062            .collect()
10063    }
10064
10065    /// Lossless fixed Avro Value view of committed updates with the given name.
10066    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10067        let state = self
10068            .state
10069            .lock()
10070            .map_err(|_| Error::WorkflowStatePoisoned)?;
10071        let mut seen = Vec::new();
10072        let mut updates = Vec::new();
10073        for event in state.history_events.iter() {
10074            if !matches!(
10075                event.event_type.as_str(),
10076                "UpdateAccepted" | "UpdateApplied"
10077            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
10078                || event.payload.get("arguments").is_none()
10079            {
10080                continue;
10081            }
10082            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
10083                if seen.iter().any(|recorded| recorded == update_id) {
10084                    continue;
10085                }
10086                seen.push(update_id.to_string());
10087            }
10088            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
10089        }
10090        Ok(updates)
10091    }
10092
10093    /// Wait for a deterministic predicate to become true or for its durable
10094    /// timeout to elapse.
10095    ///
10096    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
10097    /// predicate tokens automatically change the recorded definition
10098    /// fingerprint. Direct callers must provide an equally stable identity in
10099    /// [`ConditionWaitOptions`].
10100    pub fn wait_condition<F>(
10101        &self,
10102        options: ConditionWaitOptions,
10103        predicate: F,
10104    ) -> ConditionWaitCall
10105    where
10106        F: Fn() -> Result<bool> + Send + 'static,
10107    {
10108        ConditionWaitCall {
10109            ctx: self.clone(),
10110            options,
10111            predicate: Box::new(predicate),
10112            occurrence_id: None,
10113            opened_wait: false,
10114            parallel_group_path: Vec::new(),
10115        }
10116    }
10117
10118    /// Wait for server-backed durable time without blocking the worker executor.
10119    ///
10120    /// Polling this future emits one `start_timer` command and yields. The
10121    /// server records the deadline, so neither worker nor server restarts reset
10122    /// the wait. Replay resolves the future only from a `TimerScheduled` and
10123    /// `TimerFired` pair at the same position in the shared durable-command
10124    /// stream, with matching sequence, timer identity, and delay. Sub-second
10125    /// durations round up because protocol deadlines use whole seconds.
10126    ///
10127    /// ```no_run
10128    /// # use durable_workflow::{json, Client, Worker};
10129    /// # use std::time::Duration;
10130    /// # fn configure(client: Client) {
10131    /// let mut worker = Worker::new(client, "rust-workers");
10132    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
10133    ///     ctx.sleep(Duration::from_secs(5)).await?;
10134    ///     Ok(json!({"status": "timer fired"}))
10135    /// });
10136    /// # }
10137    /// ```
10138    pub fn sleep(&self, duration: Duration) -> TimerCall {
10139        let delay_seconds = duration
10140            .as_secs()
10141            .checked_add(u64::from(duration.subsec_nanos() > 0));
10142        TimerCall {
10143            ctx: self.clone(),
10144            delay_seconds,
10145            scheduled: false,
10146            matched_pending: false,
10147            parallel_group_path: Vec::new(),
10148        }
10149    }
10150
10151    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
10152    pub fn start_timer(&self, duration: Duration) -> TimerCall {
10153        self.sleep(duration)
10154    }
10155
10156    /// Evaluate a non-deterministic callback once and durably record its typed value.
10157    ///
10158    /// On replay the callback is not invoked: the value is decoded from the
10159    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
10160    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
10161    /// small values that must remain fixed for the lifetime of a workflow run.
10162    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
10163    where
10164        T: Serialize + DeserializeOwned,
10165        F: FnOnce() -> T,
10166    {
10167        {
10168            let mut state = self
10169                .state
10170                .lock()
10171                .map_err(|_| Error::WorkflowStatePoisoned)?;
10172            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10173                return match recorded {
10174                    RecordedCommand::SideEffect { sequence, value } => {
10175                        state.command_cursor += 1;
10176                        value.deserialize().map_err(|error| {
10177                            Error::NonDeterministicReplay(ReplayFailure::new(
10178                                "side_effect_type_mismatch",
10179                                Some(sequence),
10180                                Some(std::any::type_name::<T>().to_string()),
10181                                Some(error.to_string()),
10182                                "recorded side-effect value is incompatible with the requested Rust type",
10183                            ))
10184                        })
10185                    }
10186                    other => Err(command_mismatch(&other, "side effect")),
10187                };
10188            }
10189        }
10190
10191        let value = callback();
10192        let avro_value = AvroValue::from_serialize(&value)?;
10193        let mut state = self
10194            .state
10195            .lock()
10196            .map_err(|_| Error::WorkflowStatePoisoned)?;
10197        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
10198        state.commands.push(json!({
10199            "type": "record_side_effect",
10200            "result": result,
10201        }));
10202        Ok(value)
10203    }
10204
10205    /// Record or replay a lossless fixed Avro Value side effect.
10206    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
10207    where
10208        F: FnOnce() -> AvroValue,
10209    {
10210        {
10211            let mut state = self
10212                .state
10213                .lock()
10214                .map_err(|_| Error::WorkflowStatePoisoned)?;
10215            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10216                return match recorded {
10217                    RecordedCommand::SideEffect { value, .. } => {
10218                        state.command_cursor += 1;
10219                        Ok(value)
10220                    }
10221                    other => Err(command_mismatch(&other, "side effect")),
10222                };
10223            }
10224        }
10225
10226        let value = callback();
10227        let mut state = self
10228            .state
10229            .lock()
10230            .map_err(|_| Error::WorkflowStatePoisoned)?;
10231        let result = encode_typed_envelope(&value, &state.payload_codec)?;
10232        state.commands.push(json!({
10233            "type": "record_side_effect",
10234            "result": result,
10235        }));
10236        Ok(value)
10237    }
10238
10239    /// Append output items at a deterministic workflow command boundary.
10240    ///
10241    /// Stable idempotency keys are derived from the server-provided durable
10242    /// workflow command identity, command ordinal, and item index. Replay
10243    /// consumes the recorded side effect and never emits another append.
10244    pub fn append_workflow_stream(
10245        &self,
10246        stream_name: impl Into<String>,
10247        items: &[WorkflowStreamAppendItem],
10248        max_pending_items: Option<u64>,
10249    ) -> Result<()> {
10250        if items.is_empty() {
10251            return Err(Error::Codec(
10252                "workflow_stream_items_empty: append requires at least one item".to_string(),
10253            ));
10254        }
10255        if max_pending_items == Some(0) {
10256            return Err(Error::Codec(
10257                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
10258                    .to_string(),
10259            ));
10260        }
10261        let stream_name = stream_name.into();
10262        if stream_name.is_empty() {
10263            return Err(Error::Codec(
10264                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10265            ));
10266        }
10267
10268        let mut state = self
10269            .state
10270            .lock()
10271            .map_err(|_| Error::WorkflowStatePoisoned)?;
10272        let command_ordinal = state.workflow_stream_command_counter;
10273        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10274            state.workflow_stream_command_counter += 1;
10275            return match recorded {
10276                RecordedCommand::SideEffect { .. } => {
10277                    state.command_cursor += 1;
10278                    Ok(())
10279                }
10280                other => Err(command_mismatch(&other, "workflow stream append")),
10281            };
10282        }
10283
10284        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10285        state.workflow_stream_command_counter += 1;
10286        let wire_items = items
10287            .iter()
10288            .enumerate()
10289            .map(|(item_index, item)| {
10290                item.wire_value(Some(format!(
10291                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
10292                )))
10293            })
10294            .collect::<Vec<_>>();
10295        let mut directive = json!({
10296            "operation": "append",
10297            "stream_name": stream_name,
10298            "command_identity": identity,
10299            "command_ordinal": command_ordinal,
10300            "items": wire_items,
10301        });
10302        if let Some(max_pending_items) = max_pending_items {
10303            directive["max_pending_items"] = json!(max_pending_items);
10304        }
10305        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10306        state.commands.push(json!({
10307            "type": "record_side_effect",
10308            "result": result,
10309            "workflow_stream": directive,
10310        }));
10311        Ok(())
10312    }
10313
10314    /// Close a run-scoped output stream at a deterministic command boundary.
10315    pub fn close_workflow_stream(
10316        &self,
10317        stream_name: impl Into<String>,
10318        retention_seconds: Option<u64>,
10319    ) -> Result<()> {
10320        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
10321    }
10322
10323    /// Mark a run-scoped output stream errored at a deterministic command boundary.
10324    pub fn error_workflow_stream(
10325        &self,
10326        stream_name: impl Into<String>,
10327        error_reason: impl Into<String>,
10328        retention_seconds: Option<u64>,
10329    ) -> Result<()> {
10330        let error_reason = error_reason.into();
10331        if error_reason.is_empty() {
10332            return Err(Error::Codec(
10333                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
10334            ));
10335        }
10336        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
10337    }
10338
10339    fn finish_workflow_stream(
10340        &self,
10341        stream_name: String,
10342        error_reason: Option<String>,
10343        retention_seconds: Option<u64>,
10344    ) -> Result<()> {
10345        if stream_name.is_empty() {
10346            return Err(Error::Codec(
10347                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10348            ));
10349        }
10350        if retention_seconds == Some(0) {
10351            return Err(Error::Codec(
10352                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
10353            ));
10354        }
10355        let mut state = self
10356            .state
10357            .lock()
10358            .map_err(|_| Error::WorkflowStatePoisoned)?;
10359        let command_ordinal = state.workflow_stream_command_counter;
10360        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10361            state.workflow_stream_command_counter += 1;
10362            return match recorded {
10363                RecordedCommand::SideEffect { .. } => {
10364                    state.command_cursor += 1;
10365                    Ok(())
10366                }
10367                other => Err(command_mismatch(&other, "workflow stream close")),
10368            };
10369        }
10370        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10371        state.workflow_stream_command_counter += 1;
10372        let mut directive = json!({
10373            "operation": if error_reason.is_some() { "error" } else { "close" },
10374            "stream_name": stream_name,
10375            "command_identity": identity,
10376            "command_ordinal": command_ordinal,
10377        });
10378        if let Some(error_reason) = error_reason {
10379            directive["error_reason"] = json!(error_reason);
10380        }
10381        if let Some(retention_seconds) = retention_seconds {
10382            directive["retention_seconds"] = json!(retention_seconds);
10383        }
10384        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10385        state.commands.push(json!({
10386            "type": "record_side_effect",
10387            "result": result,
10388            "workflow_stream": directive,
10389        }));
10390        Ok(())
10391    }
10392
10393    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
10394        let identity = state.workflow_command_identity.as_str();
10395        if identity.is_empty() {
10396            return Err(Error::MissingWorkflowCommandIdentity);
10397        }
10398        Ok(identity)
10399    }
10400
10401    /// Validate, emit, or replay a typed workflow search-attribute update.
10402    ///
10403    /// The command is non-blocking within a workflow decision, but its
10404    /// `SearchAttributesUpserted` event occupies the same deterministic command
10405    /// stream as activities, timers, conditions, and other durable operations.
10406    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
10407        update.validate()?;
10408        let (attributes, attribute_types) = update.into_wire_parts();
10409        let mut state = self
10410            .state
10411            .lock()
10412            .map_err(|_| Error::WorkflowStatePoisoned)?;
10413
10414        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10415            return match recorded {
10416                RecordedCommand::SearchAttributes {
10417                    sequence,
10418                    attributes: recorded_attributes,
10419                    attribute_types: recorded_attribute_types,
10420                } => {
10421                    if recorded_attributes != attributes {
10422                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10423                            "search_attribute_value_mismatch",
10424                            Some(sequence),
10425                            Some(recorded_attributes.to_string()),
10426                            Some(attributes.to_string()),
10427                            "search-attribute values differ from the recorded durable command",
10428                        )));
10429                    }
10430                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
10431                        if recorded_types != attribute_types {
10432                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10433                                "search_attribute_type_mismatch",
10434                                Some(sequence),
10435                                Some(json!(recorded_types).to_string()),
10436                                Some(json!(attribute_types).to_string()),
10437                                "search-attribute declared types differ from the recorded durable command",
10438                            )));
10439                        }
10440                    }
10441                    state.command_cursor += 1;
10442                    Ok(())
10443                }
10444                other => Err(command_mismatch(&other, "search-attribute update")),
10445            };
10446        }
10447
10448        let mut command = serde_json::Map::from_iter([
10449            ("type".to_string(), json!("upsert_search_attributes")),
10450            ("attributes".to_string(), attributes),
10451        ]);
10452        if !attribute_types.is_empty() {
10453            command.insert("attribute_types".to_string(), json!(attribute_types));
10454        }
10455        state.commands.push(Value::Object(command));
10456        Ok(())
10457    }
10458
10459    /// Record a UUIDv4 once and return the same UUID on every replay.
10460    pub fn uuid_v4(&self) -> Result<Uuid> {
10461        self.side_effect(Uuid::new_v4)
10462    }
10463
10464    /// Select the newest supported version for a change, or replay the version
10465    /// already committed for that stable change ID.
10466    ///
10467    /// An unmarked old history that reached its next durable operation, or
10468    /// already completed, selects `-1` when that version is supported. This
10469    /// leaves the original operation available and writes no additional marker.
10470    /// Consistent markers written by older workers retain their original ordered
10471    /// positions. Repeated calls consume a matching marker at the current cursor.
10472    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
10473    pub fn get_version(
10474        &self,
10475        change_id: impl Into<String>,
10476        min_supported: i32,
10477        max_supported: i32,
10478    ) -> Result<i32> {
10479        let change_id = change_id.into();
10480        if change_id.trim().is_empty() {
10481            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10482                "version_change_id_invalid",
10483                None,
10484                Some("non-empty change ID".to_string()),
10485                Some(change_id),
10486                "version markers require a stable non-empty change ID",
10487            )));
10488        }
10489        if min_supported > max_supported {
10490            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10491                "version_range_invalid",
10492                None,
10493                Some("min_supported <= max_supported".to_string()),
10494                Some(format!("{min_supported}..={max_supported}")),
10495                "version marker supported range is invalid",
10496            )));
10497        }
10498
10499        let mut state = self
10500            .state
10501            .lock()
10502            .map_err(|_| Error::WorkflowStatePoisoned)?;
10503        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
10504            if let Some(RecordedCommand::VersionMarker {
10505                sequence: alias_sequence,
10506                change_id: alias_change_id,
10507                version: alias_version,
10508            }) = state.recorded_commands.get(state.command_cursor)
10509            {
10510                if alias_change_id == &change_id {
10511                    if *alias_version != version {
10512                        return Err(invalid_recorded_history(
10513                            "version_marker_conflict",
10514                            *alias_sequence,
10515                            &format!("selected version {version} for change ID {change_id:?}"),
10516                            &format!("recorded version {alias_version}"),
10517                            "recorded marker conflicts with the decision already selected during replay",
10518                        ));
10519                    }
10520                    ensure_version_supported(
10521                        &change_id,
10522                        version,
10523                        min_supported,
10524                        max_supported,
10525                        *alias_sequence,
10526                    )?;
10527                    // Older workers could record the same decision again. Keep
10528                    // each physical boundary without skipping intervening work.
10529                    state.command_cursor += 1;
10530                    return Ok(version);
10531                }
10532            }
10533            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
10534            return Ok(version);
10535        }
10536
10537        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10538            return match recorded {
10539                RecordedCommand::VersionMarker {
10540                    sequence,
10541                    change_id: recorded_change_id,
10542                    version,
10543                    ..
10544                } => {
10545                    if recorded_change_id != change_id {
10546                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10547                            "version_change_id_mismatch",
10548                            Some(sequence),
10549                            Some(recorded_change_id),
10550                            Some(change_id),
10551                            "recorded version marker change ID differs from current workflow code",
10552                        )));
10553                    }
10554                    ensure_version_supported(
10555                        &change_id,
10556                        version,
10557                        min_supported,
10558                        max_supported,
10559                        sequence,
10560                    )?;
10561                    state.command_cursor += 1;
10562                    state.version_markers.insert(change_id, (version, sequence));
10563                    Ok(version)
10564                }
10565                other => {
10566                    let version = -1;
10567                    let sequence = other.sequence();
10568                    ensure_version_supported(
10569                        &change_id,
10570                        version,
10571                        min_supported,
10572                        max_supported,
10573                        sequence,
10574                    )?;
10575                    // The existing operation proves this patch site was reached
10576                    // before its marker existed. Keep its original cursor.
10577                    state.version_markers.insert(change_id, (version, sequence));
10578                    Ok(version)
10579                }
10580            };
10581        }
10582
10583        if state
10584            .history_events
10585            .iter()
10586            .any(|event| event.event_type == "WorkflowCompleted")
10587        {
10588            let version = -1;
10589            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
10590            state.version_markers.insert(change_id, (version, 0));
10591            return Ok(version);
10592        }
10593
10594        let version = max_supported;
10595        state.commands.push(json!({
10596            "type": "record_version_marker",
10597            "change_id": change_id,
10598            "version": version,
10599            "min_supported": min_supported,
10600            "max_supported": max_supported,
10601        }));
10602        // Sequence numbers are assigned by the server. Zero identifies a marker
10603        // selected in this uncommitted decision batch for duplicate-call checks.
10604        state.version_markers.insert(change_id, (version, 0));
10605        Ok(version)
10606    }
10607
10608    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
10609    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
10610        Ok(self.get_version(change_id, -1, 1)? == 1)
10611    }
10612
10613    /// Keep a patch marker in history after the legacy branch has been removed.
10614    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
10615        self.get_version(change_id, -1, 1).map(|_| ())
10616    }
10617
10618    /// Merge non-indexed workflow memo metadata through durable history.
10619    ///
10620    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
10621    /// public Avro payload envelope consumed by Server and Cloud runtimes.
10622    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
10623        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
10624        let mut state = self
10625            .state
10626            .lock()
10627            .map_err(|_| Error::WorkflowStatePoisoned)?;
10628
10629        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10630            return match recorded {
10631                RecordedCommand::Memo {
10632                    sequence,
10633                    entries: recorded_entries,
10634                } => {
10635                    if recorded_entries != entries {
10636                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10637                            "memo_update_mismatch",
10638                            Some(sequence),
10639                            Some(format!("{recorded_entries:?}")),
10640                            Some(format!("{entries:?}")),
10641                            "recorded memo entries differ from the current workflow update",
10642                        )));
10643                    }
10644                    state.command_cursor += 1;
10645                    Ok(())
10646                }
10647                other => Err(command_mismatch(&other, "memo upsert")),
10648            };
10649        }
10650
10651        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
10652        state.commands.push(json!({
10653            "type": "upsert_memo",
10654            "entries": entries_envelope,
10655        }));
10656        Ok(())
10657    }
10658
10659    /// Start a named durable child on an explicit queue and await its result.
10660    ///
10661    /// The command is recorded in the parent's sequence-ordered durable command
10662    /// stream. Replay keeps a scheduled child pending without emitting another
10663    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
10664    /// values preserve the history payload codec and include both sides of the
10665    /// durable relationship; failures are returned as
10666    /// [`Error::ChildWorkflowFailed`].
10667    ///
10668    /// ```no_run
10669    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10670    /// # fn configure(client: Client) {
10671    /// let mut worker = Worker::new(client, "parent-workers");
10672    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10673    ///     let child = ctx
10674    ///         .start_child_workflow(
10675    ///             "fulfil-order",
10676    ///             ChildWorkflowOptions::new("fulfilment-workers")
10677    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10678    ///             json!([{"order_id": "order-42"}]),
10679    ///         )
10680    ///         .await?;
10681    ///     Ok(child.result)
10682    /// });
10683    /// # }
10684    /// ```
10685    pub fn start_child_workflow<T: Serialize>(
10686        &self,
10687        workflow_type: impl Into<String>,
10688        options: ChildWorkflowOptions,
10689        args: T,
10690    ) -> ChildWorkflowCall {
10691        ChildWorkflowCall {
10692            ctx: self.clone(),
10693            workflow_type: workflow_type.into(),
10694            options,
10695            args: Some(AvroValue::from_serialize(&args)),
10696            scheduled: false,
10697            matched_pending: false,
10698            parallel_group_path: Vec::new(),
10699        }
10700    }
10701
10702    pub async fn start_child_workflow_avro_value<T: Serialize>(
10703        &self,
10704        workflow_type: impl Into<String>,
10705        options: ChildWorkflowOptions,
10706        args: T,
10707    ) -> Result<ChildWorkflowAvroResult> {
10708        let mut call = self.start_child_workflow(workflow_type, options, args);
10709        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10710    }
10711
10712    fn take_commands(&self) -> Result<Vec<Value>> {
10713        let mut state = self
10714            .state
10715            .lock()
10716            .map_err(|_| Error::WorkflowStatePoisoned)?;
10717        Ok(std::mem::take(&mut state.commands))
10718    }
10719
10720    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10721        let mut state = self
10722            .state
10723            .lock()
10724            .map_err(|_| Error::WorkflowStatePoisoned)?;
10725
10726        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10727            return Err(command_mismatch(&recorded, "continue as new"));
10728        }
10729        if state.recorded_continue_as_new_sequence.is_some() {
10730            state.continue_as_new_consumed = true;
10731            return Ok(None);
10732        }
10733
10734        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10735        let mut command = serde_json::Map::from_iter([
10736            ("type".to_string(), json!("continue_as_new")),
10737            ("arguments".to_string(), arguments),
10738            ("queue".to_string(), json!(state.task_queue.clone())),
10739        ]);
10740        if let Some(workflow_type) = request.options.workflow_type {
10741            command.insert("workflow_type".to_string(), json!(workflow_type));
10742        }
10743        if let Some(task_queue) = request.options.task_queue {
10744            command.insert("queue".to_string(), json!(task_queue));
10745        }
10746        Ok(Some(Value::Object(command)))
10747    }
10748
10749    fn matched_recorded_pending(&self) -> Result<bool> {
10750        let state = self
10751            .state
10752            .lock()
10753            .map_err(|_| Error::WorkflowStatePoisoned)?;
10754        Ok(state.matched_recorded_pending)
10755    }
10756
10757    fn ensure_history_consumed(&self) -> Result<()> {
10758        let state = self
10759            .state
10760            .lock()
10761            .map_err(|_| Error::WorkflowStatePoisoned)?;
10762        if let Some(replay) = &state.scope_delivery {
10763            if let Some((&sequence, _)) = replay
10764                .canonical
10765                .deliveries
10766                .iter()
10767                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10768            {
10769                return Err(invalid_recorded_history(
10770                    "cancellation_scope_delivery_unconsumed",
10771                    sequence,
10772                    "original scoped delivery",
10773                    "workflow completion",
10774                    "workflow completed without consuming its committed scope delivery",
10775                ));
10776            }
10777        }
10778        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10779            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10780                "recorded_commands_unconsumed",
10781                Some(command.sequence()),
10782                Some(command.shape().to_string()),
10783                Some("workflow completion".to_string()),
10784                "workflow completed before consuming all recorded durable commands",
10785            )));
10786        }
10787        if let Some(delivery) = state
10788            .cancellation_history
10789            .delivery
10790            .as_ref()
10791            .filter(|_| !state.cancellation_consumed)
10792        {
10793            return Err(invalid_recorded_history(
10794                "cooperative_cancellation_unconsumed",
10795                delivery.sequence,
10796                "committed cancellation call",
10797                "workflow completion",
10798                "workflow completed without reaching its committed cancellation boundary",
10799            ));
10800        }
10801        if let Some(sequence) = state
10802            .recorded_continue_as_new_sequence
10803            .filter(|_| !state.continue_as_new_consumed)
10804        {
10805            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10806                "recorded_continue_as_new_unconsumed",
10807                Some(sequence),
10808                Some("continue as new".to_string()),
10809                Some("workflow completion".to_string()),
10810                "workflow completed without consuming its recorded continue-as-new transition",
10811            )));
10812        }
10813        Ok(())
10814    }
10815}
10816
10817fn contiguous_message_stream_count(
10818    pending: &[MessageStreamMessage],
10819    cursor: u64,
10820    max_items: usize,
10821) -> usize {
10822    pending
10823        .iter()
10824        .take(max_items)
10825        .enumerate()
10826        .take_while(|(offset, message)| {
10827            u64::try_from(*offset)
10828                .ok()
10829                .and_then(|offset| cursor.checked_add(offset + 1))
10830                == Some(message.position)
10831        })
10832        .count()
10833}
10834
10835fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
10836    matches!(
10837        event.event_type.as_str(),
10838        "ActivityScheduled"
10839            | "TimerScheduled"
10840            | "ChildWorkflowScheduled"
10841            | "SignalWaitOpened"
10842            | "ConditionWaitOpened"
10843            | "SearchAttributesUpserted"
10844            | "SideEffectRecorded"
10845            | "VersionMarkerRecorded"
10846            | "MemoUpserted"
10847            | "WorkflowContinuedAsNew"
10848    )
10849}
10850
10851#[derive(Debug)]
10852struct WorkflowState {
10853    workflow_id: Option<String>,
10854    run_id: Option<String>,
10855    task_queue: String,
10856    payload_codec: String,
10857    history_events: Arc<Vec<HistoryEvent>>,
10858    history_budget: WorkflowHistoryBudget,
10859    cancel_requested: bool,
10860    cancellation_history: CancellationHistory,
10861    cancellation_consumed: bool,
10862    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
10863    cancellation_shield_depth: u64,
10864    cancellation_delivery_enabled: bool,
10865    cancellation_delivery_intent: Option<CancellationDelivery>,
10866    cancellation_delivery_command_count: usize,
10867    allow_cancellation_scope_authoring: bool,
10868    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
10869    cancellation_scope_memberships: BTreeMap<u64, String>,
10870    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
10871    resume_signal: Option<ResumeSignal>,
10872    recorded_commands: Vec<RecordedCommand>,
10873    selection_markers: Vec<SelectionMarker>,
10874    selection_marker_cursor: usize,
10875    cancelled_selection_members: Vec<SelectionCancellation>,
10876    recorded_continue_as_new_sequence: Option<u64>,
10877    continue_as_new_consumed: bool,
10878    command_cursor: usize,
10879    condition_wait_occurrence_counter: u64,
10880    matched_recorded_pending: bool,
10881    version_markers: HashMap<String, (i32, u64)>,
10882    workflow_command_identity: String,
10883    workflow_stream_command_counter: u64,
10884    commands: Vec<Value>,
10885    local_activity_requests: Vec<local_activity::Request>,
10886    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
10887    message_stream_cursors: HashMap<String, u64>,
10888    message_stream_waits: HashMap<String, u64>,
10889}
10890
10891impl WorkflowState {
10892    #[cfg(test)]
10893    fn new(
10894        history: Vec<HistoryEvent>,
10895        task_queue: String,
10896        payload_codec: String,
10897        resume_signal: Option<ResumeSignal>,
10898    ) -> Result<Self> {
10899        Self::new_with_identity(
10900            history,
10901            None,
10902            None,
10903            task_queue,
10904            payload_codec,
10905            resume_signal,
10906        )
10907    }
10908
10909    fn new_with_identity(
10910        history: Vec<HistoryEvent>,
10911        workflow_id: Option<String>,
10912        run_id: Option<String>,
10913        task_queue: String,
10914        payload_codec: String,
10915        resume_signal: Option<ResumeSignal>,
10916    ) -> Result<Self> {
10917        Self::new_with_identity_and_scopes(
10918            history,
10919            workflow_id,
10920            run_id,
10921            task_queue,
10922            payload_codec,
10923            resume_signal,
10924            false,
10925        )
10926    }
10927
10928    fn new_with_identity_and_scopes(
10929        history: Vec<HistoryEvent>,
10930        workflow_id: Option<String>,
10931        run_id: Option<String>,
10932        task_queue: String,
10933        payload_codec: String,
10934        resume_signal: Option<ResumeSignal>,
10935        allow_cancellation_scope_authoring: bool,
10936    ) -> Result<Self> {
10937        Self::new_with_identity_and_scope_delivery(
10938            history,
10939            workflow_id,
10940            run_id,
10941            task_queue,
10942            payload_codec,
10943            resume_signal,
10944            allow_cancellation_scope_authoring,
10945            false,
10946        )
10947    }
10948
10949    fn new_with_identity_and_scope_delivery(
10950        history: Vec<HistoryEvent>,
10951        workflow_id: Option<String>,
10952        run_id: Option<String>,
10953        task_queue: String,
10954        payload_codec: String,
10955        resume_signal: Option<ResumeSignal>,
10956        allow_cancellation_scope_authoring: bool,
10957        allow_cancellation_scope_delivery: bool,
10958    ) -> Result<Self> {
10959        cooperative_cancellation::assert_cancellation_scope_replay_supported(
10960            &history,
10961            allow_cancellation_scope_authoring,
10962            allow_cancellation_scope_delivery,
10963        )?;
10964        let scopes = if allow_cancellation_scope_authoring {
10965            cancellation_scope::CancellationScopeHistory::read(
10966                &history,
10967                run_id.as_deref().unwrap_or_default(),
10968            )?
10969        } else {
10970            cancellation_scope::CancellationScopeHistory::default()
10971        };
10972        let cancellation_history = CancellationHistory::from_events(
10973            &history,
10974            run_id.as_deref().unwrap_or_default(),
10975            None,
10976        )?;
10977        if allow_cancellation_scope_authoring
10978            && cancellation_history.request.is_some()
10979            && !allow_cancellation_scope_delivery
10980        {
10981            return Err(Error::CancellationScopeExecutionUnavailable);
10982        }
10983        let scope_delivery = if allow_cancellation_scope_delivery {
10984            Some(cancellation_scope_replay::ScopeReplay::read(
10985                &history,
10986                &scopes,
10987                run_id.as_deref().unwrap_or_default(),
10988                workflow_id.as_deref().unwrap_or_default(),
10989            )?)
10990        } else {
10991            None
10992        };
10993        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
10994            &history,
10995            &payload_codec,
10996            WorkflowIdentity {
10997                workflow_id: workflow_id.clone(),
10998                run_id: run_id.clone(),
10999            },
11000        )?)?;
11001        for (sequence, opening) in &scopes.openings {
11002            if recorded_commands
11003                .iter()
11004                .any(|command| command.sequence() == *sequence)
11005            {
11006                return Err(invalid_recorded_history(
11007                    "invalid_cancellation_scope_history",
11008                    *sequence,
11009                    "distinct authored scope opening",
11010                    "operation collision",
11011                    "scope opening collides with a command",
11012                ));
11013            }
11014            recorded_commands.push(RecordedCommand::CancellationScope {
11015                sequence: *sequence,
11016                scope_id: opening.scope_id.clone(),
11017                parent_scope_id: opening.parent_scope_id.clone(),
11018                shield_parent: opening.shield_parent,
11019            });
11020        }
11021        recorded_commands.sort_by_key(RecordedCommand::sequence);
11022        if let Some(replay) = &scope_delivery {
11023            replay.bind_commands(&mut recorded_commands)?;
11024        }
11025        let selection_markers = recorded_selection_markers(&history)?;
11026        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11027        let recorded_continue_as_new = history
11028            .iter()
11029            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11030            .collect::<Vec<_>>();
11031        if recorded_continue_as_new.len() > 1 {
11032            return Err(invalid_recorded_history(
11033                "duplicate_continue_as_new_transition",
11034                recorded_continue_as_new
11035                    .last()
11036                    .and_then(|event| durable_event_sequence(event))
11037                    .unwrap_or(0),
11038                "one WorkflowContinuedAsNew event",
11039                &format!(
11040                    "{} WorkflowContinuedAsNew events",
11041                    recorded_continue_as_new.len()
11042                ),
11043                "workflow history records one continue-as-new transition more than once",
11044            ));
11045        }
11046        let recorded_continue_as_new_sequence = recorded_continue_as_new
11047            .first()
11048            .map(|event| {
11049                durable_event_sequence(event).ok_or_else(|| {
11050                    Error::NonDeterministicReplay(ReplayFailure::new(
11051                        "continue_as_new_sequence_missing",
11052                        None,
11053                        Some("recorded transition sequence".to_string()),
11054                        Some("missing sequence".to_string()),
11055                        "WorkflowContinuedAsNew history is missing its recorded sequence",
11056                    ))
11057                })
11058            })
11059            .transpose()?;
11060        let mut message_stream_cursors = HashMap::new();
11061        for event in &history {
11062            if !matches!(
11063                event.event_type.as_str(),
11064                "SignalReceived" | "SignalApplied"
11065            ) || event.payload.get("signal_name").and_then(Value::as_str)
11066                != Some(MESSAGE_STREAM_SIGNAL)
11067            {
11068                continue;
11069            }
11070            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
11071            if arguments.len() != 1 {
11072                continue;
11073            }
11074            let envelope = arguments[0].clone().into_json()?;
11075            let Some(envelope) = envelope.as_object() else {
11076                continue;
11077            };
11078            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
11079            {
11080                continue;
11081            }
11082            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11083                continue;
11084            };
11085            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11086            else {
11087                continue;
11088            };
11089            let cursor = message_stream_cursors
11090                .entry(stream_name.to_string())
11091                .or_insert(0);
11092            *cursor = (*cursor).max(through_position);
11093        }
11094        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
11095        let cancel_requested = history.iter().any(|event| {
11096            matches!(
11097                event.event_type.as_str(),
11098                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
11099            )
11100        });
11101        let cancellation_clock = cancellation_history
11102            .request
11103            .as_ref()
11104            .and_then(|request| request.context.as_ref())
11105            .map(|_| {
11106                cancellation_replay_clock::ReplayClock::new(
11107                    &history,
11108                    &recorded_commands,
11109                    cancellation_history.delivery_index,
11110                )
11111            })
11112            .or_else(|| {
11113                scope_delivery.as_ref().map(|_| {
11114                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
11115                })
11116            });
11117        Ok(Self {
11118            workflow_command_identity: String::new(),
11119            workflow_stream_command_counter: 0,
11120            workflow_id,
11121            run_id,
11122            task_queue,
11123            payload_codec,
11124            history_events: Arc::new(history),
11125            history_budget: WorkflowHistoryBudget {
11126                event_count,
11127                ..WorkflowHistoryBudget::default()
11128            },
11129            cancel_requested,
11130            cancellation_history,
11131            cancellation_consumed: false,
11132            cancellation_clock,
11133            cancellation_shield_depth: 0,
11134            cancellation_delivery_enabled: false,
11135            cancellation_delivery_intent: None,
11136            cancellation_delivery_command_count: 0,
11137            allow_cancellation_scope_authoring,
11138            cancellation_scope_opening: None,
11139            cancellation_scope_memberships: scopes.memberships,
11140            scope_delivery,
11141            resume_signal,
11142            recorded_commands,
11143            selection_markers,
11144            selection_marker_cursor: 0,
11145            cancelled_selection_members,
11146            recorded_continue_as_new_sequence,
11147            continue_as_new_consumed: false,
11148            command_cursor: 0,
11149            condition_wait_occurrence_counter: 0,
11150            matched_recorded_pending: false,
11151            version_markers: HashMap::new(),
11152            commands: Vec::new(),
11153            local_activity_requests: Vec::new(),
11154            message_stream_messages: HashMap::new(),
11155            message_stream_cursors,
11156            message_stream_waits: HashMap::new(),
11157        })
11158    }
11159}
11160
11161enum MessageStreamDelivery {
11162    Message(MessageStreamMessage),
11163    Cursor {
11164        stream_name: String,
11165        through_position: u64,
11166    },
11167}
11168
11169fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
11170    if arguments.len() != 1 {
11171        return Ok(None);
11172    }
11173    let envelope = arguments
11174        .into_iter()
11175        .next()
11176        .expect("one argument was checked");
11177    let Some(envelope) = envelope.as_object() else {
11178        return Ok(None);
11179    };
11180    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11181        return Ok(None);
11182    };
11183    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
11184        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11185        else {
11186            return Ok(None);
11187        };
11188        return Ok(Some(MessageStreamDelivery::Cursor {
11189            stream_name: stream_name.to_string(),
11190            through_position,
11191        }));
11192    }
11193    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
11194        return Ok(None);
11195    }
11196    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
11197        return Ok(None);
11198    };
11199    let Some(position) = envelope
11200        .get("position")
11201        .and_then(Value::as_u64)
11202        .filter(|value| *value > 0)
11203    else {
11204        return Ok(None);
11205    };
11206    let Some(payload_envelope) = envelope.get("payload_envelope") else {
11207        return Ok(None);
11208    };
11209    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
11210    else {
11211        return Ok(None);
11212    };
11213    let decoded = decode_avro_value(&payload_envelope)?;
11214    let AvroValue::Array(values) = decoded else {
11215        return Ok(None);
11216    };
11217    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
11218        stream_name: stream_name.to_string(),
11219        message_id: message_id.to_string(),
11220        position,
11221        arguments: values,
11222    })))
11223}
11224
11225#[derive(Clone, Debug)]
11226enum RecordedCommand {
11227    CancellationScope {
11228        sequence: u64,
11229        scope_id: String,
11230        parent_scope_id: String,
11231        shield_parent: bool,
11232    },
11233    CancellationGroup {
11234        sequence: u64,
11235        span: u64,
11236        original: Vec<RecordedCommand>,
11237    },
11238    CancellationBoundary {
11239        sequence: u64,
11240        call_kind: CancellationCallKind,
11241        original: Option<Box<RecordedCommand>>,
11242    },
11243    Activity {
11244        sequence: u64,
11245        activity_type: Option<String>,
11246        cancellation_policy: String,
11247        options: Option<RecordedActivityOptions>,
11248        outcome: Option<ActivityOutcome>,
11249        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11250    },
11251    Timer {
11252        sequence: u64,
11253        delay_seconds: u64,
11254        fired: bool,
11255        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11256    },
11257    ChildWorkflow {
11258        sequence: u64,
11259        workflow_type: Option<String>,
11260        policies: RecordedChildPolicies,
11261        outcome: Option<ChildWorkflowOutcome>,
11262        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11263    },
11264    SignalWait {
11265        sequence: u64,
11266        signal_name: String,
11267        value: Option<Vec<AvroValue>>,
11268        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11269    },
11270    ConditionWait {
11271        sequence: u64,
11272        occurrence_id: String,
11273        condition_key: Option<String>,
11274        predicate_identity: String,
11275        timeout_seconds: Option<u64>,
11276        result: Option<ConditionWaitResult>,
11277        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11278    },
11279    SearchAttributes {
11280        sequence: u64,
11281        attributes: Value,
11282        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
11283    },
11284    SideEffect {
11285        sequence: u64,
11286        value: AvroValue,
11287    },
11288    VersionMarker {
11289        sequence: u64,
11290        change_id: String,
11291        version: i32,
11292    },
11293    Memo {
11294        sequence: u64,
11295        entries: AvroValue,
11296    },
11297}
11298
11299#[derive(Clone, Debug, PartialEq, Eq)]
11300struct SelectionMarker {
11301    selection_group_id: String,
11302    selection_group_base_sequence: u64,
11303    selection_group_size: usize,
11304    member_key: SelectionKey,
11305    member_index: usize,
11306    member_base_sequence: u64,
11307    member_size: usize,
11308    operation_kind: String,
11309    operation_identity: String,
11310    outcome: String,
11311    resolution_event_id: String,
11312    resolution_event_type: String,
11313}
11314
11315#[derive(Clone, Debug, PartialEq, Eq)]
11316struct SelectionCancellation {
11317    selection_group_id: String,
11318    member_key: SelectionKey,
11319    member_index: usize,
11320    member_base_sequence: u64,
11321    member_size: usize,
11322    operation_kind: String,
11323    operation_identity: String,
11324}
11325
11326fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
11327    let mut markers: Vec<SelectionMarker> = Vec::new();
11328    for event in events
11329        .iter()
11330        .filter(|event| event.event_type == "SelectionResolved")
11331    {
11332        let payload = &event.payload;
11333        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
11334        let group_size = required_selection_usize(payload, "selection_group_size")?;
11335        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
11336        let member_size = required_selection_usize(payload, "member_size")?;
11337        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
11338        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
11339            invalid_recorded_history(
11340                "selection_marker_invalid",
11341                base_sequence,
11342                "non-empty selection_group_id",
11343                &payload.to_string(),
11344                "selection winner history is missing its durable group identity",
11345            )
11346        })?;
11347        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
11348        if group_id != expected_group_id {
11349            return Err(invalid_recorded_history(
11350                "selection_marker_invalid",
11351                base_sequence,
11352                &expected_group_id,
11353                &group_id,
11354                "selection winner history contains an incompatible group identity",
11355            ));
11356        }
11357        let group_end = base_sequence
11358            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
11359            .unwrap_or(u64::MAX);
11360        let member_end = member_base_sequence
11361            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
11362            .unwrap_or(u64::MAX);
11363        if member_index >= group_size
11364            || member_base_sequence < base_sequence
11365            || member_end > group_end
11366        {
11367            return Err(invalid_recorded_history(
11368                "selection_marker_invalid",
11369                base_sequence,
11370                "winner member within selection group bounds",
11371                &payload.to_string(),
11372                "selection winner history contains an invalid member range",
11373            ));
11374        }
11375        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
11376            invalid_recorded_history(
11377                "selection_marker_invalid",
11378                base_sequence,
11379                "selection operation kind",
11380                &payload.to_string(),
11381                "selection winner history is missing its operation kind",
11382            )
11383        })?;
11384        if !matches!(
11385            operation_kind.as_str(),
11386            "activity" | "child" | "timer" | "signal" | "condition" | "group"
11387        ) {
11388            return Err(invalid_recorded_history(
11389                "selection_marker_invalid",
11390                base_sequence,
11391                "activity, child, timer, signal, condition, or group",
11392                &operation_kind,
11393                "selection winner history contains an unsupported operation kind",
11394            ));
11395        }
11396        let operation_identity =
11397            payload_string(payload, "operation_identity").ok_or_else(|| {
11398                invalid_recorded_history(
11399                    "selection_marker_invalid",
11400                    base_sequence,
11401                    "non-empty operation identity",
11402                    &payload.to_string(),
11403                    "selection winner history is missing its durable operation identity",
11404                )
11405            })?;
11406        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
11407            invalid_recorded_history(
11408                "selection_marker_invalid",
11409                base_sequence,
11410                "completed or failed selection outcome",
11411                &payload.to_string(),
11412                "selection winner history is missing its outcome",
11413            )
11414        })?;
11415        if !matches!(outcome.as_str(), "completed" | "failed") {
11416            return Err(invalid_recorded_history(
11417                "selection_marker_invalid",
11418                base_sequence,
11419                "completed or failed selection outcome",
11420                &outcome,
11421                "selection winner history contains an unsupported outcome",
11422            ));
11423        }
11424        let marker = SelectionMarker {
11425            selection_group_id: group_id,
11426            selection_group_base_sequence: base_sequence,
11427            selection_group_size: group_size,
11428            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
11429            member_index,
11430            member_base_sequence,
11431            member_size,
11432            operation_kind,
11433            operation_identity,
11434            outcome,
11435            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
11436                || {
11437                    invalid_recorded_history(
11438                        "selection_marker_invalid",
11439                        base_sequence,
11440                        "durable resolution_event_id",
11441                        &payload.to_string(),
11442                        "selection winner history is missing its terminal event identity",
11443                    )
11444                },
11445            )?,
11446            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
11447                || {
11448                    invalid_recorded_history(
11449                        "selection_marker_invalid",
11450                        base_sequence,
11451                        "durable resolution_event_type",
11452                        &payload.to_string(),
11453                        "selection winner history is missing its terminal event type",
11454                    )
11455                },
11456            )?,
11457        };
11458        if let Some(existing) = markers
11459            .iter()
11460            .find(|existing| existing.selection_group_id == marker.selection_group_id)
11461        {
11462            if existing != &marker {
11463                return Err(invalid_recorded_history(
11464                    "selection_marker_conflict",
11465                    base_sequence,
11466                    &format!("one winner for {}", marker.selection_group_id),
11467                    &payload.to_string(),
11468                    "selection history records conflicting winners for one durable group",
11469                ));
11470            }
11471            continue;
11472        }
11473        markers.push(marker);
11474    }
11475    Ok(markers)
11476}
11477
11478fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
11479    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
11480    for event in events
11481        .iter()
11482        .filter(|event| event.event_type == "SelectionOperationCancelled")
11483    {
11484        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
11485            invalid_recorded_history(
11486                "selection_cancellation_invalid",
11487                0,
11488                "non-empty selection_group_id",
11489                &event.payload.to_string(),
11490                "selection cancellation history is missing its group identity",
11491            )
11492        })?;
11493        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
11494        let marker = SelectionCancellation {
11495            selection_group_id: group_id,
11496            member_key: selection_key_from_value(
11497                event.payload.get("member_key"),
11498                member_base_sequence,
11499            )?,
11500            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
11501            member_base_sequence,
11502            member_size: required_selection_usize(&event.payload, "member_size")?,
11503            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
11504                invalid_recorded_history(
11505                    "selection_cancellation_invalid",
11506                    member_base_sequence,
11507                    "selection operation kind",
11508                    &event.payload.to_string(),
11509                    "selection cancellation is missing its operation kind",
11510                )
11511            })?,
11512            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
11513                || {
11514                    invalid_recorded_history(
11515                        "selection_cancellation_invalid",
11516                        member_base_sequence,
11517                        "selection operation identity",
11518                        &event.payload.to_string(),
11519                        "selection cancellation is missing its operation identity",
11520                    )
11521                },
11522            )?,
11523        };
11524        if let Some(existing) = cancelled.iter().find(|recorded| {
11525            recorded.selection_group_id == marker.selection_group_id
11526                && recorded.member_base_sequence == marker.member_base_sequence
11527        }) {
11528            if existing != &marker {
11529                return Err(invalid_recorded_history(
11530                    "selection_cancellation_conflict",
11531                    member_base_sequence,
11532                    "one stable SelectionOperationCancelled marker",
11533                    &event.payload.to_string(),
11534                    "selection cancellation history contains conflicting member metadata",
11535                ));
11536            }
11537        } else {
11538            cancelled.push(marker);
11539        }
11540    }
11541    Ok(cancelled)
11542}
11543
11544fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
11545    payload
11546        .get(field)
11547        .and_then(value_as_u64)
11548        .filter(|value| *value > 0)
11549        .ok_or_else(|| {
11550            invalid_recorded_history(
11551                "selection_marker_invalid",
11552                0,
11553                &format!("positive integer {field}"),
11554                &payload.to_string(),
11555                "selection history contains invalid durable identity metadata",
11556            )
11557        })
11558}
11559
11560fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
11561    required_selection_usize_allow_zero(payload, field).and_then(|value| {
11562        if value > 0 {
11563            Ok(value)
11564        } else {
11565            Err(invalid_recorded_history(
11566                "selection_marker_invalid",
11567                0,
11568                &format!("positive integer {field}"),
11569                &payload.to_string(),
11570                "selection history contains invalid durable identity metadata",
11571            ))
11572        }
11573    })
11574}
11575
11576fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
11577    payload
11578        .get(field)
11579        .and_then(value_as_u64)
11580        .and_then(|value| usize::try_from(value).ok())
11581        .ok_or_else(|| {
11582            invalid_recorded_history(
11583                "selection_marker_invalid",
11584                0,
11585                &format!("non-negative integer {field}"),
11586                &payload.to_string(),
11587                "selection history contains invalid durable identity metadata",
11588            )
11589        })
11590}
11591
11592#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11593struct RecordedActivityOptions {
11594    task_queue: RecordedSnapshotValue<Option<String>>,
11595    execution_mode: RecordedSnapshotValue<Option<String>>,
11596    retry_policy: ActivityRetrySnapshot,
11597    worker_session: Option<Value>,
11598}
11599
11600#[derive(Clone, Debug)]
11601struct RecordedChildPolicies {
11602    parent_close_policy: String,
11603    cancellation_policy: String,
11604}
11605
11606fn recorded_activity_cancellation_policy(
11607    events: &[&HistoryEvent],
11608    sequence: u64,
11609) -> Result<String> {
11610    let mut policy: Option<String> = None;
11611    for event in events.iter().filter(|event| {
11612        matches!(
11613            event.event_type.as_str(),
11614            "ActivityScheduled"
11615                | "ActivityStarted"
11616                | "ActivityCompleted"
11617                | "ActivityFailed"
11618                | "ActivityTimedOut"
11619                | "ActivityCancelled"
11620        )
11621    }) {
11622        for source in [Some(&event.payload), event.payload.get("activity")]
11623            .into_iter()
11624            .flatten()
11625        {
11626            let Some(value) = source.get("cancellation_policy") else {
11627                continue;
11628            };
11629            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
11630                value.as_str()
11631            else {
11632                return Err(invalid_recorded_history(
11633                    "invalid_activity_cancellation_policy_history",
11634                    sequence,
11635                    "supported Activity cancellation policy",
11636                    &value.to_string(),
11637                    "Activity history contains an invalid cancellation policy",
11638                ));
11639            };
11640            if let Some(previous) = policy.as_deref() {
11641                if previous != incoming {
11642                    return Err(invalid_recorded_history(
11643                        "activity_cancellation_policy_history_conflict",
11644                        sequence,
11645                        previous,
11646                        incoming,
11647                        "Activity cancellation policy changed between history events",
11648                    ));
11649                }
11650            }
11651            policy = Some(incoming.to_string());
11652        }
11653        policy.get_or_insert_with(|| "try_cancel".to_string());
11654    }
11655    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
11656}
11657
11658fn recorded_child_policy_value<'a>(
11659    payload: &'a Value,
11660    field: &str,
11661    sequence: u64,
11662) -> Result<Option<&'a str>> {
11663    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
11664        return Ok(None);
11665    };
11666    let valid = match (field, value.as_str()) {
11667        (
11668            "parent_close_policy",
11669            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11670        ) => true,
11671        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11672            true
11673        }
11674        _ => false,
11675    };
11676    if !valid {
11677        return Err(invalid_recorded_history(
11678            "invalid_child_workflow_policy_history",
11679            sequence,
11680            "supported child workflow policy",
11681            &value.to_string(),
11682            "child workflow history contains an invalid policy",
11683        ));
11684    }
11685    Ok(value.as_str())
11686}
11687
11688fn recorded_child_policies(
11689    events: &[&HistoryEvent],
11690    scheduled: &HistoryEvent,
11691    sequence: u64,
11692) -> Result<RecordedChildPolicies> {
11693    let parent_close_policy =
11694        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11695            .unwrap_or("abandon")
11696            .to_string();
11697    let cancellation_policy =
11698        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11699            .unwrap_or("abandon")
11700            .to_string();
11701    for event in events {
11702        for (field, expected) in [
11703            ("parent_close_policy", parent_close_policy.as_str()),
11704            ("cancellation_policy", cancellation_policy.as_str()),
11705        ] {
11706            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11707                if actual != expected {
11708                    return Err(invalid_recorded_history(
11709                        "child_workflow_policy_history_conflict",
11710                        sequence,
11711                        expected,
11712                        actual,
11713                        "child workflow policy changed between history events",
11714                    ));
11715                }
11716            }
11717        }
11718    }
11719    Ok(RecordedChildPolicies {
11720        parent_close_policy,
11721        cancellation_policy,
11722    })
11723}
11724
11725fn ensure_child_policies_match(
11726    sequence: u64,
11727    recorded: &RecordedChildPolicies,
11728    current: &ChildWorkflowOptions,
11729) -> Result<()> {
11730    for (field, expected, actual) in [
11731        (
11732            "parent_close_policy",
11733            recorded.parent_close_policy.as_str(),
11734            current.parent_close_policy.as_str(),
11735        ),
11736        (
11737            "cancellation_policy",
11738            recorded.cancellation_policy.as_str(),
11739            current.cancellation_policy.as_str(),
11740        ),
11741    ] {
11742        if expected != actual {
11743            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11744                "child_workflow_policy_changed",
11745                Some(sequence),
11746                Some(expected.to_string()),
11747                Some(actual.to_string()),
11748                format!("child workflow {field} changed during replay"),
11749            )));
11750        }
11751    }
11752    Ok(())
11753}
11754
11755#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11756enum RecordedSnapshotValue<T> {
11757    /// Older history did not persist this field, so it cannot constrain replay.
11758    Unknown,
11759    Known(T),
11760}
11761
11762impl<T: PartialEq> RecordedSnapshotValue<T> {
11763    fn matches_current(&self, current: &Self) -> bool {
11764        match self {
11765            Self::Unknown => true,
11766            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11767        }
11768    }
11769}
11770
11771#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11772struct ActivityRetrySnapshot {
11773    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11774    max_attempts: RecordedSnapshotValue<Option<u64>>,
11775    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11776    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11777    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11778    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11779    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11780    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11781}
11782
11783impl ActivityRetrySnapshot {
11784    fn matches_current(&self, current: &Self) -> bool {
11785        self.snapshot_version
11786            .matches_current(&current.snapshot_version)
11787            && self.max_attempts.matches_current(&current.max_attempts)
11788            && self
11789                .backoff_seconds
11790                .matches_current(&current.backoff_seconds)
11791            && self
11792                .start_to_close_timeout
11793                .matches_current(&current.start_to_close_timeout)
11794            && self
11795                .schedule_to_start_timeout
11796                .matches_current(&current.schedule_to_start_timeout)
11797            && self
11798                .schedule_to_close_timeout
11799                .matches_current(&current.schedule_to_close_timeout)
11800            && self
11801                .heartbeat_timeout
11802                .matches_current(&current.heartbeat_timeout)
11803            && self
11804                .non_retryable_error_types
11805                .matches_current(&current.non_retryable_error_types)
11806    }
11807}
11808
11809fn recorded_optional_u64(
11810    object: Option<&serde_json::Map<String, Value>>,
11811    field: &str,
11812) -> RecordedSnapshotValue<Option<u64>> {
11813    match object.and_then(|object| object.get(field)) {
11814        None => RecordedSnapshotValue::Unknown,
11815        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11816        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
11817    }
11818}
11819
11820fn recorded_optional_string(
11821    object: &serde_json::Map<String, Value>,
11822    field: &str,
11823) -> RecordedSnapshotValue<Option<String>> {
11824    match object.get(field) {
11825        None => RecordedSnapshotValue::Unknown,
11826        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11827        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
11828    }
11829}
11830
11831fn recorded_activity_execution_mode(
11832    events: &[&HistoryEvent],
11833    sequence: u64,
11834) -> Result<RecordedSnapshotValue<Option<String>>> {
11835    let mut recorded = RecordedSnapshotValue::Unknown;
11836    for event in events {
11837        for object in [
11838            event.payload.as_object(),
11839            event.payload.get("activity").and_then(Value::as_object),
11840        ]
11841        .into_iter()
11842        .flatten()
11843        {
11844            let mode = match object.get("execution_mode") {
11845                None => None,
11846                Some(Value::Null) => Some(None),
11847                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
11848                Some(_) => {
11849                    return Err(invalid_recorded_history(
11850                        "activity_execution_mode_invalid",
11851                        sequence,
11852                        "null or a non-empty execution mode",
11853                        "invalid execution_mode",
11854                        "activity history contains an invalid execution mode",
11855                    ))
11856                }
11857            };
11858            let legacy_mode = match object.get("local_activity") {
11859                None => None,
11860                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
11861                Some(_) => {
11862                    return Err(invalid_recorded_history(
11863                        "activity_execution_mode_invalid",
11864                        sequence,
11865                        "boolean local_activity",
11866                        "invalid local_activity",
11867                        "activity history contains an invalid local-activity marker",
11868                    ))
11869                }
11870            };
11871            for mode in [mode, legacy_mode].into_iter().flatten() {
11872                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
11873                {
11874                    return Err(invalid_recorded_history(
11875                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
11876                        "activity lifecycle events at one workflow sequence disagree on execution mode",
11877                    ));
11878                }
11879                recorded = RecordedSnapshotValue::Known(mode);
11880            }
11881        }
11882    }
11883    Ok(recorded)
11884}
11885
11886fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
11887    let policy = policy.and_then(Value::as_object);
11888    let backoff_seconds = policy
11889        .and_then(|policy| policy.get("backoff_seconds"))
11890        .and_then(Value::as_array)
11891        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11892        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
11893    let mut non_retryable_error_types = Vec::new();
11894    for error_type in policy
11895        .and_then(|policy| policy.get("non_retryable_error_types"))
11896        .and_then(Value::as_array)
11897        .into_iter()
11898        .flatten()
11899        .filter_map(Value::as_str)
11900        .map(str::trim)
11901        .filter(|error_type| !error_type.is_empty())
11902    {
11903        if !non_retryable_error_types
11904            .iter()
11905            .any(|recorded| recorded == error_type)
11906        {
11907            non_retryable_error_types.push(error_type.to_string());
11908        }
11909    }
11910
11911    ActivityRetrySnapshot {
11912        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
11913        max_attempts: recorded_optional_u64(policy, "max_attempts"),
11914        backoff_seconds,
11915        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
11916        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
11917        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
11918        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
11919        non_retryable_error_types: if policy
11920            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
11921        {
11922            RecordedSnapshotValue::Known(non_retryable_error_types)
11923        } else {
11924            RecordedSnapshotValue::Unknown
11925        },
11926    }
11927}
11928
11929fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
11930    let policy = options.retry_policy.as_ref();
11931    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
11932        Some(Value::Null) => None,
11933        Some(value) => value_as_u64(value),
11934        None => Some(1),
11935    };
11936    let backoff_seconds = policy
11937        .and_then(|policy| policy.get("backoff_seconds"))
11938        .and_then(Value::as_array)
11939        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11940        .unwrap_or_default();
11941    let non_retryable_error_types = policy
11942        .and_then(|policy| policy.get("non_retryable_error_types"))
11943        .and_then(Value::as_array)
11944        .into_iter()
11945        .flatten()
11946        .filter_map(Value::as_str)
11947        .map(str::to_string)
11948        .collect();
11949
11950    ActivityRetrySnapshot {
11951        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
11952        max_attempts: RecordedSnapshotValue::Known(max_attempts),
11953        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
11954        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
11955        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
11956        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
11957        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
11958        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
11959    }
11960}
11961
11962fn activity_options_description(options: &RecordedActivityOptions) -> String {
11963    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
11964}
11965
11966impl RecordedCommand {
11967    fn sequence(&self) -> u64 {
11968        match self {
11969            Self::CancellationGroup { sequence, .. }
11970            | Self::CancellationScope { sequence, .. }
11971            | Self::CancellationBoundary { sequence, .. }
11972            | Self::Activity { sequence, .. }
11973            | Self::Timer { sequence, .. }
11974            | Self::ChildWorkflow { sequence, .. }
11975            | Self::SignalWait { sequence, .. }
11976            | Self::ConditionWait { sequence, .. }
11977            | Self::SearchAttributes { sequence, .. }
11978            | Self::SideEffect { sequence, .. }
11979            | Self::VersionMarker { sequence, .. }
11980            | Self::Memo { sequence, .. } => *sequence,
11981        }
11982    }
11983
11984    fn shape(&self) -> &'static str {
11985        match self {
11986            Self::CancellationScope { .. } => "cancellation scope",
11987            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
11988                "cooperative cancellation"
11989            }
11990            Self::Activity { .. } => "activity",
11991            Self::Timer { .. } => "timer",
11992            Self::ChildWorkflow { .. } => "child workflow",
11993            Self::SignalWait { .. } => "signal wait",
11994            Self::ConditionWait { .. } => "condition wait",
11995            Self::SearchAttributes { .. } => "search-attribute update",
11996            Self::SideEffect { .. } => "side effect",
11997            Self::VersionMarker { .. } => "version marker",
11998            Self::Memo { .. } => "memo upsert",
11999        }
12000    }
12001}
12002
12003fn ensure_version_supported(
12004    change_id: &str,
12005    version: i32,
12006    min_supported: i32,
12007    max_supported: i32,
12008    sequence: u64,
12009) -> Result<()> {
12010    if (min_supported..=max_supported).contains(&version) {
12011        return Ok(());
12012    }
12013    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12014        "version_marker_incompatible_range",
12015        (sequence != 0).then_some(sequence),
12016        Some(format!("{min_supported}..={max_supported}")),
12017        Some(format!("{change_id}:{version}")),
12018        "recorded workflow version is outside the range supported by current code",
12019    )))
12020}
12021
12022#[derive(Clone, Debug)]
12023struct ResumeSignal {
12024    signal_name: String,
12025    arguments: Vec<AvroValue>,
12026}
12027
12028const MAX_PARALLEL_OPERATIONS: usize = 1000;
12029
12030fn parallel_group_prefix(kind: &str) -> &'static str {
12031    match kind {
12032        "activity" => "parallel-activities",
12033        "child" => "parallel-children",
12034        "timer" => "parallel-timers",
12035        _ => "parallel-calls",
12036    }
12037}
12038
12039fn parallel_group_entry(
12040    base_sequence: u64,
12041    size: usize,
12042    index: usize,
12043    kind: &str,
12044) -> ParallelGroupMetadata {
12045    ParallelGroupMetadata {
12046        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12047        parallel_group_kind: kind.to_string(),
12048        parallel_group_base_sequence: base_sequence,
12049        parallel_group_size: size,
12050        parallel_group_index: index,
12051        parallel_group_mode: None,
12052        selection_member_key: None,
12053        selection_member_index: None,
12054        selection_member_base_sequence: None,
12055        selection_member_size: None,
12056        selection_member_kind: None,
12057    }
12058}
12059
12060struct SelectionMemberMetadata {
12061    key: SelectionKey,
12062    index: usize,
12063    base_sequence: u64,
12064    size: usize,
12065    kind: String,
12066}
12067
12068fn selection_group_entry(
12069    base_sequence: u64,
12070    size: usize,
12071    index: usize,
12072    kind: &str,
12073    member: &SelectionMemberMetadata,
12074) -> ParallelGroupMetadata {
12075    ParallelGroupMetadata {
12076        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
12077        parallel_group_kind: kind.to_string(),
12078        parallel_group_base_sequence: base_sequence,
12079        parallel_group_size: size,
12080        parallel_group_index: index,
12081        parallel_group_mode: Some("select".to_string()),
12082        selection_member_key: Some(member.key.clone()),
12083        selection_member_index: Some(member.index),
12084        selection_member_base_sequence: Some(member.base_sequence),
12085        selection_member_size: Some(member.size),
12086        selection_member_kind: Some(member.kind.clone()),
12087    }
12088}
12089
12090fn apply_parallel_group_path(
12091    command: &mut serde_json::Map<String, Value>,
12092    path: &[ParallelGroupMetadata],
12093) {
12094    let Some(inner) = path.last() else {
12095        return;
12096    };
12097    command.insert(
12098        "parallel_group_id".to_string(),
12099        json!(inner.parallel_group_id),
12100    );
12101    command.insert(
12102        "parallel_group_kind".to_string(),
12103        json!(inner.parallel_group_kind),
12104    );
12105    command.insert(
12106        "parallel_group_base_sequence".to_string(),
12107        json!(inner.parallel_group_base_sequence),
12108    );
12109    command.insert(
12110        "parallel_group_size".to_string(),
12111        json!(inner.parallel_group_size),
12112    );
12113    command.insert(
12114        "parallel_group_index".to_string(),
12115        json!(inner.parallel_group_index),
12116    );
12117    if let Some(mode) = &inner.parallel_group_mode {
12118        command.insert("parallel_group_mode".to_string(), json!(mode));
12119    }
12120    if let Some(key) = &inner.selection_member_key {
12121        command.insert("selection_member_key".to_string(), json!(key));
12122    }
12123    if let Some(index) = inner.selection_member_index {
12124        command.insert("selection_member_index".to_string(), json!(index));
12125    }
12126    if let Some(base_sequence) = inner.selection_member_base_sequence {
12127        command.insert(
12128            "selection_member_base_sequence".to_string(),
12129            json!(base_sequence),
12130        );
12131    }
12132    if let Some(size) = inner.selection_member_size {
12133        command.insert("selection_member_size".to_string(), json!(size));
12134    }
12135    if let Some(kind) = &inner.selection_member_kind {
12136        command.insert("selection_member_kind".to_string(), json!(kind));
12137    }
12138    command.insert("parallel_group_path".to_string(), json!(path));
12139}
12140
12141fn ensure_parallel_path_matches(
12142    sequence: u64,
12143    recorded: Option<&[ParallelGroupMetadata]>,
12144    expected: &[ParallelGroupMetadata],
12145) -> Result<()> {
12146    match (recorded, expected.is_empty()) {
12147        (None, true) => Ok(()),
12148        (Some(recorded), false) if recorded == expected => Ok(()),
12149        (None, false) => Err(invalid_recorded_history(
12150            "parallel_group_metadata_missing",
12151            sequence,
12152            &serde_json::to_string(expected).unwrap_or_default(),
12153            "<missing>",
12154            "recorded parallel member is missing its durable group path",
12155        )),
12156        (Some(recorded), true) => Err(invalid_recorded_history(
12157            "parallel_group_shape_mismatch",
12158            sequence,
12159            "sequential command",
12160            &serde_json::to_string(recorded).unwrap_or_default(),
12161            "recorded command belonged to a parallel group but current code schedules it sequentially",
12162        )),
12163        (Some(recorded), false) => Err(invalid_recorded_history(
12164            "parallel_group_shape_mismatch",
12165            sequence,
12166            &serde_json::to_string(recorded).unwrap_or_default(),
12167            &serde_json::to_string(expected).unwrap_or_default(),
12168            "recorded parallel-group identity or path changed during replay",
12169        )),
12170    }
12171}
12172
12173#[derive(Clone, Debug)]
12174enum ParallelShape {
12175    Leaf,
12176    Group(Vec<ParallelShape>),
12177}
12178
12179struct ParallelDescriptor {
12180    operation: ParallelOperation,
12181    offset: usize,
12182    member_path: Vec<usize>,
12183    group_path: Vec<ParallelGroupMetadata>,
12184}
12185
12186fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
12187    operations
12188        .iter()
12189        .map(|operation| match operation {
12190            ParallelOperation::Group(children) => parallel_leaf_count(children),
12191            _ => 1,
12192        })
12193        .sum()
12194}
12195
12196fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
12197    match operation {
12198        ParallelOperation::Activity { .. } => Some("activity"),
12199        ParallelOperation::ChildWorkflow { .. } => Some("child"),
12200        ParallelOperation::Timer(_) => Some("timer"),
12201        ParallelOperation::Signal(_) => Some("signal"),
12202        ParallelOperation::Condition { .. } => Some("condition"),
12203        ParallelOperation::Group(children) => parallel_group_kind(children),
12204    }
12205}
12206
12207fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
12208    let mut kind = None;
12209    for operation in operations {
12210        let Some(operation_kind) = parallel_operation_kind(operation) else {
12211            continue;
12212        };
12213        match kind {
12214            None => kind = Some(operation_kind),
12215            Some(current) if current == operation_kind => {}
12216            Some(_) => return Some("mixed"),
12217        }
12218    }
12219    kind
12220}
12221
12222fn validate_parallel_operations(
12223    operations: &[ParallelOperation],
12224    member_path: &mut Vec<usize>,
12225    root: bool,
12226) -> Result<()> {
12227    let leaves = parallel_leaf_count(operations);
12228    if leaves > MAX_PARALLEL_OPERATIONS {
12229        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12230            reason: "fan_out_limit_exceeded",
12231            member_path: member_path.clone(),
12232            message: format!(
12233                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12234            ),
12235        }));
12236    }
12237    if !root && operations.is_empty() {
12238        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12239            reason: "nested_group_empty",
12240            member_path: member_path.clone(),
12241            message: "a nested group must contain at least one durable leaf".to_string(),
12242        }));
12243    }
12244
12245    for (index, operation) in operations.iter().enumerate() {
12246        member_path.push(index);
12247        match operation {
12248            ParallelOperation::Activity {
12249                options, arguments, ..
12250            } => {
12251                options
12252                    .validate()
12253                    .map_err(|error| Error::InvalidActivityOptions(error))?;
12254                if let Err(error) = arguments {
12255                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12256                        reason: "arguments_invalid",
12257                        member_path: member_path.clone(),
12258                        message: error.to_string(),
12259                    }));
12260                }
12261            }
12262            ParallelOperation::ChildWorkflow {
12263                options, arguments, ..
12264            } => {
12265                validate_parallel_child_options(options)?;
12266                if let Err(error) = arguments {
12267                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12268                        reason: "arguments_invalid",
12269                        member_path: member_path.clone(),
12270                        message: error.to_string(),
12271                    }));
12272                }
12273            }
12274            ParallelOperation::Timer(duration)
12275                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
12276            {
12277                return Err(Error::TimerDurationOverflow);
12278            }
12279            ParallelOperation::Timer(_) => {}
12280            ParallelOperation::Signal(signal_name) => {
12281                validate_user_signal_name(signal_name)?;
12282                if signal_name.trim().is_empty() {
12283                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12284                        reason: "signal_name_empty",
12285                        member_path: member_path.clone(),
12286                        message: "signal wait name must not be empty".to_string(),
12287                    }));
12288                }
12289            }
12290            ParallelOperation::Condition { options, .. } => {
12291                options.validate()?;
12292            }
12293            ParallelOperation::Group(children) => {
12294                validate_parallel_operations(children, member_path, false)?;
12295            }
12296        }
12297        member_path.pop();
12298    }
12299    Ok(())
12300}
12301
12302fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
12303    if options.task_queue.trim().is_empty() {
12304        return Err(Error::InvalidChildWorkflowOptions(
12305            "task_queue must not be empty".to_string(),
12306        ));
12307    }
12308    for (name, value) in [
12309        (
12310            "execution_timeout_seconds",
12311            options.execution_timeout_seconds,
12312        ),
12313        ("run_timeout_seconds", options.run_timeout_seconds),
12314    ] {
12315        if value == Some(0) {
12316            return Err(Error::InvalidChildWorkflowOptions(format!(
12317                "{name} must be at least 1"
12318            )));
12319        }
12320    }
12321    if options
12322        .retry_policy
12323        .as_ref()
12324        .is_some_and(|policy| policy.max_attempts == Some(0))
12325    {
12326        return Err(Error::InvalidChildWorkflowOptions(
12327            "retry_policy.max_attempts must be at least 1".to_string(),
12328        ));
12329    }
12330    Ok(())
12331}
12332
12333fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
12334    ParallelShape::Group(
12335        operations
12336            .iter()
12337            .map(|operation| match operation {
12338                ParallelOperation::Group(children) => parallel_shape(children),
12339                _ => ParallelShape::Leaf,
12340            })
12341            .collect(),
12342    )
12343}
12344
12345fn parallel_descriptors(
12346    operations: Vec<ParallelOperation>,
12347    base_sequence: u64,
12348) -> Result<Vec<ParallelDescriptor>> {
12349    let size = parallel_leaf_count(&operations);
12350    let kind = parallel_group_kind(&operations).unwrap_or("activity");
12351    let mut descriptors = Vec::with_capacity(size);
12352    let mut cursor = 0;
12353
12354    for (index, operation) in operations.into_iter().enumerate() {
12355        match operation {
12356            ParallelOperation::Group(children) => {
12357                let child_base = base_sequence
12358                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12359                    .ok_or(Error::TimerDurationOverflow)?;
12360                for mut descriptor in parallel_descriptors(children, child_base)? {
12361                    let outer_index = cursor + descriptor.offset;
12362                    descriptor.group_path.insert(
12363                        0,
12364                        parallel_group_entry(base_sequence, size, outer_index, kind),
12365                    );
12366                    descriptor.member_path.insert(0, index);
12367                    descriptor.offset = outer_index;
12368                    descriptors.push(descriptor);
12369                }
12370                cursor = descriptors.len();
12371            }
12372            operation => {
12373                descriptors.push(ParallelDescriptor {
12374                    operation,
12375                    offset: cursor,
12376                    member_path: vec![index],
12377                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
12378                });
12379                cursor += 1;
12380            }
12381        }
12382    }
12383    Ok(descriptors)
12384}
12385
12386enum ParallelLeafCall {
12387    Activity(ActivityCall),
12388    ChildWorkflow(ChildWorkflowCall),
12389    Timer(TimerCall),
12390    Signal(SignalCall),
12391    Condition(ConditionWaitCall),
12392}
12393
12394fn parallel_leaf_call(
12395    ctx: &WorkflowContext,
12396    operation: ParallelOperation,
12397    parallel_group_path: Vec<ParallelGroupMetadata>,
12398) -> ParallelLeafCall {
12399    match operation {
12400        ParallelOperation::Activity {
12401            activity_type,
12402            options,
12403            arguments,
12404        } => ParallelLeafCall::Activity(ActivityCall {
12405            ctx: ctx.clone(),
12406            activity_type,
12407            options,
12408            worker_session: None,
12409            args: Some(arguments),
12410            scheduled: false,
12411            local: false,
12412            local_result: None,
12413            parallel_group_path,
12414        }),
12415        ParallelOperation::ChildWorkflow {
12416            workflow_type,
12417            options,
12418            arguments,
12419        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
12420            ctx: ctx.clone(),
12421            workflow_type,
12422            options,
12423            args: Some(arguments),
12424            scheduled: false,
12425            matched_pending: false,
12426            parallel_group_path,
12427        }),
12428        ParallelOperation::Timer(duration) => {
12429            let delay_seconds = duration
12430                .as_secs()
12431                .checked_add(u64::from(duration.subsec_nanos() > 0));
12432            ParallelLeafCall::Timer(TimerCall {
12433                ctx: ctx.clone(),
12434                delay_seconds,
12435                scheduled: false,
12436                matched_pending: false,
12437                parallel_group_path,
12438            })
12439        }
12440        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
12441            ctx: ctx.clone(),
12442            signal_name,
12443            runtime_reserved_allowed: false,
12444            opened_wait: false,
12445            matched_pending: false,
12446            parallel_group_path,
12447        }),
12448        ParallelOperation::Condition { options, predicate } => {
12449            ParallelLeafCall::Condition(ConditionWaitCall {
12450                ctx: ctx.clone(),
12451                options,
12452                predicate,
12453                occurrence_id: None,
12454                opened_wait: false,
12455                parallel_group_path,
12456            })
12457        }
12458        ParallelOperation::Group(_) => {
12459            unreachable!("parallel descriptors contain only durable leaves")
12460        }
12461    }
12462}
12463
12464impl ParallelLeafCall {
12465    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
12466        match self {
12467            Self::Activity(call) => Pin::new(call)
12468                .poll_avro_value(cx)
12469                .map_ok(ParallelAvroResult::Activity),
12470            Self::ChildWorkflow(call) => Pin::new(call)
12471                .poll_avro_value(cx)
12472                .map_ok(ParallelAvroResult::ChildWorkflow),
12473            Self::Timer(call) => Pin::new(call)
12474                .poll(cx)
12475                .map_ok(|()| ParallelAvroResult::Timer),
12476            Self::Signal(call) => Pin::new(call)
12477                .poll_avro_value(cx)
12478                .map_ok(ParallelAvroResult::Signal),
12479            Self::Condition(call) => Pin::new(call)
12480                .poll(cx)
12481                .map_ok(ParallelAvroResult::Condition),
12482        }
12483    }
12484}
12485
12486struct ParallelLeaf {
12487    call: ParallelLeafCall,
12488    sequence: u64,
12489    member_path: Vec<usize>,
12490    group_path: Vec<ParallelGroupMetadata>,
12491    result: Option<ParallelAvroResult>,
12492}
12493
12494/// Future returned by [`WorkflowContext::parallel`].
12495pub struct ParallelCall {
12496    ctx: WorkflowContext,
12497    operations: Option<Vec<ParallelOperation>>,
12498    shape: Option<ParallelShape>,
12499    leaves: Vec<ParallelLeaf>,
12500    pending_scope_delivery: bool,
12501    worker_session: Option<WorkerSessionOptions>,
12502}
12503
12504impl ParallelCall {
12505    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
12506        Self {
12507            ctx,
12508            operations: Some(operations),
12509            shape: None,
12510            leaves: Vec::new(),
12511            pending_scope_delivery: false,
12512            worker_session: None,
12513        }
12514    }
12515
12516    fn initialize(&mut self) -> Result<()> {
12517        if let Some(session) = &self.worker_session {
12518            session.to_wire()?;
12519        }
12520        let operations = self.operations.take().unwrap_or_default();
12521        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
12522        self.shape = Some(parallel_shape(&operations));
12523        if operations.is_empty() {
12524            return Ok(());
12525        }
12526
12527        let base_sequence = {
12528            let state = self
12529                .ctx
12530                .state
12531                .lock()
12532                .map_err(|_| Error::WorkflowStatePoisoned)?;
12533            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12534                recorded.sequence()
12535            } else {
12536                let last = state
12537                    .recorded_commands
12538                    .last()
12539                    .map(RecordedCommand::sequence)
12540                    .unwrap_or(0);
12541                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12542                    .and_then(|sequence| sequence.checked_add(1))
12543                    .ok_or_else(|| {
12544                        Error::InvalidParallelGroup(ParallelGroupError {
12545                            reason: "sequence_overflow",
12546                            member_path: Vec::new(),
12547                            message: "parallel group sequence identity overflowed u64".to_string(),
12548                        })
12549                    })?
12550            }
12551        };
12552
12553        let descriptors = parallel_descriptors(operations, base_sequence)?;
12554        {
12555            let mut state = self
12556                .ctx
12557                .state
12558                .lock()
12559                .map_err(|_| Error::WorkflowStatePoisoned)?;
12560            let cursor = state.command_cursor;
12561            self.ctx.validate_scope_membership(&mut state, cursor)?;
12562            if state.prepare_parallel_scope_cancellation(&descriptors)? {
12563                self.pending_scope_delivery = true;
12564                return Ok(());
12565            }
12566            state.expand_cancellation_group(&descriptors)?;
12567            state.prepare_group_cancellation(&descriptors)?;
12568        }
12569        self.leaves = descriptors
12570            .into_iter()
12571            .map(|descriptor| {
12572                let mut call = parallel_leaf_call(
12573                    &self.ctx,
12574                    descriptor.operation,
12575                    descriptor.group_path.clone(),
12576                );
12577                if let (Some(session), ParallelLeafCall::Activity(activity)) =
12578                    (&self.worker_session, &mut call)
12579                {
12580                    activity.worker_session = Some(session.clone());
12581                }
12582                ParallelLeaf {
12583                    call,
12584                    sequence: base_sequence + descriptor.offset as u64,
12585                    member_path: descriptor.member_path,
12586                    group_path: descriptor.group_path,
12587                    result: None,
12588                }
12589            })
12590            .collect();
12591        Ok(())
12592    }
12593
12594    fn poll_avro_value(
12595        mut self: Pin<&mut Self>,
12596        cx: &mut TaskContext<'_>,
12597    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
12598        if self.operations.is_some() {
12599            if let Err(error) = self.initialize() {
12600                return Poll::Ready(Err(error));
12601            }
12602        }
12603        if self.pending_scope_delivery {
12604            return Poll::Pending;
12605        }
12606        if self.leaves.is_empty() {
12607            return Poll::Ready(Ok(Vec::new()));
12608        }
12609
12610        let mut failures = Vec::new();
12611        let mut pending = false;
12612        for (index, leaf) in self.leaves.iter_mut().enumerate() {
12613            if leaf.result.is_some() {
12614                continue;
12615            }
12616            match leaf.call.poll_avro_value(cx) {
12617                Poll::Ready(Ok(result)) => leaf.result = Some(result),
12618                Poll::Ready(Err(error)) => failures.push((index, error)),
12619                Poll::Pending => pending = true,
12620            }
12621        }
12622
12623        if !failures.is_empty() {
12624            if let Some(position) = failures
12625                .iter()
12626                .position(|(_, error)| workflow_task_integrity_error(error))
12627            {
12628                return Poll::Ready(Err(failures.remove(position).1));
12629            }
12630            if self
12631                .ctx
12632                .state
12633                .lock()
12634                .map_err(|_| Error::WorkflowStatePoisoned)?
12635                .cancellation_delivery_intent
12636                .is_some()
12637            {
12638                return Poll::Pending;
12639            }
12640            if let Some(position) = failures
12641                .iter()
12642                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
12643            {
12644                return Poll::Ready(Err(failures.remove(position).1));
12645            }
12646            failures.sort_by_key(|(index, _)| *index);
12647            let (failed_index, cause) = failures.remove(0);
12648            let failed = &self.leaves[failed_index];
12649            let completed = self
12650                .leaves
12651                .iter()
12652                .filter_map(|leaf| {
12653                    leaf.result
12654                        .clone()
12655                        .and_then(|result| result.into_json_result().ok())
12656                        .map(|result| ParallelCompletion {
12657                            member_path: leaf.member_path.clone(),
12658                            result,
12659                        })
12660                })
12661                .collect();
12662            let group_id = failed
12663                .group_path
12664                .first()
12665                .map(|entry| entry.parallel_group_id.clone())
12666                .unwrap_or_default();
12667            let sequences = self
12668                .leaves
12669                .iter()
12670                .map(|leaf| leaf.sequence)
12671                .collect::<Vec<_>>();
12672            self.ctx
12673                .state
12674                .lock()
12675                .map_err(|_| Error::WorkflowStatePoisoned)?
12676                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12677            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12678                group_id,
12679                member_path: failed.member_path.clone(),
12680                group_path: failed.group_path.clone(),
12681                completed,
12682                cause: Box::new(cause),
12683            })));
12684        }
12685        if pending
12686            || self
12687                .ctx
12688                .state
12689                .lock()
12690                .map_err(|_| Error::WorkflowStatePoisoned)?
12691                .cancellation_delivery_intent
12692                .is_some()
12693        {
12694            return Poll::Pending;
12695        }
12696
12697        let mut flat_results = self
12698            .leaves
12699            .iter_mut()
12700            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12701            .collect::<Vec<_>>()
12702            .into_iter();
12703        let results = parallel_results_for_shape(
12704            self.shape.as_ref().expect("initialized parallel shape"),
12705            &mut flat_results,
12706        );
12707        let sequences = self
12708            .leaves
12709            .iter()
12710            .map(|leaf| leaf.sequence)
12711            .collect::<Vec<_>>();
12712        self.ctx
12713            .state
12714            .lock()
12715            .map_err(|_| Error::WorkflowStatePoisoned)?
12716            .advance_cancellation_sequences(&sequences, None);
12717        Poll::Ready(Ok(match results {
12718            ParallelAvroResult::Group(results) => results,
12719            ParallelAvroResult::Activity(_)
12720            | ParallelAvroResult::ChildWorkflow(_)
12721            | ParallelAvroResult::Timer
12722            | ParallelAvroResult::Signal(_)
12723            | ParallelAvroResult::Condition(_) => {
12724                unreachable!("root parallel shape is a group")
12725            }
12726        }))
12727    }
12728}
12729
12730fn parallel_results_for_shape(
12731    shape: &ParallelShape,
12732    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12733) -> ParallelAvroResult {
12734    match shape {
12735        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12736        ParallelShape::Group(children) => ParallelAvroResult::Group(
12737            children
12738                .iter()
12739                .map(|child| parallel_results_for_shape(child, flat_results))
12740                .collect(),
12741        ),
12742    }
12743}
12744
12745impl Future for ParallelCall {
12746    type Output = Result<Vec<ParallelResult>>;
12747
12748    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12749        self.poll_avro_value(cx)
12750            .map_ok(|results| {
12751                results
12752                    .into_iter()
12753                    .map(ParallelAvroResult::into_json_result)
12754                    .collect::<Result<Vec<_>>>()
12755            })
12756            .map_ok(|result| result)
12757            .flatten_result()
12758    }
12759}
12760
12761#[derive(Clone, Debug)]
12762struct SelectionMemberPlan {
12763    key: SelectionKey,
12764    index: usize,
12765    base_sequence: u64,
12766    size: usize,
12767    kind: String,
12768    shape: ParallelShape,
12769    leaf_start: usize,
12770}
12771
12772fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12773    match operation {
12774        ParallelOperation::Activity { .. } => "activity",
12775        ParallelOperation::ChildWorkflow { .. } => "child",
12776        ParallelOperation::Timer(_) => "timer",
12777        ParallelOperation::Signal(_) => "signal",
12778        ParallelOperation::Condition { .. } => "condition",
12779        ParallelOperation::Group(_) => "group",
12780    }
12781}
12782
12783fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12784    match operation {
12785        ParallelOperation::Group(children) => parallel_shape(children),
12786        _ => ParallelShape::Leaf,
12787    }
12788}
12789
12790fn selection_descriptors(
12791    operations: Vec<(SelectionKey, ParallelOperation)>,
12792    base_sequence: u64,
12793) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12794    if operations.is_empty() {
12795        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12796            reason: "selection_empty",
12797            member_path: Vec::new(),
12798            message: "durable selection requires at least one operation".to_string(),
12799        }));
12800    }
12801    let operation_refs = operations
12802        .iter()
12803        .map(|(_, operation)| operation)
12804        .collect::<Vec<_>>();
12805    let total_size = operation_refs
12806        .iter()
12807        .map(|operation| match operation {
12808            ParallelOperation::Group(children) => parallel_leaf_count(children),
12809            _ => 1,
12810        })
12811        .sum::<usize>();
12812    if total_size > MAX_PARALLEL_OPERATIONS {
12813        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12814            reason: "fan_out_limit_exceeded",
12815            member_path: Vec::new(),
12816            message: format!(
12817                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12818            ),
12819        }));
12820    }
12821    let group_kind = {
12822        let mut kind = None;
12823        for operation in &operation_refs {
12824            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
12825            match kind {
12826                None => kind = Some(operation_kind),
12827                Some(current) if current == operation_kind => {}
12828                Some(_) => {
12829                    kind = Some("mixed");
12830                    break;
12831                }
12832            }
12833        }
12834        kind.unwrap_or("mixed")
12835    };
12836
12837    let mut descriptors = Vec::with_capacity(total_size);
12838    let mut members = Vec::with_capacity(operations.len());
12839    let mut cursor = 0usize;
12840    let mut seen_keys: Vec<SelectionKey> = Vec::new();
12841    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
12842        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
12843            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12844                reason: "selection_key_invalid",
12845                member_path: vec![member_index],
12846                message: "selection member keys must be non-empty strings or non-negative integers"
12847                    .to_string(),
12848            }));
12849        }
12850        if seen_keys.contains(&key) {
12851            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12852                reason: "selection_key_duplicate",
12853                member_path: vec![member_index],
12854                message: format!("selection member key {key:?} is duplicated"),
12855            }));
12856        }
12857        seen_keys.push(key.clone());
12858        let member_size = match &operation {
12859            ParallelOperation::Group(children) => parallel_leaf_count(children),
12860            _ => 1,
12861        };
12862        if member_size == 0 {
12863            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12864                reason: "selection_member_empty",
12865                member_path: vec![member_index],
12866                message: "a selection member must contain at least one durable leaf".to_string(),
12867            }));
12868        }
12869        let member_base = base_sequence
12870            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12871            .ok_or(Error::TimerDurationOverflow)?;
12872        let member_kind = selection_operation_kind(&operation).to_string();
12873        let member_shape = selection_operation_shape(&operation);
12874        let leaf_start = descriptors.len();
12875        match operation {
12876            ParallelOperation::Group(children) => {
12877                validate_parallel_operations(&children, &mut vec![member_index], false)?;
12878                for mut descriptor in parallel_descriptors(children, member_base)? {
12879                    let flat_index = cursor + descriptor.offset;
12880                    descriptor.group_path.insert(
12881                        0,
12882                        selection_group_entry(
12883                            base_sequence,
12884                            total_size,
12885                            flat_index,
12886                            group_kind,
12887                            &SelectionMemberMetadata {
12888                                key: key.clone(),
12889                                index: member_index,
12890                                base_sequence: member_base,
12891                                size: member_size,
12892                                kind: member_kind.clone(),
12893                            },
12894                        ),
12895                    );
12896                    descriptor.member_path.insert(0, member_index);
12897                    descriptor.offset = flat_index;
12898                    descriptors.push(descriptor);
12899                }
12900            }
12901            operation => {
12902                validate_parallel_operations(
12903                    std::slice::from_ref(&operation),
12904                    &mut Vec::new(),
12905                    true,
12906                )?;
12907                descriptors.push(ParallelDescriptor {
12908                    operation,
12909                    offset: cursor,
12910                    member_path: vec![member_index],
12911                    group_path: vec![selection_group_entry(
12912                        base_sequence,
12913                        total_size,
12914                        cursor,
12915                        group_kind,
12916                        &SelectionMemberMetadata {
12917                            key: key.clone(),
12918                            index: member_index,
12919                            base_sequence: member_base,
12920                            size: member_size,
12921                            kind: member_kind.clone(),
12922                        },
12923                    )],
12924                });
12925            }
12926        }
12927        members.push(SelectionMemberPlan {
12928            key,
12929            index: member_index,
12930            base_sequence: member_base,
12931            size: member_size,
12932            kind: member_kind,
12933            shape: member_shape,
12934            leaf_start,
12935        });
12936        cursor += member_size;
12937    }
12938    Ok((descriptors, members))
12939}
12940
12941struct SelectionLeaf {
12942    call: ParallelLeafCall,
12943    outcome: Option<Result<ParallelAvroResult>>,
12944}
12945
12946/// Stable reference to one member of a durable selection group.
12947#[derive(Clone)]
12948pub struct DurableOperationHandle {
12949    ctx: WorkflowContext,
12950    pub key: SelectionKey,
12951    pub index: usize,
12952    pub kind: String,
12953    pub identity: String,
12954    pub base_sequence: u64,
12955    pub size: usize,
12956    pub selection_group_id: String,
12957    shape: ParallelShape,
12958}
12959
12960impl std::fmt::Debug for DurableOperationHandle {
12961    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12962        formatter
12963            .debug_struct("DurableOperationHandle")
12964            .field("key", &self.key)
12965            .field("index", &self.index)
12966            .field("kind", &self.kind)
12967            .field("identity", &self.identity)
12968            .field("base_sequence", &self.base_sequence)
12969            .field("size", &self.size)
12970            .field("selection_group_id", &self.selection_group_id)
12971            .finish()
12972    }
12973}
12974
12975impl DurableOperationHandle {
12976    /// Await this member after another member has already won the selection.
12977    pub fn await_result(&self) -> DurableOperationAwaitCall {
12978        DurableOperationAwaitCall {
12979            handle: self.clone(),
12980        }
12981    }
12982
12983    /// Request cancellation without affecting siblings. The future resolves
12984    /// to unit; only `SelectionOperationCancelled` history proves cancellation
12985    /// beat a concurrently committed terminal result.
12986    pub fn cancel(&self) -> CancelDurableOperationCall {
12987        CancelDurableOperationCall {
12988            handle: self.clone(),
12989            emitted: false,
12990        }
12991    }
12992}
12993
12994/// The one winner committed for a durable selection group.
12995#[derive(Debug)]
12996pub struct SelectionResult {
12997    pub key: SelectionKey,
12998    pub index: usize,
12999    pub kind: String,
13000    pub identity: String,
13001    pub value: Option<ParallelResult>,
13002    pub failure: Option<Error>,
13003    pub winner: DurableOperationHandle,
13004    pub handles: Vec<DurableOperationHandle>,
13005}
13006
13007impl SelectionResult {
13008    pub fn succeeded(&self) -> bool {
13009        self.failure.is_none()
13010    }
13011
13012    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13013        self.handles.iter().find(|handle| &handle.key == key)
13014    }
13015
13016    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13017        self.handles
13018            .iter()
13019            .filter(|handle| handle.index != self.index)
13020            .collect()
13021    }
13022
13023    pub fn into_result(self) -> Result<ParallelResult> {
13024        match (self.value, self.failure) {
13025            (Some(value), None) => Ok(value),
13026            (_, Some(error)) => Err(error),
13027            _ => Err(Error::WorkerLoop(
13028                "selection result contained neither a value nor a failure".to_string(),
13029            )),
13030        }
13031    }
13032}
13033
13034/// Future returned by [`WorkflowContext::select`].
13035pub struct SelectCall {
13036    ctx: WorkflowContext,
13037    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13038    members: Vec<SelectionMemberPlan>,
13039    leaves: Vec<SelectionLeaf>,
13040    group_id: Option<String>,
13041}
13042
13043impl SelectCall {
13044    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13045        Self {
13046            ctx,
13047            operations: Some(operations),
13048            members: Vec::new(),
13049            leaves: Vec::new(),
13050            group_id: None,
13051        }
13052    }
13053
13054    fn initialize(&mut self) -> Result<()> {
13055        let operations = self.operations.take().unwrap_or_default();
13056        let base_sequence = {
13057            let state = self
13058                .ctx
13059                .state
13060                .lock()
13061                .map_err(|_| Error::WorkflowStatePoisoned)?;
13062            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
13063                state.recorded_commands.get(state.command_cursor)
13064            {
13065                *sequence
13066            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
13067            {
13068                marker.selection_group_base_sequence
13069            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13070                recorded.sequence()
13071            } else {
13072                let last = state
13073                    .recorded_commands
13074                    .last()
13075                    .map(RecordedCommand::sequence)
13076                    .unwrap_or(0);
13077                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13078                    .and_then(|sequence| sequence.checked_add(1))
13079                    .ok_or(Error::TimerDurationOverflow)?
13080            }
13081        };
13082        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
13083        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
13084        {
13085            let mut state = self
13086                .ctx
13087                .state
13088                .lock()
13089                .map_err(|_| Error::WorkflowStatePoisoned)?;
13090            state.expand_cancellation_group(&descriptors)?;
13091            state.prepare_group_cancellation(&descriptors)?;
13092        }
13093        self.leaves = descriptors
13094            .into_iter()
13095            .map(|descriptor| SelectionLeaf {
13096                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
13097                outcome: None,
13098            })
13099            .collect();
13100        self.members = members;
13101        self.group_id = Some(group_id);
13102        Ok(())
13103    }
13104}
13105
13106impl Future for SelectCall {
13107    type Output = Result<SelectionResult>;
13108
13109    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13110        if self.operations.is_some() {
13111            if let Err(error) = self.initialize() {
13112                return Poll::Ready(Err(error));
13113            }
13114        }
13115
13116        for leaf in &mut self.leaves {
13117            if leaf.outcome.is_some() {
13118                continue;
13119            }
13120            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
13121                if outcome
13122                    .as_ref()
13123                    .err()
13124                    .is_some_and(workflow_task_integrity_error)
13125                {
13126                    return Poll::Ready(outcome.map(|_| unreachable!()));
13127                }
13128                leaf.outcome = Some(outcome);
13129            }
13130        }
13131
13132        if self
13133            .ctx
13134            .state
13135            .lock()
13136            .map_err(|_| Error::WorkflowStatePoisoned)?
13137            .cancellation_delivery_intent
13138            .is_some()
13139        {
13140            return Poll::Pending;
13141        }
13142
13143        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
13144            matches!(
13145                leaf.outcome,
13146                Some(Err(Error::CooperativeCancellationRequested(_)))
13147            )
13148        }) {
13149            return Poll::Ready(
13150                leaf.outcome
13151                    .take()
13152                    .expect("matched cancellation")
13153                    .map(|_| unreachable!()),
13154            );
13155        }
13156
13157        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
13158        let selection_member_range = self
13159            .members
13160            .first()
13161            .map(|member| member.base_sequence)
13162            .zip(self.leaves.len().try_into().ok())
13163            .map(|(base_sequence, size): (u64, u64)| {
13164                base_sequence..base_sequence.saturating_add(size)
13165            });
13166        let marker = {
13167            let mut state = match self.ctx.state.lock() {
13168                Ok(state) => state,
13169                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13170            };
13171            let marker = state
13172                .selection_markers
13173                .get(state.selection_marker_cursor)
13174                .cloned();
13175            if marker.is_none()
13176                && all_members_terminal
13177                && selection_member_range.as_ref().is_some_and(|member_range| {
13178                    state
13179                        .recorded_commands
13180                        .iter()
13181                        .any(|command| member_range.contains(&command.sequence()))
13182                })
13183            {
13184                // Terminal member history can be committed before the server's
13185                // SelectionResolved marker becomes visible to this task. That
13186                // marker is the durable barrier the selection is still waiting
13187                // on, so an otherwise commandless replay remains legitimately
13188                // pending instead of failing as an untracked yield.
13189                state.matched_recorded_pending = true;
13190            }
13191            marker
13192        };
13193        let Some(marker) = marker else {
13194            return Poll::Pending;
13195        };
13196        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
13197            || marker.selection_group_size != self.leaves.len()
13198            || self.members.first().map(|member| member.base_sequence)
13199                != Some(marker.selection_group_base_sequence)
13200        {
13201            return Poll::Ready(Err(invalid_recorded_history(
13202                "selection_group_shape_mismatch",
13203                marker.selection_group_base_sequence,
13204                self.group_id
13205                    .as_deref()
13206                    .unwrap_or("initialized selection group"),
13207                &marker.selection_group_id,
13208                "recorded selection group differs from current workflow code",
13209            )));
13210        }
13211        let Some(member_position) = self.members.iter().position(|member| {
13212            member.key == marker.member_key
13213                && member.index == marker.member_index
13214                && member.base_sequence == marker.member_base_sequence
13215                && member.size == marker.member_size
13216                && member.kind == marker.operation_kind
13217        }) else {
13218            return Poll::Ready(Err(invalid_recorded_history(
13219                "selection_member_shape_mismatch",
13220                marker.member_base_sequence,
13221                "winner member matching current workflow code",
13222                &format!("{:?}", marker.member_key),
13223                "recorded selection winner differs from the authored member identity",
13224            )));
13225        };
13226        let member = self.members[member_position].clone();
13227        let (handles, resolution_sequence) = {
13228            let mut state = match self.ctx.state.lock() {
13229                Ok(state) => state,
13230                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13231            };
13232            let identities = self
13233                .members
13234                .iter()
13235                .map(|candidate| {
13236                    selection_operation_identity(
13237                        &state,
13238                        &candidate.kind,
13239                        candidate.base_sequence,
13240                        candidate.size,
13241                    )
13242                })
13243                .collect::<Vec<_>>();
13244            if let Some((position, missing)) = identities
13245                .iter()
13246                .enumerate()
13247                .find(|(_, identity)| identity.is_empty())
13248                .map(|(position, identity)| (position, identity.clone()))
13249            {
13250                let candidate = &self.members[position];
13251                return Poll::Ready(Err(invalid_recorded_history(
13252                    "selection_operation_identity_missing",
13253                    candidate.base_sequence,
13254                    &format!(
13255                        "durable {} resource identity from scheduled/open history",
13256                        candidate.kind
13257                    ),
13258                    &missing,
13259                    "selection member history is missing its canonical durable identity",
13260                )));
13261            }
13262            let expected_winner_identity = &identities[member_position];
13263            let resolution_sequence = match validated_selection_resolution_sequence(
13264                &state,
13265                &marker,
13266                &member,
13267                expected_winner_identity,
13268            ) {
13269                Ok(sequence) => sequence,
13270                Err(error) => return Poll::Ready(Err(error)),
13271            };
13272            let handles = self
13273                .members
13274                .iter()
13275                .zip(identities)
13276                .map(|(member, identity)| DurableOperationHandle {
13277                    ctx: self.ctx.clone(),
13278                    key: member.key.clone(),
13279                    index: member.index,
13280                    kind: member.kind.clone(),
13281                    identity,
13282                    base_sequence: member.base_sequence,
13283                    size: member.size,
13284                    selection_group_id: marker.selection_group_id.clone(),
13285                    shape: member.shape.clone(),
13286                })
13287                .collect::<Vec<_>>();
13288            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
13289                return Poll::Ready(Err(error));
13290            }
13291            state.selection_marker_cursor += 1;
13292            (handles, resolution_sequence)
13293        };
13294
13295        let mut winner_failure = None;
13296        let mut flat_results = Vec::with_capacity(member.size);
13297        if marker.outcome == "failed" {
13298            let resolution_offset = match resolution_sequence
13299                .checked_sub(member.base_sequence)
13300                .and_then(|offset| usize::try_from(offset).ok())
13301            {
13302                Some(offset) if offset < member.size => offset,
13303                _ => {
13304                    return Poll::Ready(Err(invalid_recorded_history(
13305                        "selection_resolution_event_mismatch",
13306                        member.base_sequence,
13307                        "failure event within selected member bounds",
13308                        &resolution_sequence.to_string(),
13309                        "selection failure event is outside the authored member",
13310                    )))
13311                }
13312            };
13313            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
13314            match leaf.outcome.take() {
13315                Some(Err(error)) => winner_failure = Some(error),
13316                _ => {
13317                    return Poll::Ready(Err(invalid_recorded_history(
13318                        "selection_winner_outcome_mismatch",
13319                        member.base_sequence,
13320                        "exact failed terminal history referenced by SelectionResolved",
13321                        "missing or successful resolution event",
13322                        "selection winner marker disagrees with terminal operation history",
13323                    )))
13324                }
13325            }
13326        } else {
13327            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
13328                match leaf.outcome.take() {
13329                    Some(Ok(result)) => flat_results.push(result),
13330                    Some(Err(_)) => {
13331                        return Poll::Ready(Err(invalid_recorded_history(
13332                            "selection_winner_outcome_mismatch",
13333                            member.base_sequence,
13334                            "fully completed nested selection member",
13335                            "failed durable leaf",
13336                            "completed selection winner contains a failed leaf",
13337                        )))
13338                    }
13339                    None => {
13340                        return Poll::Ready(Err(invalid_recorded_history(
13341                            "selection_winner_unresolved",
13342                            member.base_sequence,
13343                            "terminal history for every completed winner leaf",
13344                            "pending member history",
13345                            "completed SelectionResolved member has an unfinished durable barrier",
13346                        )))
13347                    }
13348                }
13349            }
13350        }
13351        let value = if winner_failure.is_none() {
13352            let mut flat_results = flat_results.into_iter();
13353            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
13354            match value.into_json_result() {
13355                Ok(value) => Some(value),
13356                Err(error) => return Poll::Ready(Err(error)),
13357            }
13358        } else {
13359            None
13360        };
13361        let winner = handles[member_position].clone();
13362        self.ctx
13363            .state
13364            .lock()
13365            .map_err(|_| Error::WorkflowStatePoisoned)?
13366            .advance_cancellation_selection(&marker.selection_group_id);
13367        Poll::Ready(Ok(SelectionResult {
13368            key: winner.key.clone(),
13369            index: winner.index,
13370            kind: winner.kind.clone(),
13371            identity: winner.identity.clone(),
13372            value,
13373            failure: winner_failure,
13374            winner,
13375            handles,
13376        }))
13377    }
13378}
13379
13380fn selection_operation_identity(
13381    state: &WorkflowState,
13382    kind: &str,
13383    base_sequence: u64,
13384    size: usize,
13385) -> String {
13386    if kind == "group" {
13387        return format!("group:{base_sequence}:{size}");
13388    }
13389    let fields: &[&str] = match kind {
13390        "activity" => &["activity_execution_id"],
13391        "child" => &["child_workflow_run_id"],
13392        "timer" => &["timer_id"],
13393        "signal" => &["signal_wait_id"],
13394        "condition" => &["condition_wait_id"],
13395        _ => &[],
13396    };
13397    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
13398        for event in state
13399            .history_events
13400            .iter()
13401            .filter(|event| durable_event_sequence(event) == Some(sequence))
13402        {
13403            for field in fields {
13404                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
13405                    if !identity.is_empty() {
13406                        return identity.to_string();
13407                    }
13408                }
13409            }
13410        }
13411    }
13412    String::new()
13413}
13414
13415fn validated_selection_resolution_sequence(
13416    state: &WorkflowState,
13417    marker: &SelectionMarker,
13418    member: &SelectionMemberPlan,
13419    expected_identity: &str,
13420) -> Result<u64> {
13421    if expected_identity.is_empty() {
13422        return Err(invalid_recorded_history(
13423            "selection_operation_identity_missing",
13424            member.base_sequence,
13425            &format!(
13426                "durable {} resource identity from scheduled/open history",
13427                member.kind
13428            ),
13429            "missing operation identity",
13430            "selection member history is missing its canonical durable identity",
13431        ));
13432    }
13433    if marker.operation_identity != expected_identity {
13434        return Err(invalid_recorded_history(
13435            "selection_operation_identity_mismatch",
13436            member.base_sequence,
13437            expected_identity,
13438            &marker.operation_identity,
13439            "selection winner identity does not match durable scheduled/open history",
13440        ));
13441    }
13442
13443    let failure_types = [
13444        "ActivityFailed",
13445        "ActivityCancelled",
13446        "ActivityTimedOut",
13447        "ChildRunFailed",
13448        "ChildRunCancelled",
13449        "ChildRunTerminated",
13450    ];
13451    let success_types = [
13452        "ActivityCompleted",
13453        "ChildRunCompleted",
13454        "TimerFired",
13455        "SignalApplied",
13456        "ConditionWaitSatisfied",
13457        "ConditionWaitTimedOut",
13458    ];
13459    let terminal_types: &[&str] = if marker.outcome == "failed" {
13460        &failure_types
13461    } else {
13462        &success_types
13463    };
13464    let mut candidates = Vec::new();
13465    let member_commands = (member.base_sequence
13466        ..member.base_sequence.saturating_add(member.size as u64))
13467        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
13468        .map(|command| (command.sequence(), command))
13469        .collect::<BTreeMap<_, _>>();
13470    let mut resolved_conditions = BTreeSet::new();
13471    for event in state.history_events.iter() {
13472        let Some(sequence) = durable_event_sequence(event) else {
13473            continue;
13474        };
13475        let Some(command) = member_commands.get(&sequence) else {
13476            continue;
13477        };
13478        if !terminal_types.contains(&event.event_type.as_str()) {
13479            continue;
13480        }
13481        if matches!(command, RecordedCommand::ConditionWait { .. }) {
13482            if !matches!(
13483                event.event_type.as_str(),
13484                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
13485            ) && !(event.event_type == "TimerFired"
13486                && event.payload.get("timer_kind").and_then(Value::as_str)
13487                    == Some("condition_timeout"))
13488            {
13489                continue;
13490            }
13491            if !resolved_conditions.insert(sequence) {
13492                continue;
13493            }
13494        }
13495        let event_id = event
13496            .raw
13497            .get("id")
13498            .or_else(|| event.raw.get("event_id"))
13499            .and_then(Value::as_str)
13500            .filter(|value| !value.is_empty())
13501            .ok_or_else(|| {
13502                invalid_recorded_history(
13503                    "selection_resolution_event_id_missing",
13504                    member.base_sequence,
13505                    "terminal selection history with a durable event id",
13506                    &event.payload.to_string(),
13507                    "selection terminal history cannot be bound to its winner marker",
13508                )
13509            })?;
13510        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
13511    }
13512    let resolution = if marker.outcome == "failed" {
13513        candidates.first()
13514    } else {
13515        candidates.last()
13516    };
13517    let Some((event_id, event_type, sequence)) = resolution else {
13518        return Err(invalid_recorded_history(
13519            "selection_resolution_event_missing",
13520            member.base_sequence,
13521            "terminal history for the selected member",
13522            &format!("{:?}", marker.member_key),
13523            "selection winner marker has no matching durable terminal event",
13524        ));
13525    };
13526    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
13527        return Err(invalid_recorded_history(
13528            "selection_resolution_event_mismatch",
13529            member.base_sequence,
13530            &format!("{event_type}:{event_id}"),
13531            &format!(
13532                "{}:{}",
13533                marker.resolution_event_type, marker.resolution_event_id
13534            ),
13535            "selection winner marker does not reference the event that made its member terminal",
13536        ));
13537    }
13538    Ok(*sequence)
13539}
13540
13541fn selection_member_recorded_command(
13542    state: &WorkflowState,
13543    authored_sequence: u64,
13544) -> Option<&RecordedCommand> {
13545    let original = state
13546        .recorded_commands
13547        .iter()
13548        .find(|command| command.sequence() == authored_sequence)?;
13549    let RecordedCommand::ConditionWait {
13550        occurrence_id,
13551        parallel_group_path: Some(_),
13552        ..
13553    } = original
13554    else {
13555        return Some(original);
13556    };
13557    // Decoding proves each physical reopen has the same authored identity and
13558    // group path after a satisfied predecessor. Only its latest wait can make
13559    // this logical member terminal.
13560    state
13561        .recorded_commands
13562        .iter()
13563        .filter(|command| {
13564            matches!(command, RecordedCommand::ConditionWait {
13565                occurrence_id: candidate, ..
13566            } if candidate == occurrence_id)
13567        })
13568        .max_by_key(|command| command.sequence())
13569}
13570
13571fn recorded_selection_member_outcome(
13572    state: &WorkflowState,
13573    handle: &DurableOperationHandle,
13574) -> Result<Option<ParallelResult>> {
13575    for event in state.history_events.iter() {
13576        let Some(sequence) = durable_event_sequence(event) else {
13577            continue;
13578        };
13579        if sequence < handle.base_sequence
13580            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
13581            || !matches!(
13582                event.event_type.as_str(),
13583                "ActivityFailed"
13584                    | "ActivityCancelled"
13585                    | "ActivityTimedOut"
13586                    | "ChildRunFailed"
13587                    | "ChildRunCancelled"
13588                    | "ChildRunTerminated"
13589            )
13590        {
13591            continue;
13592        }
13593        let Some(command) = state
13594            .recorded_commands
13595            .iter()
13596            .find(|command| command.sequence() == sequence)
13597        else {
13598            continue;
13599        };
13600        match command {
13601            RecordedCommand::Activity {
13602                outcome: Some(Err(failure)),
13603                ..
13604            } => return Err(Error::ActivityFailed(failure.clone())),
13605            RecordedCommand::ChildWorkflow {
13606                outcome: Some(Err(failure)),
13607                ..
13608            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
13609            _ => {}
13610        }
13611    }
13612
13613    let mut results = Vec::with_capacity(handle.size);
13614    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13615        let Some(command) = selection_member_recorded_command(state, sequence) else {
13616            return Ok(None);
13617        };
13618        let result = match command {
13619            RecordedCommand::Activity { outcome, .. } => match outcome {
13620                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
13621                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
13622                None => return Ok(None),
13623            },
13624            RecordedCommand::Timer { fired, .. } => {
13625                if !fired {
13626                    return Ok(None);
13627                }
13628                ParallelAvroResult::Timer
13629            }
13630            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
13631                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
13632                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
13633                None => return Ok(None),
13634            },
13635            RecordedCommand::SignalWait { value, .. } => match value {
13636                Some(value) => ParallelAvroResult::Signal(value.clone()),
13637                None => return Ok(None),
13638            },
13639            RecordedCommand::ConditionWait { result, .. } => match result {
13640                Some(result) => ParallelAvroResult::Condition(*result),
13641                None => return Ok(None),
13642            },
13643            other => {
13644                return Err(command_mismatch(
13645                    other,
13646                    format!("selected {} member", handle.kind),
13647                ))
13648            }
13649        };
13650        results.push(result);
13651    }
13652    let mut results = results.into_iter();
13653    parallel_results_for_shape(&handle.shape, &mut results)
13654        .into_json_result()
13655        .map(Some)
13656}
13657
13658fn recorded_selection_member_is_terminal(
13659    state: &WorkflowState,
13660    handle: &DurableOperationHandle,
13661) -> bool {
13662    let mut completed = 0usize;
13663    let mut all_completed = true;
13664    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13665        let Some(command) = selection_member_recorded_command(state, sequence) else {
13666            all_completed = false;
13667            continue;
13668        };
13669        let terminal = match command {
13670            RecordedCommand::Activity {
13671                outcome: Some(Err(_)),
13672                ..
13673            }
13674            | RecordedCommand::ChildWorkflow {
13675                outcome: Some(Err(_)),
13676                ..
13677            } => return true,
13678            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13679            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13680            RecordedCommand::Timer { fired, .. } => *fired,
13681            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13682            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13683            RecordedCommand::SearchAttributes { .. }
13684            | RecordedCommand::CancellationScope { .. }
13685            | RecordedCommand::SideEffect { .. }
13686            | RecordedCommand::VersionMarker { .. }
13687            | RecordedCommand::Memo { .. }
13688            | RecordedCommand::CancellationBoundary { .. }
13689            | RecordedCommand::CancellationGroup { .. } => false,
13690        };
13691        if !terminal {
13692            all_completed = false;
13693            continue;
13694        }
13695        completed += 1;
13696    }
13697    all_completed && completed == handle.size
13698}
13699
13700fn selection_cancellation_for_handle(
13701    state: &WorkflowState,
13702    handle: &DurableOperationHandle,
13703) -> Result<bool> {
13704    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13705        recorded.selection_group_id == handle.selection_group_id
13706            && recorded.member_base_sequence == handle.base_sequence
13707    }) else {
13708        return Ok(false);
13709    };
13710    validate_selection_cancellation_marker(marker, handle)?;
13711    Ok(true)
13712}
13713
13714fn validate_selection_cancellations_for_handles(
13715    state: &WorkflowState,
13716    handles: &[DurableOperationHandle],
13717) -> Result<()> {
13718    let Some(group_id) = handles
13719        .first()
13720        .map(|handle| handle.selection_group_id.as_str())
13721    else {
13722        return Ok(());
13723    };
13724    for marker in state
13725        .cancelled_selection_members
13726        .iter()
13727        .filter(|marker| marker.selection_group_id == group_id)
13728    {
13729        let Some(handle) = handles
13730            .iter()
13731            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13732        else {
13733            return Err(invalid_recorded_history(
13734                "selection_cancellation_member_mismatch",
13735                marker.member_base_sequence,
13736                "SelectionOperationCancelled matching an authored selection handle",
13737                &format!("{marker:?}"),
13738                "selection cancellation member base does not name an authored member",
13739            ));
13740        };
13741        validate_selection_cancellation_marker(marker, handle)?;
13742    }
13743    Ok(())
13744}
13745
13746fn validate_selection_cancellation_marker(
13747    marker: &SelectionCancellation,
13748    handle: &DurableOperationHandle,
13749) -> Result<()> {
13750    if marker.selection_group_id != handle.selection_group_id
13751        || marker.member_key != handle.key
13752        || marker.member_index != handle.index
13753        || marker.member_base_sequence != handle.base_sequence
13754        || marker.member_size != handle.size
13755        || marker.operation_kind != handle.kind
13756        || marker.operation_identity != handle.identity
13757    {
13758        return Err(invalid_recorded_history(
13759            "selection_cancellation_member_mismatch",
13760            handle.base_sequence,
13761            "SelectionOperationCancelled matching the authored selection handle",
13762            &format!("{marker:?}"),
13763            "selection cancellation history targets different authored member metadata",
13764        ));
13765    }
13766    Ok(())
13767}
13768
13769/// Future returned by [`DurableOperationHandle::await_result`].
13770pub struct DurableOperationAwaitCall {
13771    handle: DurableOperationHandle,
13772}
13773
13774impl Future for DurableOperationAwaitCall {
13775    type Output = Result<ParallelResult>;
13776
13777    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13778        let mut state = match self.handle.ctx.state.lock() {
13779            Ok(state) => state,
13780            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13781        };
13782        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13783            return Poll::Ready(Err(error));
13784        }
13785        match state.prepare_selection_handle_cancellation(&self.handle) {
13786            Ok(true) => return Poll::Pending,
13787            Ok(false) => {}
13788            Err(error) => return Poll::Ready(Err(error)),
13789        }
13790        match selection_cancellation_for_handle(&state, &self.handle) {
13791            Err(error) => return Poll::Ready(Err(error)),
13792            Ok(false) => {}
13793            Ok(true) => {
13794                state.advance_cancellation_receipt(
13795                    &self.handle.selection_group_id,
13796                    self.handle.base_sequence,
13797                );
13798                return Poll::Ready(Err(Error::DurableOperationCancelled(
13799                    DurableOperationCancelled {
13800                        selection_group_id: self.handle.selection_group_id.clone(),
13801                        member_key: self.handle.key.clone(),
13802                        member_index: self.handle.index,
13803                        operation_kind: self.handle.kind.clone(),
13804                        operation_identity: self.handle.identity.clone(),
13805                    },
13806                )));
13807            }
13808        }
13809        match recorded_selection_member_outcome(&state, &self.handle) {
13810            Ok(Some(result)) => {
13811                state.advance_cancellation_handle(&self.handle, false);
13812                Poll::Ready(Ok(result))
13813            }
13814            Ok(None) => Poll::Pending,
13815            Err(error) => {
13816                if !workflow_task_integrity_error(&error) {
13817                    state.advance_cancellation_handle(&self.handle, true);
13818                }
13819                Poll::Ready(Err(error))
13820            }
13821        }
13822    }
13823}
13824
13825fn validate_selection_delivery_handle(
13826    state: &WorkflowState,
13827    handle: &DurableOperationHandle,
13828) -> Result<()> {
13829    let path = state
13830        .recorded_commands
13831        .iter()
13832        .find(|command| command.sequence() == handle.base_sequence)
13833        .and_then(|command| match command {
13834            RecordedCommand::Activity {
13835                parallel_group_path,
13836                ..
13837            }
13838            | RecordedCommand::ChildWorkflow {
13839                parallel_group_path,
13840                ..
13841            }
13842            | RecordedCommand::Timer {
13843                parallel_group_path,
13844                ..
13845            }
13846            | RecordedCommand::SignalWait {
13847                parallel_group_path,
13848                ..
13849            }
13850            | RecordedCommand::ConditionWait {
13851                parallel_group_path,
13852                ..
13853            } => parallel_group_path.as_ref(),
13854            _ => None,
13855        })
13856        .and_then(|path| path.first());
13857    let matches = path.is_some_and(|entry| {
13858        entry.parallel_group_mode.as_deref() == Some("select")
13859            && entry.parallel_group_id == handle.selection_group_id
13860            && entry.selection_member_key.as_ref() == Some(&handle.key)
13861            && entry.selection_member_index == Some(handle.index)
13862            && entry.selection_member_base_sequence == Some(handle.base_sequence)
13863            && entry.selection_member_size == Some(handle.size)
13864            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
13865    });
13866    if !matches
13867        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
13868            != handle.identity
13869    {
13870        return Err(invalid_recorded_history(
13871            "cooperative_cancellation_call_mismatch",
13872            handle.base_sequence,
13873            "selection handle matching its authored durable identity",
13874            &format!("{handle:?}"),
13875            "selection handle identity or member metadata changed before cancellation replay",
13876        ));
13877    }
13878    Ok(())
13879}
13880
13881/// Future returned by [`DurableOperationHandle::cancel`].
13882pub struct CancelDurableOperationCall {
13883    handle: DurableOperationHandle,
13884    emitted: bool,
13885}
13886
13887impl Future for CancelDurableOperationCall {
13888    type Output = Result<()>;
13889
13890    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13891        let ctx = self.handle.ctx.clone();
13892        let mut state = match ctx.state.lock() {
13893            Ok(state) => state,
13894            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13895        };
13896        match selection_cancellation_for_handle(&state, &self.handle) {
13897            Err(error) => return Poll::Ready(Err(error)),
13898            Ok(true) => {
13899                state.advance_cancellation_receipt(
13900                    &self.handle.selection_group_id,
13901                    self.handle.base_sequence,
13902                );
13903                return Poll::Ready(Ok(()));
13904            }
13905            Ok(false) => {}
13906        }
13907        if recorded_selection_member_is_terminal(&state, &self.handle) {
13908            return Poll::Ready(Ok(()));
13909        }
13910        if !self.emitted {
13911            state.commands.push(json!({
13912                "type": "cancel_selection_operation",
13913                "selection_group_id": self.handle.selection_group_id,
13914                "member_key": self.handle.key,
13915                "member_index": self.handle.index,
13916                "member_base_sequence": self.handle.base_sequence,
13917                "member_size": self.handle.size,
13918                "operation_kind": self.handle.kind,
13919                "operation_identity": self.handle.identity,
13920            }));
13921            self.emitted = true;
13922        }
13923        // The cancellation command is only a request. Do not expose workflow
13924        // state after cancel until committed SelectionOperationCancelled
13925        // history proves that the request won the race with member completion.
13926        Poll::Pending
13927    }
13928}
13929
13930trait PollNestedResultExt<T> {
13931    fn flatten_result(self) -> Poll<Result<T>>;
13932}
13933
13934impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
13935    fn flatten_result(self) -> Poll<Result<T>> {
13936        match self {
13937            Poll::Ready(Ok(result)) => Poll::Ready(result),
13938            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13939            Poll::Pending => Poll::Pending,
13940        }
13941    }
13942}
13943
13944struct SagaCompensation {
13945    activity_type: String,
13946    options: ActivityOptions,
13947    arguments: AvroValue,
13948    registration_order: usize,
13949}
13950
13951/// Workflow-local deterministic saga compensation helper.
13952///
13953/// Register each compensation only after its forward step succeeds. Passing
13954/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
13955/// reverse registration order after any failure, including cooperative
13956/// cancellation. Each compensation is an ordinary durable activity, so replay,
13957/// duplicate delivery, and worker restart use existing history semantics.
13958pub struct Saga {
13959    ctx: WorkflowContext,
13960    compensations: Vec<SagaCompensation>,
13961}
13962
13963impl Saga {
13964    fn new(ctx: WorkflowContext) -> Self {
13965        Self {
13966            ctx,
13967            compensations: Vec::new(),
13968        }
13969    }
13970
13971    pub fn add_compensation<T: Serialize>(
13972        &mut self,
13973        activity_type: impl Into<String>,
13974        args: T,
13975    ) -> Result<&mut Self> {
13976        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
13977    }
13978
13979    pub fn add_compensation_with_options<T: Serialize>(
13980        &mut self,
13981        activity_type: impl Into<String>,
13982        options: ActivityOptions,
13983        args: T,
13984    ) -> Result<&mut Self> {
13985        let activity_type = activity_type.into();
13986        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
13987            return Err(Error::Codec(
13988                "saga compensation activity type must be non-empty without surrounding whitespace"
13989                    .to_string(),
13990            ));
13991        }
13992        options.validate().map_err(Error::InvalidActivityOptions)?;
13993        let arguments = AvroValue::from_serialize(&args)?;
13994        let registration_order = self.compensations.len() + 1;
13995        self.compensations.push(SagaCompensation {
13996            activity_type,
13997            options,
13998            arguments,
13999            registration_order,
14000        });
14001        Ok(self)
14002    }
14003
14004    /// Compensate `initiating_failure` and return the failure that must remain.
14005    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14006        let _shield = match self.ctx.cancellation_shield() {
14007            Ok(shield) => shield,
14008            Err(error) => return error,
14009        };
14010        while let Some(compensation) = self.compensations.pop() {
14011            if let Err(compensation_failure) = self
14012                .ctx
14013                .activity_with_options(
14014                    compensation.activity_type.clone(),
14015                    compensation.options,
14016                    compensation.arguments,
14017                )
14018                .await
14019            {
14020                if workflow_task_integrity_error(&compensation_failure) {
14021                    return compensation_failure;
14022                }
14023                return Error::SagaCompensationFailed(SagaCompensationFailure {
14024                    initiating_failure: Box::new(initiating_failure),
14025                    compensation_failure: Box::new(compensation_failure),
14026                    compensation_activity_type: compensation.activity_type,
14027                    compensation_registration_order: compensation.registration_order,
14028                });
14029            }
14030        }
14031        initiating_failure
14032    }
14033
14034    /// Return a successful forward value or compensate and preserve its failure.
14035    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14036        match outcome {
14037            Ok(value) => Ok(value),
14038            Err(error) => Err(self.compensate(error).await),
14039        }
14040    }
14041}
14042
14043pub struct ActivityCall {
14044    ctx: WorkflowContext,
14045    activity_type: String,
14046    options: ActivityOptions,
14047    worker_session: Option<WorkerSessionOptions>,
14048    args: Option<Result<AvroValue>>,
14049    scheduled: bool,
14050    local: bool,
14051    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
14052    parallel_group_path: Vec<ParallelGroupMetadata>,
14053}
14054
14055impl ActivityCall {
14056    fn poll_avro_value(
14057        mut self: Pin<&mut Self>,
14058        _cx: &mut TaskContext<'_>,
14059    ) -> Poll<Result<AvroValue>> {
14060        let ctx = self.ctx.clone();
14061        let mut state = match ctx.state.lock() {
14062            Ok(state) => state,
14063            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14064        };
14065
14066        if let Some(result) = &self.local_result {
14067            return match result.lock() {
14068                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
14069                    Poll::Ready(result.map_err(Error::ActivityFailed))
14070                }),
14071                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14072            };
14073        }
14074        if self.scheduled {
14075            return Poll::Pending;
14076        }
14077
14078        let options = match self.options.validate() {
14079            Ok(options) => options,
14080            Err(error) => {
14081                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
14082            }
14083        };
14084        if self.local {
14085            if self.worker_session.is_some() {
14086                return Poll::Ready(Err(Error::WorkerLoop(
14087                    "local activities cannot use worker-session routing".into(),
14088                )));
14089            }
14090            if let Err(error) = local_activity::validate(&options) {
14091                return Poll::Ready(Err(error));
14092            }
14093        }
14094        let session = match self
14095            .worker_session
14096            .as_ref()
14097            .map(WorkerSessionOptions::to_wire)
14098            .transpose()
14099        {
14100            Ok(value) => value,
14101            Err(error) => return Poll::Ready(Err(error)),
14102        };
14103        let session_queue = session
14104            .as_ref()
14105            .and_then(|session| session["queue"].as_str());
14106        let task_queue = options
14107            .task_queue
14108            .clone()
14109            .or_else(|| session_queue.map(str::to_owned))
14110            .unwrap_or_else(|| state.task_queue.clone());
14111        if session_queue.is_some_and(|queue| queue != task_queue) {
14112            return Poll::Ready(Err(Error::WorkerLoop(
14113                "worker-session queue must match the activity task queue".into(),
14114            )));
14115        }
14116        let current_recorded_options = RecordedActivityOptions {
14117            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
14118            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
14119            retry_policy: current_activity_retry_snapshot(&options),
14120            worker_session: session,
14121        };
14122
14123        let cursor = state.command_cursor;
14124        let call_kind = if self.local {
14125            CancellationCallKind::LocalActivity
14126        } else {
14127            CancellationCallKind::Activity
14128        };
14129        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14130            return Poll::Ready(Err(error));
14131        }
14132        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
14133            Ok(recorded) => recorded,
14134            Err(error) => return Poll::Ready(Err(error)),
14135        };
14136        if let Some(recorded) = recorded {
14137            let sequence = recorded.sequence();
14138            match recorded {
14139                RecordedCommand::Activity {
14140                    activity_type,
14141                    cancellation_policy,
14142                    options: recorded_options,
14143                    outcome,
14144                    parallel_group_path,
14145                    ..
14146                } => {
14147                    let current_policy = options
14148                        .cancellation_policy
14149                        .unwrap_or(CancellationPolicy::TryCancel)
14150                        .as_str();
14151                    if cancellation_policy != current_policy {
14152                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14153                            ReplayFailure::new(
14154                                "activity_cancellation_policy_changed",
14155                                Some(sequence),
14156                                Some(cancellation_policy),
14157                                Some(current_policy.to_string()),
14158                                "Activity cancellation policy changed during replay",
14159                            ),
14160                        )));
14161                    }
14162                    if let Err(error) = ensure_parallel_path_matches(
14163                        sequence,
14164                        parallel_group_path.as_deref(),
14165                        &self.parallel_group_path,
14166                    ) {
14167                        return Poll::Ready(Err(error));
14168                    }
14169                    if let Some(recorded_type) = activity_type {
14170                        if recorded_type != self.activity_type {
14171                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14172                                ReplayFailure::new(
14173                                    "recorded_command_detail_mismatch",
14174                                    Some(sequence),
14175                                    Some(format!("activity:{recorded_type}")),
14176                                    Some(format!("activity:{}", self.activity_type)),
14177                                    "recorded activity type differs from the current workflow command",
14178                                ),
14179                            )));
14180                        }
14181                    }
14182                    if let Some(recorded_options) = recorded_options {
14183                        if recorded_options.worker_session
14184                            != current_recorded_options.worker_session
14185                        {
14186                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14187                                "activity_worker_session_mismatch", Some(sequence),
14188                                Some(activity_options_description(&recorded_options)),
14189                                Some(activity_options_description(&current_recorded_options)),
14190                                "recorded worker-session routing differs from the current activity",
14191                            ))));
14192                        }
14193                        if !recorded_options
14194                            .task_queue
14195                            .matches_current(&current_recorded_options.task_queue)
14196                        {
14197                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14198                                ReplayFailure::new(
14199                                    "activity_task_queue_mismatch",
14200                                    Some(sequence),
14201                                    Some(activity_options_description(&recorded_options)),
14202                                    Some(activity_options_description(&current_recorded_options)),
14203                                    "recorded activity task queue differs from the current workflow command",
14204                                ),
14205                            )));
14206                        }
14207                        if (self.local
14208                            && matches!(
14209                                recorded_options.execution_mode,
14210                                RecordedSnapshotValue::Unknown
14211                            ))
14212                            || !recorded_options
14213                                .execution_mode
14214                                .matches_current(&current_recorded_options.execution_mode)
14215                        {
14216                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14217                                ReplayFailure::new(
14218                                    "activity_execution_mode_mismatch",
14219                                    Some(sequence),
14220                                    Some(activity_options_description(&recorded_options)),
14221                                    Some(activity_options_description(&current_recorded_options)),
14222                                    "recorded activity execution mode differs from the current workflow command",
14223                                ),
14224                            )));
14225                        }
14226                        if !recorded_options
14227                            .retry_policy
14228                            .matches_current(&current_recorded_options.retry_policy)
14229                        {
14230                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14231                                ReplayFailure::new(
14232                                    "activity_retry_policy_mismatch",
14233                                    Some(sequence),
14234                                    Some(activity_options_description(&recorded_options)),
14235                                    Some(activity_options_description(&current_recorded_options)),
14236                                    "recorded activity retry policy differs from the current workflow command",
14237                                ),
14238                            )));
14239                        }
14240                    }
14241                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
14242                        return Poll::Ready(Err(error));
14243                    }
14244                    match state.prepare_scalar_cancellation(
14245                        cursor,
14246                        call_kind,
14247                        &self.parallel_group_path,
14248                    ) {
14249                        Ok(true) => {
14250                            self.scheduled = true;
14251                            return Poll::Pending;
14252                        }
14253                        Ok(false) => {}
14254                        Err(error) => return Poll::Ready(Err(error)),
14255                    }
14256                    state.command_cursor += 1;
14257                    if let Some(outcome) = outcome {
14258                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14259                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
14260                    }
14261                    state.matched_recorded_pending = true;
14262                    self.scheduled = true;
14263                    return Poll::Pending;
14264                }
14265                other => {
14266                    return Poll::Ready(Err(command_mismatch(
14267                        &other,
14268                        format!("activity:{}", self.activity_type),
14269                    )));
14270                }
14271            }
14272        }
14273
14274        if !self.scheduled {
14275            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14276                Ok(args) => args,
14277                Err(error) => return Poll::Ready(Err(error)),
14278            };
14279            let arguments = normalize_avro_arguments(args);
14280            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
14281                Ok(envelope) => envelope,
14282                Err(error) => return Poll::Ready(Err(error)),
14283            };
14284
14285            let mut command = serde_json::Map::from_iter([
14286                (
14287                    "type".to_string(),
14288                    json!(if self.local {
14289                        "record_local_activity"
14290                    } else {
14291                        "schedule_activity"
14292                    }),
14293                ),
14294                (
14295                    "activity_type".to_string(),
14296                    json!(self.activity_type.clone()),
14297                ),
14298                ("queue".to_string(), json!(task_queue)),
14299                ("arguments".to_string(), envelope),
14300            ]);
14301            for (field, value) in [
14302                ("start_to_close_timeout", options.start_to_close_timeout),
14303                (
14304                    "schedule_to_start_timeout",
14305                    options.schedule_to_start_timeout,
14306                ),
14307                (
14308                    "schedule_to_close_timeout",
14309                    options.schedule_to_close_timeout,
14310                ),
14311                ("heartbeat_timeout", options.heartbeat_timeout),
14312            ] {
14313                if let Some(value) = value {
14314                    command.insert(field.to_string(), json!(value));
14315                }
14316            }
14317            if let Some(retry_policy) = &options.retry_policy {
14318                command.insert("retry_policy".to_string(), retry_policy.clone());
14319            }
14320            if let Some(policy) = options.cancellation_policy {
14321                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
14322            }
14323            if let Some(session) = current_recorded_options.worker_session {
14324                command.insert("worker_session".into(), session);
14325            }
14326            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14327            ctx.apply_scope_membership(&mut command);
14328            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
14329                Ok(true) => {
14330                    self.scheduled = true;
14331                    return Poll::Pending;
14332                }
14333                Ok(false) => {}
14334                Err(error) => return Poll::Ready(Err(error)),
14335            }
14336            if self.local {
14337                command.remove("queue");
14338                command.insert("execution_mode".into(), json!("local"));
14339                let result = Arc::new(Mutex::new(None));
14340                let command_index = state.commands.len();
14341                state.local_activity_requests.push(local_activity::Request {
14342                    command_index,
14343                    options,
14344                    arguments,
14345                    result: result.clone(),
14346                });
14347                self.local_result = Some(result);
14348            }
14349            state.commands.push(Value::Object(command));
14350            self.scheduled = true;
14351        }
14352
14353        Poll::Pending
14354    }
14355}
14356
14357impl Future for ActivityCall {
14358    type Output = Result<Value>;
14359
14360    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14361        match self.poll_avro_value(cx) {
14362            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
14363            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14364            Poll::Pending => Poll::Pending,
14365        }
14366    }
14367}
14368
14369/// Future returned by [`WorkflowContext::sleep`].
14370pub struct TimerCall {
14371    ctx: WorkflowContext,
14372    delay_seconds: Option<u64>,
14373    scheduled: bool,
14374    matched_pending: bool,
14375    parallel_group_path: Vec<ParallelGroupMetadata>,
14376}
14377
14378impl Future for TimerCall {
14379    type Output = Result<()>;
14380
14381    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14382        if self.matched_pending {
14383            return Poll::Pending;
14384        }
14385
14386        let ctx = self.ctx.clone();
14387        let Some(requested_delay) = self.delay_seconds else {
14388            return Poll::Ready(Err(Error::TimerDurationOverflow));
14389        };
14390        let mut state = match ctx.state.lock() {
14391            Ok(state) => state,
14392            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14393        };
14394
14395        let cursor = state.command_cursor;
14396        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14397            return Poll::Ready(Err(error));
14398        }
14399        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
14400        {
14401            Ok(recorded) => recorded,
14402            Err(error) => return Poll::Ready(Err(error)),
14403        };
14404        if let Some(recorded) = recorded {
14405            match recorded {
14406                RecordedCommand::Timer {
14407                    sequence,
14408                    delay_seconds,
14409                    fired,
14410                    parallel_group_path,
14411                    ..
14412                } => {
14413                    if let Err(error) =
14414                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
14415                    {
14416                        return Poll::Ready(Err(error));
14417                    }
14418                    if let Err(error) = ensure_parallel_path_matches(
14419                        sequence,
14420                        parallel_group_path.as_deref(),
14421                        &self.parallel_group_path,
14422                    ) {
14423                        return Poll::Ready(Err(error));
14424                    }
14425                    if delay_seconds != requested_delay {
14426                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14427                            ReplayFailure::new(
14428                                "timer_delay_mismatch",
14429                                Some(sequence),
14430                                Some(format!("timer:{delay_seconds}s")),
14431                                Some(format!("timer:{requested_delay}s")),
14432                                "recorded timer delay differs from the current workflow command",
14433                            ),
14434                        )));
14435                    }
14436                    if let Err(error) =
14437                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
14438                    {
14439                        return Poll::Ready(Err(error));
14440                    }
14441                    match state.prepare_scalar_cancellation(
14442                        cursor,
14443                        CancellationCallKind::Timer,
14444                        &self.parallel_group_path,
14445                    ) {
14446                        Ok(true) => {
14447                            self.scheduled = true;
14448                            self.matched_pending = true;
14449                            return Poll::Pending;
14450                        }
14451                        Ok(false) => {}
14452                        Err(error) => return Poll::Ready(Err(error)),
14453                    }
14454                    state.command_cursor += 1;
14455                    if fired {
14456                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14457                        return Poll::Ready(Ok(()));
14458                    }
14459                    state.matched_recorded_pending = true;
14460                    self.scheduled = true;
14461                    self.matched_pending = true;
14462                    return Poll::Pending;
14463                }
14464                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
14465            }
14466        }
14467
14468        if !self.scheduled {
14469            let mut command = serde_json::Map::from_iter([
14470                ("type".to_string(), json!("start_timer")),
14471                ("delay_seconds".to_string(), json!(requested_delay)),
14472            ]);
14473            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
14474                Ok(Some(proof)) => {
14475                    command.insert("cancellation_cleanup".into(), proof);
14476                }
14477                Ok(None) => {}
14478                Err(error) => return Poll::Ready(Err(error)),
14479            }
14480            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14481            ctx.apply_scope_membership(&mut command);
14482            match state.prepare_scalar_cancellation(
14483                cursor,
14484                CancellationCallKind::Timer,
14485                &self.parallel_group_path,
14486            ) {
14487                Ok(true) => {
14488                    self.scheduled = true;
14489                    self.matched_pending = true;
14490                    return Poll::Pending;
14491                }
14492                Ok(false) => {}
14493                Err(error) => return Poll::Ready(Err(error)),
14494            }
14495            state.commands.push(Value::Object(command));
14496            self.scheduled = true;
14497        }
14498
14499        Poll::Pending
14500    }
14501}
14502
14503/// Future returned by [`WorkflowContext::wait_condition`].
14504pub struct ConditionWaitCall {
14505    ctx: WorkflowContext,
14506    options: ConditionWaitOptions,
14507    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
14508    occurrence_id: Option<String>,
14509    opened_wait: bool,
14510    parallel_group_path: Vec<ParallelGroupMetadata>,
14511}
14512
14513impl Future for ConditionWaitCall {
14514    type Output = Result<ConditionWaitResult>;
14515
14516    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14517        if self.opened_wait {
14518            return Poll::Pending;
14519        }
14520
14521        let options = match self.options.validate() {
14522            Ok(options) => options,
14523            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
14524        };
14525        let ctx = self.ctx.clone();
14526        let occurrence_id = match self.occurrence_id.as_ref() {
14527            Some(occurrence_id) => occurrence_id.clone(),
14528            None => {
14529                let mut state = match ctx.state.lock() {
14530                    Ok(state) => state,
14531                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14532                };
14533                let ordinal = state.condition_wait_occurrence_counter;
14534                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
14535                    Some(next) => next,
14536                    None => {
14537                        return Poll::Ready(Err(Error::WorkerLoop(
14538                            "condition wait occurrence counter overflowed".to_string(),
14539                        )))
14540                    }
14541                };
14542                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
14543                drop(state);
14544                self.occurrence_id = Some(occurrence_id.clone());
14545                occurrence_id
14546            }
14547        };
14548
14549        let recorded_result = {
14550            let mut state = match ctx.state.lock() {
14551                Ok(state) => state,
14552                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14553            };
14554            let initial_cursor = state.command_cursor;
14555            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
14556                return Poll::Ready(Err(error));
14557            }
14558            let recorded = match state
14559                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
14560            {
14561                Ok(recorded) => recorded,
14562                Err(error) => return Poll::Ready(Err(error)),
14563            };
14564            let Some(recorded) = recorded else {
14565                drop(state);
14566                return self.poll_new_condition(options);
14567            };
14568            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
14569                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
14570            }
14571
14572            let mut cursor = state.command_cursor;
14573            let mut result = None;
14574            let mut pending_delivery = false;
14575            loop {
14576                if cursor > initial_cursor
14577                    && matches!(
14578                        state.recorded_commands.get(cursor),
14579                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
14580                    )
14581                {
14582                    break;
14583                }
14584                let recorded = match state
14585                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
14586                {
14587                    Ok(recorded) => recorded,
14588                    Err(error) => return Poll::Ready(Err(error)),
14589                };
14590                let Some(RecordedCommand::ConditionWait {
14591                    sequence,
14592                    occurrence_id: ref recorded_occurrence_id,
14593                    ref condition_key,
14594                    ref predicate_identity,
14595                    timeout_seconds,
14596                    result: recorded_result,
14597                    ref parallel_group_path,
14598                    ..
14599                }) = recorded
14600                else {
14601                    break;
14602                };
14603
14604                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
14605                    break;
14606                }
14607                if let Err(error) = ensure_parallel_path_matches(
14608                    sequence,
14609                    parallel_group_path.as_deref(),
14610                    &self.parallel_group_path,
14611                ) {
14612                    return Poll::Ready(Err(error));
14613                }
14614                if let Err(error) = validate_recorded_condition_wait(
14615                    sequence,
14616                    recorded_occurrence_id,
14617                    condition_key.as_deref(),
14618                    predicate_identity,
14619                    timeout_seconds,
14620                    &occurrence_id,
14621                    &options,
14622                ) {
14623                    return Poll::Ready(Err(error));
14624                }
14625                if result == Some(ConditionWaitResult::TimedOut) {
14626                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14627                        "condition_wait_reopened_after_timeout",
14628                        Some(sequence),
14629                        Some("timed-out condition is terminal".to_string()),
14630                        Some("another physical wait-open".to_string()),
14631                        "condition history reopened one logical wait after its durable timeout",
14632                    ))));
14633                }
14634                if let Err(error) =
14635                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
14636                {
14637                    return Poll::Ready(Err(error));
14638                }
14639                match state.prepare_scalar_cancellation(
14640                    cursor,
14641                    CancellationCallKind::Condition,
14642                    &self.parallel_group_path,
14643                ) {
14644                    Ok(pending) => pending_delivery |= pending,
14645                    Err(error) => return Poll::Ready(Err(error)),
14646                }
14647                result = recorded_result;
14648                if result.is_some() {
14649                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14650                }
14651                cursor += 1;
14652            }
14653            state.command_cursor = cursor;
14654            if pending_delivery {
14655                self.opened_wait = true;
14656                return Poll::Pending;
14657            }
14658            result
14659        };
14660
14661        if let Some(result) = recorded_result {
14662            return Poll::Ready(Ok(result));
14663        }
14664
14665        self.poll_open_condition(options, true)
14666    }
14667}
14668
14669impl ConditionWaitCall {
14670    fn poll_new_condition(
14671        self: Pin<&mut Self>,
14672        options: ValidatedConditionWaitOptions,
14673    ) -> Poll<Result<ConditionWaitResult>> {
14674        self.poll_open_condition(options, false)
14675    }
14676
14677    fn poll_open_condition(
14678        mut self: Pin<&mut Self>,
14679        options: ValidatedConditionWaitOptions,
14680        recorded_wait: bool,
14681    ) -> Poll<Result<ConditionWaitResult>> {
14682        {
14683            let ctx = self.ctx.clone();
14684            let mut state = match ctx.state.lock() {
14685                Ok(state) => state,
14686                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14687            };
14688            let cursor = state.command_cursor;
14689            match state.prepare_scalar_cancellation(
14690                cursor,
14691                CancellationCallKind::Condition,
14692                &self.parallel_group_path,
14693            ) {
14694                Ok(true) => {
14695                    self.opened_wait = true;
14696                    return Poll::Pending;
14697                }
14698                Ok(false) => {}
14699                Err(error) => return Poll::Ready(Err(error)),
14700            }
14701        }
14702        let selection_member = self
14703            .parallel_group_path
14704            .first()
14705            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14706        match (self.predicate)() {
14707            Ok(true) if !selection_member || recorded_wait => {
14708                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14709            }
14710            Ok(_) => {}
14711            Err(error) => return Poll::Ready(Err(error)),
14712        }
14713        if options.timeout_seconds == Some(0) && !selection_member {
14714            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14715        }
14716
14717        let ctx = self.ctx.clone();
14718        let mut state = match ctx.state.lock() {
14719            Ok(state) => state,
14720            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14721        };
14722        let mut command = serde_json::Map::from_iter([
14723            ("type".to_string(), json!("open_condition_wait")),
14724            (
14725                "condition_wait_occurrence_id".to_string(),
14726                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14727            ),
14728            ("condition_key".to_string(), json!(options.condition_key)),
14729            (
14730                "condition_definition_fingerprint".to_string(),
14731                json!(options.predicate_identity),
14732            ),
14733        ]);
14734        if let Some(timeout_seconds) = options.timeout_seconds {
14735            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14736        }
14737        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14738        ctx.apply_scope_membership(&mut command);
14739        state.commands.push(Value::Object(command));
14740        drop(state);
14741        self.opened_wait = true;
14742        Poll::Pending
14743    }
14744}
14745
14746fn validate_recorded_condition_wait(
14747    sequence: u64,
14748    recorded_occurrence_id: &str,
14749    recorded_key: Option<&str>,
14750    recorded_predicate_identity: &str,
14751    recorded_timeout_seconds: Option<u64>,
14752    current_occurrence_id: &str,
14753    current: &ValidatedConditionWaitOptions,
14754) -> Result<()> {
14755    if recorded_occurrence_id != current_occurrence_id {
14756        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14757            "condition_wait_occurrence_mismatch",
14758            Some(sequence),
14759            Some(recorded_occurrence_id.to_string()),
14760            Some(current_occurrence_id.to_string()),
14761            "recorded condition occurrence differs from the current authored wait position",
14762        )));
14763    }
14764    if recorded_key != Some(current.condition_key.as_str()) {
14765        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14766            "condition_wait_key_mismatch",
14767            Some(sequence),
14768            recorded_key.map(str::to_string),
14769            Some(current.condition_key.clone()),
14770            "recorded condition identity differs from the current workflow wait",
14771        )));
14772    }
14773    if recorded_predicate_identity != current.predicate_identity {
14774        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14775            "condition_wait_predicate_mismatch",
14776            Some(sequence),
14777            Some(recorded_predicate_identity.to_string()),
14778            Some(current.predicate_identity.clone()),
14779            "recorded condition predicate behavior differs from current workflow code",
14780        )));
14781    }
14782    if recorded_timeout_seconds != current.timeout_seconds {
14783        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14784            "condition_wait_timeout_mismatch",
14785            Some(sequence),
14786            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14787            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14788            "recorded condition timeout differs from the current workflow wait",
14789        )));
14790    }
14791    Ok(())
14792}
14793
14794/// Future returned by [`WorkflowContext::start_child_workflow`].
14795pub struct ChildWorkflowCall {
14796    ctx: WorkflowContext,
14797    workflow_type: String,
14798    options: ChildWorkflowOptions,
14799    args: Option<Result<AvroValue>>,
14800    scheduled: bool,
14801    matched_pending: bool,
14802    parallel_group_path: Vec<ParallelGroupMetadata>,
14803}
14804
14805impl ChildWorkflowCall {
14806    fn poll_avro_value(
14807        mut self: Pin<&mut Self>,
14808        _cx: &mut TaskContext<'_>,
14809    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14810        if self.matched_pending {
14811            return Poll::Pending;
14812        }
14813
14814        let ctx = self.ctx.clone();
14815        let mut state = match ctx.state.lock() {
14816            Ok(state) => state,
14817            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14818        };
14819
14820        let cursor = state.command_cursor;
14821        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14822            return Poll::Ready(Err(error));
14823        }
14824        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
14825        {
14826            Ok(recorded) => recorded,
14827            Err(error) => return Poll::Ready(Err(error)),
14828        };
14829        if let Some(recorded) = recorded {
14830            let sequence = recorded.sequence();
14831            match recorded {
14832                RecordedCommand::ChildWorkflow {
14833                    workflow_type,
14834                    policies,
14835                    outcome,
14836                    parallel_group_path,
14837                    ..
14838                } => {
14839                    if let Err(error) = ensure_parallel_path_matches(
14840                        sequence,
14841                        parallel_group_path.as_deref(),
14842                        &self.parallel_group_path,
14843                    ) {
14844                        return Poll::Ready(Err(error));
14845                    }
14846                    if let Some(recorded_type) = workflow_type {
14847                        if recorded_type != self.workflow_type {
14848                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14849                                ReplayFailure::new(
14850                                    "recorded_command_detail_mismatch",
14851                                    Some(sequence),
14852                                    Some(format!("child workflow:{recorded_type}")),
14853                                    Some(format!("child workflow:{}", self.workflow_type)),
14854                                    "recorded child workflow type differs from the current workflow command",
14855                                ),
14856                            )));
14857                        }
14858                    }
14859                    if let Err(error) =
14860                        ensure_child_policies_match(sequence, &policies, &self.options)
14861                    {
14862                        return Poll::Ready(Err(error));
14863                    }
14864                    if let Err(error) =
14865                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
14866                    {
14867                        return Poll::Ready(Err(error));
14868                    }
14869                    match state.prepare_scalar_cancellation(
14870                        cursor,
14871                        CancellationCallKind::Child,
14872                        &self.parallel_group_path,
14873                    ) {
14874                        Ok(true) => {
14875                            self.scheduled = true;
14876                            self.matched_pending = true;
14877                            return Poll::Pending;
14878                        }
14879                        Ok(false) => {}
14880                        Err(error) => return Poll::Ready(Err(error)),
14881                    }
14882                    state.command_cursor += 1;
14883                    if let Some(outcome) = outcome {
14884                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14885                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
14886                    }
14887                    state.matched_recorded_pending = true;
14888                    self.scheduled = true;
14889                    self.matched_pending = true;
14890                    return Poll::Pending;
14891                }
14892                other => {
14893                    return Poll::Ready(Err(command_mismatch(
14894                        &other,
14895                        format!("child workflow:{}", self.workflow_type),
14896                    )));
14897                }
14898            }
14899        }
14900
14901        if !self.scheduled {
14902            if self.options.task_queue.trim().is_empty() {
14903                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14904                    "task_queue must not be empty".to_string(),
14905                )));
14906            }
14907            for (name, value) in [
14908                (
14909                    "execution_timeout_seconds",
14910                    self.options.execution_timeout_seconds,
14911                ),
14912                ("run_timeout_seconds", self.options.run_timeout_seconds),
14913            ] {
14914                if value == Some(0) {
14915                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
14916                        "{name} must be at least 1"
14917                    ))));
14918                }
14919            }
14920
14921            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14922                Ok(args) => args,
14923                Err(error) => return Poll::Ready(Err(error)),
14924            };
14925            let arguments = match encode_typed_envelope(
14926                &normalize_avro_arguments(args),
14927                &state.payload_codec,
14928            ) {
14929                Ok(arguments) => arguments,
14930                Err(error) => return Poll::Ready(Err(error)),
14931            };
14932            let mut command = json!({
14933                "type": "start_child_workflow",
14934                "workflow_type": self.workflow_type,
14935                "queue": self.options.task_queue,
14936                "parent_close_policy": self.options.parent_close_policy.as_str(),
14937                "arguments": arguments,
14938            });
14939            let object = command
14940                .as_object_mut()
14941                .expect("child workflow command is always an object");
14942            if self.options.cancellation_policy != CancellationPolicy::Abandon {
14943                object.insert(
14944                    "cancellation_policy".to_string(),
14945                    json!(self.options.cancellation_policy.as_str()),
14946                );
14947            }
14948            if let Some(policy) = &self.options.retry_policy {
14949                let mut retry_policy = serde_json::Map::new();
14950                if let Some(max_attempts) = policy.max_attempts {
14951                    if max_attempts == 0 {
14952                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14953                            "retry_policy.max_attempts must be at least 1".to_string(),
14954                        )));
14955                    }
14956                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
14957                }
14958                if !policy.backoff_seconds.is_empty() {
14959                    retry_policy
14960                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
14961                }
14962                if !policy.non_retryable_error_types.is_empty() {
14963                    retry_policy.insert(
14964                        "non_retryable_error_types".to_string(),
14965                        json!(policy.non_retryable_error_types),
14966                    );
14967                }
14968                if retry_policy.is_empty() {
14969                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14970                        "retry_policy must configure at least one field".to_string(),
14971                    )));
14972                }
14973                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
14974            }
14975            if let Some(seconds) = self.options.execution_timeout_seconds {
14976                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
14977            }
14978            if let Some(seconds) = self.options.run_timeout_seconds {
14979                object.insert("run_timeout_seconds".to_string(), json!(seconds));
14980            }
14981            apply_parallel_group_path(object, &self.parallel_group_path);
14982            ctx.apply_scope_membership(object);
14983            match state.prepare_scalar_cancellation(
14984                cursor,
14985                CancellationCallKind::Child,
14986                &self.parallel_group_path,
14987            ) {
14988                Ok(true) => {
14989                    self.scheduled = true;
14990                    self.matched_pending = true;
14991                    return Poll::Pending;
14992                }
14993                Ok(false) => {}
14994                Err(error) => return Poll::Ready(Err(error)),
14995            }
14996            state.commands.push(command);
14997            self.scheduled = true;
14998        }
14999
15000        Poll::Pending
15001    }
15002}
15003
15004impl Future for ChildWorkflowCall {
15005    type Output = Result<ChildWorkflowResult>;
15006
15007    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15008        match self.poll_avro_value(cx) {
15009            Poll::Ready(Ok(result)) => match result.result.into_json() {
15010                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15011                    parent: result.parent,
15012                    child: result.child,
15013                    child_workflow_type: result.child_workflow_type,
15014                    result: projected,
15015                })),
15016                Err(error) => Poll::Ready(Err(error)),
15017            },
15018            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15019            Poll::Pending => Poll::Pending,
15020        }
15021    }
15022}
15023
15024fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15025    Error::NonDeterministicReplay(ReplayFailure::new(
15026        "recorded_command_mismatch",
15027        Some(recorded.sequence()),
15028        Some(recorded.shape().to_string()),
15029        Some(actual.into()),
15030        "current workflow command does not match the recorded durable command sequence",
15031    ))
15032}
15033
15034pub struct SignalCall {
15035    ctx: WorkflowContext,
15036    signal_name: String,
15037    runtime_reserved_allowed: bool,
15038    opened_wait: bool,
15039    matched_pending: bool,
15040    parallel_group_path: Vec<ParallelGroupMetadata>,
15041}
15042
15043impl SignalCall {
15044    fn poll_avro_value(
15045        mut self: Pin<&mut Self>,
15046        _cx: &mut TaskContext<'_>,
15047    ) -> Poll<Result<Vec<AvroValue>>> {
15048        if self.matched_pending {
15049            return Poll::Pending;
15050        }
15051        if !self.runtime_reserved_allowed {
15052            if let Err(error) = validate_user_signal_name(&self.signal_name) {
15053                return Poll::Ready(Err(error));
15054            }
15055        }
15056
15057        let ctx = self.ctx.clone();
15058        let mut state = match ctx.state.lock() {
15059            Ok(state) => state,
15060            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15061        };
15062
15063        let cursor = state.command_cursor;
15064        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15065            return Poll::Ready(Err(error));
15066        }
15067        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
15068        {
15069            Ok(recorded) => recorded,
15070            Err(error) => return Poll::Ready(Err(error)),
15071        };
15072        if let Some(recorded) = recorded {
15073            match recorded {
15074                RecordedCommand::SignalWait {
15075                    sequence,
15076                    signal_name,
15077                    value,
15078                    parallel_group_path,
15079                } => {
15080                    if let Err(error) = ensure_parallel_path_matches(
15081                        sequence,
15082                        parallel_group_path.as_deref(),
15083                        &self.parallel_group_path,
15084                    ) {
15085                        return Poll::Ready(Err(error));
15086                    }
15087                    if signal_name != self.signal_name {
15088                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15089                            ReplayFailure::new(
15090                                "recorded_command_detail_mismatch",
15091                                Some(sequence),
15092                                Some(format!("signal wait:{signal_name}")),
15093                                Some(format!("signal wait:{}", self.signal_name)),
15094                                "recorded signal name differs from the current workflow command",
15095                            ),
15096                        )));
15097                    }
15098
15099                    if let Err(error) =
15100                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
15101                    {
15102                        return Poll::Ready(Err(error));
15103                    }
15104                    match state.prepare_scalar_cancellation(
15105                        cursor,
15106                        CancellationCallKind::Signal,
15107                        &self.parallel_group_path,
15108                    ) {
15109                        Ok(true) => {
15110                            self.opened_wait = true;
15111                            self.matched_pending = true;
15112                            return Poll::Pending;
15113                        }
15114                        Ok(false) => {}
15115                        Err(error) => return Poll::Ready(Err(error)),
15116                    }
15117                    state.command_cursor += 1;
15118                    if let Some(value) = value {
15119                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15120                        return Poll::Ready(Ok(value));
15121                    }
15122                    if state
15123                        .resume_signal
15124                        .as_ref()
15125                        .is_some_and(|signal| signal.signal_name == self.signal_name)
15126                    {
15127                        let signal = state
15128                            .resume_signal
15129                            .take()
15130                            .expect("matching resume signal is present");
15131                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
15132                        return Poll::Ready(Ok(signal.arguments));
15133                    }
15134
15135                    state.matched_recorded_pending = true;
15136                    self.opened_wait = true;
15137                    self.matched_pending = true;
15138                    return Poll::Pending;
15139                }
15140                other => {
15141                    return Poll::Ready(Err(command_mismatch(
15142                        &other,
15143                        format!("signal wait:{}", self.signal_name),
15144                    )));
15145                }
15146            }
15147        }
15148
15149        match state.prepare_scalar_cancellation(
15150            cursor,
15151            CancellationCallKind::Signal,
15152            &self.parallel_group_path,
15153        ) {
15154            Ok(true) => {
15155                self.opened_wait = true;
15156                self.matched_pending = true;
15157                return Poll::Pending;
15158            }
15159            Ok(false) => {}
15160            Err(error) => return Poll::Ready(Err(error)),
15161        }
15162
15163        if state
15164            .resume_signal
15165            .as_ref()
15166            .is_some_and(|signal| signal.signal_name == self.signal_name)
15167        {
15168            let signal = state
15169                .resume_signal
15170                .take()
15171                .expect("matching resume signal is present");
15172            state.unavailable_cancellation_boundary(&self.parallel_group_path);
15173            return Poll::Ready(Ok(signal.arguments));
15174        }
15175
15176        if !self.opened_wait {
15177            let mut command = serde_json::Map::from_iter([
15178                ("type".to_string(), json!("open_signal_wait")),
15179                ("signal_name".to_string(), json!(self.signal_name)),
15180            ]);
15181            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15182            ctx.apply_scope_membership(&mut command);
15183            state.commands.push(Value::Object(command));
15184            self.opened_wait = true;
15185        }
15186
15187        Poll::Pending
15188    }
15189}
15190
15191impl Future for SignalCall {
15192    type Output = Result<Vec<Value>>;
15193
15194    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15195        match self.poll_avro_value(cx) {
15196            Poll::Ready(Ok(values)) => Poll::Ready(
15197                values
15198                    .into_iter()
15199                    .map(AvroValue::into_json)
15200                    .collect::<Result<Vec<_>>>(),
15201            ),
15202            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15203            Poll::Pending => Poll::Pending,
15204        }
15205    }
15206}
15207
15208#[derive(Clone, Debug)]
15209pub struct ActivityContext {
15210    client: Client,
15211    pub task_id: String,
15212    pub activity_attempt_id: String,
15213    pub lease_owner: String,
15214    pub activity_type: String,
15215    pub attempt_number: u64,
15216    pub task_queue: String,
15217    pub worker_id: String,
15218    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
15219    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
15220    worker_session: Option<WorkerSession>,
15221}
15222
15223impl ActivityContext {
15224    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
15225        if let Some(heartbeats) = &self.local_heartbeats {
15226            return heartbeats
15227                .lock()
15228                .map_err(|_| Error::WorkflowStatePoisoned)?
15229                .record(details);
15230        }
15231        if let Some(guard) = &self.claim_guard {
15232            return guard.heartbeat(self, details).await;
15233        }
15234        if let Some(session) = &self.worker_session {
15235            if !session.active() {
15236                return Err(Error::ActivityExecutionAbandoned(
15237                    "worker-session lease or TTL is no longer active".into(),
15238                ));
15239            }
15240            let result = self
15241                .client
15242                .heartbeat_activity_task_value(
15243                    &self.task_id,
15244                    &self.activity_attempt_id,
15245                    &self.lease_owner,
15246                    details,
15247                )
15248                .await;
15249            return worker_session::settle_activity_heartbeat(
15250                session,
15251                result,
15252                &self.task_id,
15253                &self.activity_attempt_id,
15254                &self.lease_owner,
15255            );
15256        }
15257        self.client
15258            .heartbeat_activity_task(
15259                &self.task_id,
15260                &self.activity_attempt_id,
15261                &self.lease_owner,
15262                details,
15263            )
15264            .await
15265    }
15266}
15267
15268fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
15269    validate_payload_codec(codec)?;
15270    match value {
15271        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
15272            value, codec,
15273        )?)),
15274        None => Ok(AvroValue::Array(Vec::new())),
15275    }
15276}
15277
15278fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
15279    let Some(signal_name) = task
15280        .signal_name
15281        .as_deref()
15282        .filter(|value| !value.is_empty())
15283    else {
15284        return Ok(None);
15285    };
15286    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
15287    let AvroValue::Array(arguments) = decoded else {
15288        unreachable!("normalize_avro_arguments always returns an array");
15289    };
15290
15291    Ok(Some(ResumeSignal {
15292        signal_name: signal_name.to_string(),
15293        arguments,
15294    }))
15295}
15296
15297fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
15298    validate_payload_codec(&task.payload_codec)?;
15299    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
15300    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
15301    for event in &task.history_events {
15302        validate_history_event_payloads(event, &task.payload_codec)?;
15303    }
15304    Ok(())
15305}
15306
15307fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
15308    validate_payload_codec(&task.payload_codec)?;
15309    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
15310}
15311
15312fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
15313    validate_payload_codec(&task.payload_codec)?;
15314    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
15315    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
15316    for event in &task.history_events {
15317        validate_history_event_payloads(event, &task.payload_codec)?;
15318    }
15319
15320    let Some(export) = task.history_export.as_ref() else {
15321        return Ok(());
15322    };
15323    let export_codec = match export.get("payloads") {
15324        Some(payloads) => declared_payload_codec(payloads, "codec")?,
15325        None => None,
15326    }
15327    .unwrap_or(&task.payload_codec);
15328    validate_payload_codec(export_codec)?;
15329
15330    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
15331        for event in events {
15332            let event_type = event
15333                .get("event_type")
15334                .or_else(|| event.get("type"))
15335                .and_then(Value::as_str)
15336                .unwrap_or_default();
15337            if let Some(payload) = event.get("payload") {
15338                validate_history_payloads(event_type, payload, export_codec)?;
15339            }
15340        }
15341    }
15342    for signal in export
15343        .get("signals")
15344        .and_then(Value::as_array)
15345        .into_iter()
15346        .flatten()
15347    {
15348        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
15349        validate_payload_codec(codec)?;
15350        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
15351    }
15352    for activity in export
15353        .get("activities")
15354        .and_then(Value::as_array)
15355        .into_iter()
15356        .flatten()
15357    {
15358        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
15359        validate_payload_codec(codec)?;
15360        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
15361        validate_optional_inbound_payload(activity.get("result"), codec)?;
15362    }
15363    Ok(())
15364}
15365
15366fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
15367    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
15368}
15369
15370fn validate_history_payloads(
15371    event_type: &str,
15372    payload: &Value,
15373    fallback_codec: &str,
15374) -> Result<()> {
15375    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
15376    validate_payload_codec(codec)?;
15377    for field in history_payload_fields(event_type) {
15378        validate_optional_inbound_payload(payload.get(*field), codec)?;
15379    }
15380    Ok(())
15381}
15382
15383const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
15384
15385fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
15386    match event_type {
15387        "ActivityCompleted" => &["result"],
15388        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
15389        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
15390        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
15391        "ChildRunCompleted" => &["result", "output"],
15392        "WorkflowCompleted" => &["output"],
15393        "ServiceCallStarted"
15394        | "ServiceCallCompleted"
15395        | "ServiceCallFailed"
15396        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
15397        _ => &[],
15398    }
15399}
15400
15401fn signal_history_payload(payload: &Value) -> Option<&Value> {
15402    SIGNAL_HISTORY_PAYLOAD_FIELDS
15403        .iter()
15404        .find_map(|field| payload.get(*field))
15405}
15406
15407fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
15408    match value.get(field) {
15409        None => Ok(None),
15410        Some(Value::String(codec)) => Ok(Some(codec)),
15411        Some(_) => Err(invalid_payload_envelope()),
15412    }
15413}
15414
15415fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
15416    validate_payload_codec(codec)?;
15417    if let Some(value) = value.filter(|value| !value.is_null()) {
15418        decode_wire_avro_value(value, codec)?;
15419    }
15420    Ok(())
15421}
15422
15423fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
15424    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
15425        invalid_recorded_history(
15426            "parallel_group_metadata_invalid",
15427            sequence,
15428            "non-empty parallel_group_id",
15429            &payload.to_string(),
15430            "parallel-group history is missing its stable identity",
15431        )
15432    })?;
15433    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
15434        invalid_recorded_history(
15435            "parallel_group_metadata_invalid",
15436            sequence,
15437            "activity, child, timer, signal, condition, or mixed group kind",
15438            &payload.to_string(),
15439            "parallel-group history is missing its group kind",
15440        )
15441    })?;
15442    if !matches!(
15443        kind.as_str(),
15444        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
15445    ) {
15446        return Err(invalid_recorded_history(
15447            "parallel_group_metadata_invalid",
15448            sequence,
15449            "activity, child, timer, signal, condition, or mixed group kind",
15450            &kind,
15451            "parallel-group history contains an unsupported group kind",
15452        ));
15453    }
15454    let base_sequence = payload
15455        .get("parallel_group_base_sequence")
15456        .and_then(value_as_u64)
15457        .filter(|value| *value > 0)
15458        .ok_or_else(|| {
15459            invalid_recorded_history(
15460                "parallel_group_metadata_invalid",
15461                sequence,
15462                "positive parallel_group_base_sequence",
15463                &payload.to_string(),
15464                "parallel-group history contains an invalid base sequence",
15465            )
15466        })?;
15467    let size = payload
15468        .get("parallel_group_size")
15469        .and_then(value_as_u64)
15470        .and_then(|value| usize::try_from(value).ok())
15471        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
15472        .ok_or_else(|| {
15473            invalid_recorded_history(
15474                "parallel_group_metadata_invalid",
15475                sequence,
15476                "bounded positive parallel_group_size",
15477                &payload.to_string(),
15478                "parallel-group history contains an invalid group size",
15479            )
15480        })?;
15481    let index = payload
15482        .get("parallel_group_index")
15483        .and_then(value_as_u64)
15484        .and_then(|value| usize::try_from(value).ok())
15485        .filter(|value| *value < size)
15486        .ok_or_else(|| {
15487            invalid_recorded_history(
15488                "parallel_group_metadata_invalid",
15489                sequence,
15490                "parallel_group_index within group bounds",
15491                &payload.to_string(),
15492                "parallel-group history contains an invalid member index",
15493            )
15494        })?;
15495    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
15496        return Err(invalid_recorded_history(
15497            "parallel_group_metadata_invalid",
15498            sequence,
15499            "base sequence plus member index equals workflow sequence",
15500            &payload.to_string(),
15501            "parallel-group path does not preserve durable workflow position",
15502        ));
15503    }
15504    let mode = payload
15505        .get("parallel_group_mode")
15506        .and_then(Value::as_str)
15507        .unwrap_or("all");
15508    if !matches!(mode, "all" | "select") {
15509        return Err(invalid_recorded_history(
15510            "parallel_group_metadata_invalid",
15511            sequence,
15512            "parallel group mode all or select",
15513            mode,
15514            "parallel-group history contains an unsupported group mode",
15515        ));
15516    }
15517    let expected_id = if mode == "select" {
15518        format!("select-calls:{base_sequence}:{size}")
15519    } else {
15520        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
15521    };
15522    if group_id != expected_id {
15523        return Err(invalid_recorded_history(
15524            "parallel_group_metadata_invalid",
15525            sequence,
15526            &expected_id,
15527            &group_id,
15528            "parallel-group history contains an incompatible stable group ID",
15529        ));
15530    }
15531    let selection_member_key = if mode == "select" {
15532        Some(selection_key_from_value(
15533            payload.get("selection_member_key"),
15534            sequence,
15535        )?)
15536    } else {
15537        None
15538    };
15539    let selection_member_index = if mode == "select" {
15540        Some(required_parallel_usize(
15541            payload,
15542            "selection_member_index",
15543            sequence,
15544        )?)
15545    } else {
15546        None
15547    };
15548    let selection_member_base_sequence = if mode == "select" {
15549        Some(
15550            payload
15551                .get("selection_member_base_sequence")
15552                .and_then(value_as_u64)
15553                .filter(|value| *value >= base_sequence)
15554                .ok_or_else(|| {
15555                    invalid_recorded_history(
15556                        "parallel_group_metadata_invalid",
15557                        sequence,
15558                        "selection member base within its group",
15559                        &payload.to_string(),
15560                        "selection history contains an invalid member base sequence",
15561                    )
15562                })?,
15563        )
15564    } else {
15565        None
15566    };
15567    let selection_member_size = if mode == "select" {
15568        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
15569        if member_size == 0 {
15570            return Err(invalid_recorded_history(
15571                "parallel_group_metadata_invalid",
15572                sequence,
15573                "positive selection member size",
15574                &payload.to_string(),
15575                "selection history contains an invalid member size",
15576            ));
15577        }
15578        Some(member_size)
15579    } else {
15580        None
15581    };
15582    let selection_member_kind = if mode == "select" {
15583        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
15584            invalid_recorded_history(
15585                "parallel_group_metadata_invalid",
15586                sequence,
15587                "selection member operation kind",
15588                &payload.to_string(),
15589                "selection history is missing its authored member kind",
15590            )
15591        })?;
15592        if !matches!(
15593            kind.as_str(),
15594            "activity" | "child" | "timer" | "signal" | "condition" | "group"
15595        ) {
15596            return Err(invalid_recorded_history(
15597                "parallel_group_metadata_invalid",
15598                sequence,
15599                "activity, child, timer, signal, condition, or group selection member kind",
15600                &kind,
15601                "selection history contains an unsupported member kind",
15602            ));
15603        }
15604        Some(kind)
15605    } else {
15606        None
15607    };
15608    if let (Some(member_base), Some(member_size)) =
15609        (selection_member_base_sequence, selection_member_size)
15610    {
15611        let member_end = member_base
15612            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
15613            .ok_or_else(|| {
15614                invalid_recorded_history(
15615                    "parallel_group_metadata_invalid",
15616                    sequence,
15617                    "bounded selection member range",
15618                    &payload.to_string(),
15619                    "selection member range overflowed",
15620                )
15621            })?;
15622        let group_end = base_sequence
15623            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
15624            .unwrap_or(u64::MAX);
15625        if sequence < member_base || sequence >= member_end || member_end > group_end {
15626            return Err(invalid_recorded_history(
15627                "parallel_group_metadata_invalid",
15628                sequence,
15629                "workflow sequence within one bounded selection member",
15630                &payload.to_string(),
15631                "selection member range does not contain its durable leaf",
15632            ));
15633        }
15634    }
15635    Ok(ParallelGroupMetadata {
15636        parallel_group_id: group_id,
15637        parallel_group_kind: kind,
15638        parallel_group_base_sequence: base_sequence,
15639        parallel_group_size: size,
15640        parallel_group_index: index,
15641        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
15642        selection_member_key,
15643        selection_member_index,
15644        selection_member_base_sequence,
15645        selection_member_size,
15646        selection_member_kind,
15647    })
15648}
15649
15650fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
15651    payload
15652        .get(field)
15653        .and_then(value_as_u64)
15654        .and_then(|value| usize::try_from(value).ok())
15655        .ok_or_else(|| {
15656            invalid_recorded_history(
15657                "parallel_group_metadata_invalid",
15658                sequence,
15659                &format!("non-negative integer {field}"),
15660                &payload.to_string(),
15661                "selection history contains invalid member metadata",
15662            )
15663        })
15664}
15665
15666fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15667    match value {
15668        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15669        Some(value) => value_as_u64(value)
15670            .and_then(|value| usize::try_from(value).ok())
15671            .map(SelectionKey::Index)
15672            .ok_or_else(|| {
15673                invalid_recorded_history(
15674                    "selection_member_key_invalid",
15675                    sequence,
15676                    "non-empty string or non-negative integer member key",
15677                    &value.to_string(),
15678                    "selection history contains an invalid member key",
15679                )
15680            }),
15681        None => Err(invalid_recorded_history(
15682            "selection_member_key_missing",
15683            sequence,
15684            "selection_member_key",
15685            "<missing>",
15686            "selection history is missing its stable member key",
15687        )),
15688    }
15689}
15690
15691fn recorded_parallel_group_path(
15692    events: &[&HistoryEvent],
15693    sequence: u64,
15694) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15695    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15696    for event in events {
15697        let payload = &event.payload;
15698        let has_metadata = payload.get("parallel_group_path").is_some()
15699            || payload.get("parallel_group_id").is_some()
15700            || payload.get("parallel_group_kind").is_some()
15701            || payload.get("parallel_group_base_sequence").is_some()
15702            || payload.get("parallel_group_size").is_some()
15703            || payload.get("parallel_group_index").is_some()
15704            || payload.get("parallel_group_mode").is_some()
15705            || payload.get("selection_member_key").is_some();
15706        if !has_metadata {
15707            continue;
15708        }
15709
15710        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15711        let path = match payload.get("parallel_group_path") {
15712            None => vec![top_level.clone()],
15713            Some(Value::Array(entries)) if !entries.is_empty() => entries
15714                .iter()
15715                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15716                .collect::<Result<Vec<_>>>()?,
15717            Some(value) => {
15718                return Err(invalid_recorded_history(
15719                    "parallel_group_metadata_invalid",
15720                    sequence,
15721                    "non-empty parallel_group_path list",
15722                    &value.to_string(),
15723                    "parallel-group history contains an invalid group path",
15724                ));
15725            }
15726        };
15727        if path.last() != Some(&top_level) {
15728            return Err(invalid_recorded_history(
15729                "parallel_group_metadata_invalid",
15730                sequence,
15731                &serde_json::to_string(&path.last()).unwrap_or_default(),
15732                &serde_json::to_string(&top_level).unwrap_or_default(),
15733                "parallel-group top-level fields do not match the innermost path entry",
15734            ));
15735        }
15736        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15737            return Err(invalid_recorded_history(
15738                "parallel_group_history_conflict",
15739                sequence,
15740                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15741                &serde_json::to_string(&path).unwrap_or_default(),
15742                "parallel-group metadata changed between scheduling and resolution history",
15743            ));
15744        }
15745        recorded = Some(path);
15746    }
15747    Ok(recorded)
15748}
15749
15750fn recorded_commands(
15751    events: &[HistoryEvent],
15752    fallback_codec: &str,
15753    parent: WorkflowIdentity,
15754) -> Result<Vec<RecordedCommand>> {
15755    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15756    let mut last_new_sequence = None;
15757
15758    for event in events {
15759        let is_activity = matches!(
15760            event.event_type.as_str(),
15761            "ActivityScheduled"
15762                | "ActivityStarted"
15763                | "ActivityHeartbeatRecorded"
15764                | "ActivityRetryScheduled"
15765                | "ActivityCompleted"
15766                | "ActivityFailed"
15767                | "ActivityCancelled"
15768                | "ActivityTimedOut"
15769        );
15770        let is_workflow_timer = matches!(
15771            event.event_type.as_str(),
15772            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15773        ) && !is_internal_timer_event(event);
15774        let is_child_workflow = matches!(
15775            event.event_type.as_str(),
15776            "ChildWorkflowScheduled"
15777                | "ChildRunStarted"
15778                | "ChildRunCompleted"
15779                | "ChildRunFailed"
15780                | "ChildRunCancelled"
15781                | "ChildRunTerminated"
15782        );
15783        let is_signal_wait = is_recorded_signal_wait_event(event);
15784        let is_condition_wait = is_recorded_condition_wait_event(event);
15785        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15786        let is_side_effect = event.event_type == "SideEffectRecorded";
15787        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15788        let is_memo = event.event_type == "MemoUpserted";
15789        if !is_activity
15790            && !is_workflow_timer
15791            && !is_child_workflow
15792            && !is_signal_wait
15793            && !is_condition_wait
15794            && !is_search_attributes
15795            && !is_side_effect
15796            && !is_version_marker
15797            && !is_memo
15798        {
15799            continue;
15800        }
15801
15802        let sequence = durable_event_sequence(event).ok_or_else(|| {
15803            Error::NonDeterministicReplay(ReplayFailure::new(
15804                "durable_command_sequence_missing",
15805                None,
15806                Some("positive workflow sequence".to_string()),
15807                Some(event.event_type.clone()),
15808                "durable command history event has no workflow sequence",
15809            ))
15810        })?;
15811        if sequence == 0 {
15812            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15813                "durable_command_sequence_invalid",
15814                Some(sequence),
15815                Some("positive workflow sequence".to_string()),
15816                Some(sequence.to_string()),
15817                "durable command history uses an invalid workflow sequence",
15818            )));
15819        }
15820        if !events_by_sequence.contains_key(&sequence) {
15821            if let Some(previous) = last_new_sequence {
15822                if sequence < previous {
15823                    return Err(invalid_recorded_history(
15824                        "durable_command_sequence_mismatch",
15825                        sequence,
15826                        &format!("workflow sequence greater than {previous}"),
15827                        &sequence.to_string(),
15828                        "durable commands are not strictly ordered by their recorded workflow sequence",
15829                    ));
15830                }
15831            }
15832            last_new_sequence = Some(sequence);
15833        }
15834        events_by_sequence.entry(sequence).or_default().push(event);
15835    }
15836
15837    let commands: Vec<RecordedCommand> = events_by_sequence
15838        .into_iter()
15839        .map(|(sequence, sequence_events)| {
15840            let activity_events: Vec<_> = sequence_events
15841                .iter()
15842                .copied()
15843                .filter(|event| event.event_type.starts_with("Activity"))
15844                .collect();
15845            let timer_events: Vec<_> = sequence_events
15846                .iter()
15847                .copied()
15848                .filter(|event| event.event_type.starts_with("Timer"))
15849                .collect();
15850            let child_events: Vec<_> = sequence_events
15851                .iter()
15852                .copied()
15853                .filter(|event| {
15854                    event.event_type == "ChildWorkflowScheduled"
15855                        || event.event_type.starts_with("ChildRun")
15856                })
15857                .collect();
15858            let signal_wait_events: Vec<_> = sequence_events
15859                .iter()
15860                .copied()
15861                .filter(|event| is_recorded_signal_wait_event(event))
15862                .collect();
15863            let condition_wait_events: Vec<_> = sequence_events
15864                .iter()
15865                .copied()
15866                .filter(|event| is_recorded_condition_wait_event(event))
15867                .collect();
15868            let search_attribute_events: Vec<_> = sequence_events
15869                .iter()
15870                .copied()
15871                .filter(|event| event.event_type == "SearchAttributesUpserted")
15872                .collect();
15873            let side_effect_events: Vec<_> = sequence_events
15874                .iter()
15875                .copied()
15876                .filter(|event| event.event_type == "SideEffectRecorded")
15877                .collect();
15878            let version_marker_events: Vec<_> = sequence_events
15879                .iter()
15880                .copied()
15881                .filter(|event| event.event_type == "VersionMarkerRecorded")
15882                .collect();
15883            let memo_events: Vec<_> = sequence_events
15884                .iter()
15885                .copied()
15886                .filter(|event| event.event_type == "MemoUpserted")
15887                .collect();
15888
15889            let command_kind_count = usize::from(!activity_events.is_empty())
15890                + usize::from(!timer_events.is_empty())
15891                + usize::from(!child_events.is_empty())
15892                + usize::from(!signal_wait_events.is_empty())
15893                + usize::from(!condition_wait_events.is_empty())
15894                + usize::from(!search_attribute_events.is_empty())
15895                + usize::from(!side_effect_events.is_empty())
15896                + usize::from(!version_marker_events.is_empty())
15897                + usize::from(!memo_events.is_empty());
15898            if command_kind_count > 1 {
15899                let actual = [
15900                    (!activity_events.is_empty()).then_some("activity"),
15901                    (!timer_events.is_empty()).then_some("timer"),
15902                    (!child_events.is_empty()).then_some("child workflow"),
15903                    (!signal_wait_events.is_empty()).then_some("signal wait"),
15904                    (!condition_wait_events.is_empty()).then_some("condition wait"),
15905                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
15906                    (!side_effect_events.is_empty()).then_some("side effect"),
15907                    (!version_marker_events.is_empty()).then_some("version marker"),
15908                    (!memo_events.is_empty()).then_some("memo upsert"),
15909                ]
15910                .into_iter()
15911                .flatten()
15912                .collect::<Vec<_>>()
15913                .join(" and ");
15914                return Err(invalid_recorded_history(
15915                    "durable_command_sequence_collision",
15916                    sequence,
15917                    "one durable command kind",
15918                    &actual,
15919                    "one workflow sequence records more than one durable command kind",
15920                ));
15921            }
15922
15923            if !activity_events.is_empty() {
15924                let parallel_group_path =
15925                    recorded_parallel_group_path(&activity_events, sequence)?;
15926                let scheduled_count = activity_events
15927                    .iter()
15928                    .filter(|event| event.event_type == "ActivityScheduled")
15929                    .count();
15930                if scheduled_count > 1 {
15931                    return Err(invalid_recorded_history(
15932                        "duplicate_activity_schedule",
15933                        sequence,
15934                        "at most one ActivityScheduled event",
15935                        "multiple ActivityScheduled events",
15936                        "activity history schedules more than one command at one workflow sequence",
15937                    ));
15938                }
15939                let activity_type = activity_events.iter().find_map(|event| {
15940                    event
15941                        .payload
15942                        .get("activity_type")
15943                        .or_else(|| event.payload.get("activity_name"))
15944                        .and_then(Value::as_str)
15945                        .map(str::to_string)
15946                });
15947                if activity_events.iter().filter_map(|event| {
15948                    event
15949                        .payload
15950                        .get("activity_type")
15951                        .or_else(|| event.payload.get("activity_name"))
15952                        .and_then(Value::as_str)
15953                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
15954                    return Err(invalid_recorded_history(
15955                        "activity_identity_mismatch",
15956                        sequence,
15957                        activity_type.as_deref().unwrap_or("one activity identity"),
15958                        "conflicting activity identities",
15959                        "activity lifecycle events at one workflow sequence disagree on identity",
15960                    ));
15961                }
15962                let terminal: Vec<_> = activity_events
15963                    .iter()
15964                    .copied()
15965                    .filter(|event| {
15966                        matches!(
15967                            event.event_type.as_str(),
15968                            "ActivityCompleted"
15969                                | "ActivityFailed"
15970                                | "ActivityCancelled"
15971                                | "ActivityTimedOut"
15972                        )
15973                    })
15974                    .collect();
15975                let duplicate_delivery = terminal.first().is_some_and(|first| {
15976                    terminal.iter().all(|event| {
15977                        event.event_type == first.event_type && event.payload == first.payload
15978                    })
15979                });
15980                if terminal.len() > 1 && !duplicate_delivery {
15981                    return Err(invalid_recorded_history(
15982                        "duplicate_activity_terminal_event",
15983                        sequence,
15984                        "at most one terminal activity event",
15985                        "multiple terminal activity events",
15986                        "activity history settles one command more than once",
15987                    ));
15988                }
15989                let outcome = terminal
15990                    .first()
15991                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
15992                    .transpose()?;
15993                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
15994                let activity_snapshot = activity_events
15995                    .iter()
15996                    .find(|event| event.event_type == "ActivityScheduled")
15997                    .and_then(|event| event.payload.get("activity"))
15998                    .and_then(Value::as_object);
15999                let options = Some(match activity_snapshot {
16000                    Some(activity) => RecordedActivityOptions {
16001                        task_queue: recorded_optional_string(activity, "queue"),
16002                        execution_mode,
16003                        retry_policy: recorded_activity_retry_snapshot(
16004                            activity.get("retry_policy"),
16005                        ),
16006                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16007                    },
16008                    None => RecordedActivityOptions {
16009                        task_queue: RecordedSnapshotValue::Unknown,
16010                        execution_mode,
16011                        retry_policy: recorded_activity_retry_snapshot(None),
16012                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16013                    },
16014                });
16015                return Ok(RecordedCommand::Activity {
16016                    sequence,
16017                    activity_type,
16018                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
16019                    options,
16020                    outcome,
16021                    parallel_group_path,
16022                });
16023            }
16024
16025            if !child_events.is_empty() {
16026                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
16027                let scheduled: Vec<_> = child_events
16028                    .iter()
16029                    .copied()
16030                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
16031                    .collect();
16032                if scheduled.len() != 1 {
16033                    return Err(invalid_recorded_history(
16034                        "child_workflow_schedule_missing_or_duplicate",
16035                        sequence,
16036                        "one ChildWorkflowScheduled event",
16037                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
16038                        "child workflow replay requires exactly one recorded schedule event",
16039                    ));
16040                }
16041                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
16042                let workflow_type = child_events.iter().find_map(|event| {
16043                    event
16044                        .payload
16045                        .get("child_workflow_type")
16046                        .or_else(|| event.payload.get("workflow_type"))
16047                        .and_then(Value::as_str)
16048                        .filter(|value| !value.is_empty())
16049                        .map(str::to_string)
16050                });
16051                if child_events
16052                    .iter()
16053                    .filter_map(|event| {
16054                        event
16055                            .payload
16056                            .get("child_workflow_type")
16057                            .or_else(|| event.payload.get("workflow_type"))
16058                            .and_then(Value::as_str)
16059                    })
16060                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
16061                {
16062                    return Err(invalid_recorded_history(
16063                        "child_workflow_identity_mismatch",
16064                        sequence,
16065                        workflow_type
16066                            .as_deref()
16067                            .unwrap_or("one child workflow type"),
16068                        "conflicting child workflow types",
16069                        "child workflow lifecycle events at one sequence disagree on type",
16070                    ));
16071                }
16072                let mut outcomes = child_workflow_outcomes(
16073                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
16074                    fallback_codec,
16075                    parent.clone(),
16076                )?;
16077                let terminal_events = child_events
16078                    .iter()
16079                    .copied()
16080                    .filter(|event| event.event_type.starts_with("ChildRun"))
16081                    .collect::<Vec<_>>();
16082                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
16083                    terminal_events.iter().all(|event| {
16084                        event.event_type == first.event_type && event.payload == first.payload
16085                    })
16086                });
16087                if outcomes.len() > 1 && !duplicate_delivery {
16088                    return Err(invalid_recorded_history(
16089                        "duplicate_child_workflow_terminal_event",
16090                        sequence,
16091                        "at most one terminal child event",
16092                        "multiple terminal child events",
16093                        "child workflow history settles one command more than once",
16094                    ));
16095                }
16096                return Ok(RecordedCommand::ChildWorkflow {
16097                    sequence,
16098                    workflow_type,
16099                    policies,
16100                    outcome: outcomes.pop(),
16101                    parallel_group_path,
16102                });
16103            }
16104
16105            if !signal_wait_events.is_empty() {
16106                let opened: Vec<_> = signal_wait_events
16107                    .iter()
16108                    .copied()
16109                    .filter(|event| event.event_type == "SignalWaitOpened")
16110                    .collect();
16111                if opened.len() != 1 {
16112                    return Err(invalid_recorded_history(
16113                        "signal_wait_open_missing_or_duplicate",
16114                        sequence,
16115                        "one SignalWaitOpened event",
16116                        &format!("{} SignalWaitOpened events", opened.len()),
16117                        "signal replay requires exactly one canonical wait-open event",
16118                    ));
16119                }
16120
16121                let applied: Vec<_> = signal_wait_events
16122                    .iter()
16123                    .copied()
16124                    .filter(|event| event.event_type == "SignalApplied")
16125                    .collect();
16126                if applied.len() > 1 {
16127                    return Err(invalid_recorded_history(
16128                        "duplicate_signal_wait_apply",
16129                        sequence,
16130                        "at most one SignalApplied event",
16131                        "multiple SignalApplied events",
16132                        "signal history applies one durable wait more than once",
16133                    ));
16134                }
16135
16136                let signal_names = signal_wait_events
16137                    .iter()
16138                    .map(|event| required_signal_wait_name(event, sequence))
16139                    .collect::<Result<Vec<_>>>()?;
16140                let signal_name = signal_names
16141                    .first()
16142                    .expect("signal wait events are not empty")
16143                    .clone();
16144                if signal_names.iter().any(|candidate| candidate != &signal_name) {
16145                    return Err(invalid_recorded_history(
16146                        "signal_wait_identity_mismatch",
16147                        sequence,
16148                        &signal_name,
16149                        "conflicting signal names",
16150                        "signal wait lifecycle events at one workflow sequence disagree on identity",
16151                    ));
16152                }
16153                let value = applied
16154                    .first()
16155                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
16156                    .transpose()?;
16157                return Ok(RecordedCommand::SignalWait {
16158                    sequence,
16159                    signal_name,
16160                    value,
16161                    parallel_group_path: recorded_parallel_group_path(
16162                        &signal_wait_events,
16163                        sequence,
16164                    )?,
16165                });
16166            }
16167
16168            if !condition_wait_events.is_empty() {
16169                return recorded_condition_wait(
16170                    sequence,
16171                    &condition_wait_events,
16172                    events,
16173                );
16174            }
16175
16176            if !search_attribute_events.is_empty() {
16177                if search_attribute_events.len() != 1 {
16178                    return Err(invalid_recorded_history(
16179                        "duplicate_search_attribute_update",
16180                        sequence,
16181                        "one SearchAttributesUpserted event",
16182                        &format!(
16183                            "{} SearchAttributesUpserted events",
16184                            search_attribute_events.len()
16185                        ),
16186                        "search-attribute history records one workflow command more than once",
16187                    ));
16188                }
16189                let payload = &search_attribute_events[0].payload;
16190                let attributes = payload
16191                    .get("attributes")
16192                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
16193                    .cloned()
16194                    .ok_or_else(|| {
16195                        invalid_recorded_history(
16196                            "search_attribute_update_missing",
16197                            sequence,
16198                            "non-empty attributes object",
16199                            "missing or invalid attributes",
16200                            "search-attribute history is missing its recorded mutation",
16201                        )
16202                    })?;
16203                let attribute_types =
16204                    recorded_search_attribute_types(payload, &attributes, sequence)?;
16205                return Ok(RecordedCommand::SearchAttributes {
16206                    sequence,
16207                    attributes,
16208                    attribute_types,
16209                });
16210            }
16211
16212            if !side_effect_events.is_empty() {
16213                if side_effect_events.len() != 1 {
16214                    return Err(invalid_recorded_history(
16215                        "duplicate_side_effect_record",
16216                        sequence,
16217                        "one SideEffectRecorded event",
16218                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
16219                        "side-effect history records one workflow command more than once",
16220                    ));
16221                }
16222                let event = side_effect_events[0];
16223                let result = event.payload.get("result").ok_or_else(|| {
16224                    invalid_recorded_history(
16225                        "side_effect_result_missing",
16226                        sequence,
16227                        "recorded result payload",
16228                        "missing result",
16229                        "side-effect history is missing its recorded value",
16230                    )
16231                })?;
16232                let has_published_envelope = result.as_str().is_some()
16233                    || result.as_object().is_some_and(|envelope| {
16234                        envelope.get("codec").and_then(Value::as_str).is_some()
16235                            && envelope.get("blob").and_then(Value::as_str).is_some()
16236                    });
16237                if !has_published_envelope {
16238                    return Err(invalid_recorded_history(
16239                        "side_effect_payload_malformed",
16240                        sequence,
16241                        "payload blob or {codec, blob} envelope",
16242                        &result.to_string(),
16243                        "side-effect history result does not use a published payload envelope",
16244                    ));
16245                }
16246                let codec = event
16247                    .payload
16248                    .get("payload_codec")
16249                    .and_then(Value::as_str)
16250                    .unwrap_or(fallback_codec);
16251                let value = decode_wire_avro_value(result, codec).map_err(|error| {
16252                    if error.to_string().contains("unsupported_payload_codec") {
16253                        return error;
16254                    }
16255
16256                    invalid_recorded_history(
16257                        "side_effect_payload_incompatible",
16258                        sequence,
16259                        &format!("valid {codec} payload envelope"),
16260                        &error.to_string(),
16261                        "side-effect history payload cannot be decoded with its recorded codec",
16262                    )
16263                })?;
16264                return Ok(RecordedCommand::SideEffect { sequence, value });
16265            }
16266
16267            if !version_marker_events.is_empty() {
16268                if version_marker_events.len() != 1 {
16269                    return Err(invalid_recorded_history(
16270                        "duplicate_version_marker_record",
16271                        sequence,
16272                        "one VersionMarkerRecorded event",
16273                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
16274                        "version-marker history records one workflow command more than once",
16275                    ));
16276                }
16277                let payload = &version_marker_events[0].payload;
16278                let change_id = payload
16279                    .get("change_id")
16280                    .and_then(Value::as_str)
16281                    .filter(|value| !value.is_empty())
16282                    .map(str::to_string)
16283                    .ok_or_else(|| {
16284                        invalid_recorded_history(
16285                            "version_marker_field_missing",
16286                            sequence,
16287                            "non-empty change_id",
16288                            "missing or invalid change_id",
16289                            "version-marker history is missing its stable change ID",
16290                        )
16291                    })?;
16292                let version = required_version_i32(payload, "version", sequence)?;
16293                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
16294                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
16295                if min_supported > max_supported || version < min_supported || version > max_supported {
16296                    return Err(invalid_recorded_history(
16297                        "version_marker_history_range_invalid",
16298                        sequence,
16299                        "min_supported <= version <= max_supported",
16300                        &format!("{min_supported} <= {version} <= {max_supported}"),
16301                        "recorded version marker contains an internally incompatible range",
16302                    ));
16303                }
16304                return Ok(RecordedCommand::VersionMarker {
16305                    sequence,
16306                    change_id,
16307                    version,
16308                });
16309            }
16310
16311            if !memo_events.is_empty() {
16312                if memo_events.len() != 1 {
16313                    return Err(invalid_recorded_history(
16314                        "duplicate_memo_upsert_record",
16315                        sequence,
16316                        "one MemoUpserted event",
16317                        &format!("{} MemoUpserted events", memo_events.len()),
16318                        "memo history records one workflow update more than once",
16319                    ));
16320                }
16321                let payload = &memo_events[0].payload;
16322                let entries = payload.get("entries").cloned().ok_or_else(|| {
16323                    invalid_recorded_history(
16324                        "memo_entries_missing",
16325                        sequence,
16326                        "memo entries object",
16327                        "missing entries",
16328                        "MemoUpserted history is missing replay identity entries",
16329                    )
16330                })?;
16331                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
16332                    invalid_recorded_history(
16333                        "memo_entries_invalid",
16334                        sequence,
16335                        "valid canonical memo entries",
16336                        &error.to_string(),
16337                        "MemoUpserted history contains invalid replay identity entries",
16338                    )
16339                })?;
16340                let merged = payload.get("merged").cloned().ok_or_else(|| {
16341                    invalid_recorded_history(
16342                        "memo_merged_projection_missing",
16343                        sequence,
16344                        "merged memo projection",
16345                        "missing merged",
16346                        "MemoUpserted history is missing its merged projection",
16347                    )
16348                })?;
16349                decode_memo_history_map(&merged, false).map_err(|error| {
16350                    invalid_recorded_history(
16351                        "memo_merged_projection_invalid",
16352                        sequence,
16353                        "valid merged memo projection",
16354                        &error.to_string(),
16355                        "MemoUpserted history contains an invalid merged projection",
16356                    )
16357                })?;
16358
16359                return Ok(RecordedCommand::Memo { sequence, entries });
16360            }
16361            let scheduled: Vec<_> = timer_events
16362                .iter()
16363                .copied()
16364                .filter(|event| event.event_type == "TimerScheduled")
16365                .collect();
16366            let fired: Vec<_> = timer_events
16367                .iter()
16368                .copied()
16369                .filter(|event| event.event_type == "TimerFired")
16370                .collect();
16371            if scheduled.len() != 1 {
16372                return Err(invalid_recorded_history(
16373                    "timer_schedule_missing_or_duplicate",
16374                    sequence,
16375                    "one TimerScheduled event",
16376                    &format!("{} TimerScheduled events", scheduled.len()),
16377                    "timer replay requires exactly one recorded schedule event",
16378                ));
16379            }
16380            if fired.len() > 1 {
16381                return Err(invalid_recorded_history(
16382                    "duplicate_timer_fire",
16383                    sequence,
16384                    "at most one TimerFired event",
16385                    "multiple TimerFired events",
16386                    "timer history contains more than one fire event for a workflow sequence",
16387                ));
16388            }
16389
16390            let scheduled = scheduled[0];
16391            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16392            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16393            if let Some(fired) = fired.first() {
16394                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16395                if fired_timer_id != timer_id {
16396                    return Err(invalid_recorded_history(
16397                        "timer_identity_mismatch",
16398                        sequence,
16399                        &timer_id,
16400                        &fired_timer_id,
16401                        "TimerFired does not correspond to the recorded TimerScheduled event",
16402                    ));
16403                }
16404                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16405                if fired_delay != delay_seconds {
16406                    return Err(invalid_recorded_history(
16407                        "timer_history_delay_mismatch",
16408                        sequence,
16409                        &delay_seconds.to_string(),
16410                        &fired_delay.to_string(),
16411                        "TimerScheduled and TimerFired record different delays",
16412                    ));
16413                }
16414            }
16415
16416            Ok(RecordedCommand::Timer {
16417                sequence,
16418                delay_seconds,
16419                fired: !fired.is_empty(),
16420                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
16421            })
16422        })
16423        .collect::<Result<_>>()?;
16424
16425    let mut marker_decisions = HashMap::new();
16426    for command in &commands {
16427        if let RecordedCommand::VersionMarker {
16428            sequence,
16429            change_id,
16430            version,
16431        } = command
16432        {
16433            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
16434                if version != first_version {
16435                    return Err(invalid_recorded_history(
16436                        "version_marker_conflict",
16437                        *sequence,
16438                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
16439                        &format!("version {version} at sequence {sequence}"),
16440                        "workflow history contains conflicting decisions for one stable change ID",
16441                    ));
16442                }
16443            } else {
16444                marker_decisions.insert(change_id.clone(), (*version, *sequence));
16445            }
16446        }
16447    }
16448
16449    Ok(commands)
16450}
16451
16452fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
16453    payload
16454        .get(field)
16455        .and_then(Value::as_i64)
16456        .and_then(|value| i32::try_from(value).ok())
16457        .ok_or_else(|| {
16458            invalid_recorded_history(
16459                "version_marker_field_missing",
16460                sequence,
16461                &format!("integer {field}"),
16462                "missing or out-of-range integer",
16463                "version-marker history is missing a required integer field",
16464            )
16465        })
16466}
16467
16468fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
16469    event
16470        .payload
16471        .get("sequence")
16472        .or_else(|| event.payload.get("workflow_sequence"))
16473        .or_else(|| event.raw.get("sequence"))
16474        .or_else(|| event.raw.get("workflow_sequence"))
16475        .and_then(value_as_u64)
16476}
16477
16478fn is_internal_timer_event(event: &HistoryEvent) -> bool {
16479    matches!(
16480        event
16481            .payload
16482            .get("timer_kind")
16483            .or_else(|| event.raw.get("timer_kind"))
16484            .and_then(Value::as_str),
16485        Some("condition_timeout" | "signal_timeout")
16486    )
16487}
16488
16489fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
16490    matches!(
16491        event.event_type.as_str(),
16492        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16493    )
16494}
16495
16496fn recorded_condition_wait(
16497    sequence: u64,
16498    condition_events: &[&HistoryEvent],
16499    all_events: &[HistoryEvent],
16500) -> Result<RecordedCommand> {
16501    let opened = condition_events
16502        .iter()
16503        .copied()
16504        .filter(|event| event.event_type == "ConditionWaitOpened")
16505        .collect::<Vec<_>>();
16506    if opened.len() != 1 {
16507        return Err(invalid_recorded_history(
16508            "condition_wait_open_missing_or_duplicate",
16509            sequence,
16510            "one ConditionWaitOpened event",
16511            &format!("{} ConditionWaitOpened events", opened.len()),
16512            "condition replay requires exactly one canonical wait-open event",
16513        ));
16514    }
16515    let terminal = condition_events
16516        .iter()
16517        .copied()
16518        .filter(|event| {
16519            matches!(
16520                event.event_type.as_str(),
16521                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16522            )
16523        })
16524        .collect::<Vec<_>>();
16525    if terminal.len() > 1 {
16526        return Err(invalid_recorded_history(
16527            "duplicate_condition_wait_terminal_event",
16528            sequence,
16529            "at most one condition terminal event",
16530            "multiple condition terminal events",
16531            "condition history settles one durable wait more than once",
16532        ));
16533    }
16534
16535    let opened = opened[0];
16536    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
16537    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
16538    for event in condition_events
16539        .iter()
16540        .copied()
16541        .filter(|event| !std::ptr::eq(*event, opened))
16542    {
16543        let event_wait_id = required_condition_wait_id(event, sequence)?;
16544        if event_wait_id != condition_wait_id {
16545            return Err(invalid_recorded_history(
16546                "condition_wait_id_mismatch",
16547                sequence,
16548                &condition_wait_id,
16549                &event_wait_id,
16550                "condition lifecycle events at one sequence disagree on wait identity",
16551            ));
16552        }
16553        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
16554        if event_occurrence_id != occurrence_id {
16555            return Err(invalid_recorded_history(
16556                "condition_wait_occurrence_history_mismatch",
16557                sequence,
16558                &occurrence_id,
16559                &event_occurrence_id,
16560                "condition lifecycle events at one sequence disagree on authored occurrence identity",
16561            ));
16562        }
16563    }
16564
16565    let condition_key = optional_non_empty_history_string(opened, "condition_key");
16566    let predicate_identity = opened
16567        .payload
16568        .get("condition_definition_fingerprint")
16569        .and_then(Value::as_str)
16570        .filter(|value| !value.is_empty())
16571        .map(str::to_string)
16572        .ok_or_else(|| {
16573            invalid_recorded_history(
16574                "condition_wait_predicate_fingerprint_missing",
16575                sequence,
16576                "non-empty condition_definition_fingerprint",
16577                &opened.event_type,
16578                "canonical condition history is missing its predicate identity",
16579            )
16580        })?;
16581    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
16582    for event in condition_events
16583        .iter()
16584        .copied()
16585        .filter(|event| !std::ptr::eq(*event, opened))
16586    {
16587        for (field, opened_value) in [
16588            ("condition_key", condition_key.as_deref()),
16589            (
16590                "condition_definition_fingerprint",
16591                Some(predicate_identity.as_str()),
16592            ),
16593        ] {
16594            if let Some(value) = optional_non_empty_history_string(event, field) {
16595                if opened_value.is_some_and(|opened_value| opened_value != value) {
16596                    return Err(invalid_recorded_history(
16597                        "condition_wait_definition_history_mismatch",
16598                        sequence,
16599                        opened_value.unwrap_or_default(),
16600                        &value,
16601                        "condition lifecycle events disagree on the recorded definition",
16602                    ));
16603                }
16604            }
16605        }
16606        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
16607            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
16608                return Err(invalid_recorded_history(
16609                    "condition_wait_definition_history_mismatch",
16610                    sequence,
16611                    &format!("{}s", timeout_seconds.unwrap_or_default()),
16612                    &format!("{event_timeout}s"),
16613                    "condition lifecycle events disagree on the recorded timeout",
16614                ));
16615            }
16616        }
16617    }
16618
16619    let timeout_timer_events = all_events
16620        .iter()
16621        .filter(|event| {
16622            matches!(
16623                event.event_type.as_str(),
16624                "TimerScheduled" | "TimerCancelled" | "TimerFired"
16625            ) && event.payload.get("timer_kind").and_then(Value::as_str)
16626                == Some("condition_timeout")
16627                && event
16628                    .payload
16629                    .get("condition_wait_id")
16630                    .and_then(Value::as_str)
16631                    == Some(condition_wait_id.as_str())
16632        })
16633        .collect::<Vec<_>>();
16634    let scheduled = timeout_timer_events
16635        .iter()
16636        .copied()
16637        .filter(|event| event.event_type == "TimerScheduled")
16638        .collect::<Vec<_>>();
16639    let fired = timeout_timer_events
16640        .iter()
16641        .copied()
16642        .filter(|event| event.event_type == "TimerFired")
16643        .collect::<Vec<_>>();
16644    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
16645        return Err(invalid_recorded_history(
16646            "condition_wait_timeout_history_invalid",
16647            sequence,
16648            "one timeout schedule and at most one fire",
16649            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
16650            "condition timeout history has a missing or duplicate lifecycle event",
16651        ));
16652    }
16653    if let Some(scheduled) = scheduled.first() {
16654        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16655        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16656        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
16657            return Err(invalid_recorded_history(
16658                "condition_wait_timeout_delay_mismatch",
16659                sequence,
16660                &format!("{}s", timeout_seconds.unwrap_or_default()),
16661                &format!("{delay_seconds}s"),
16662                "condition timeout timer differs from the wait definition",
16663            ));
16664        }
16665        if let Some(fired) = fired.first() {
16666            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16667            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16668            if fired_timer_id != timer_id || fired_delay != delay_seconds {
16669                return Err(invalid_recorded_history(
16670                    "condition_wait_timeout_identity_mismatch",
16671                    sequence,
16672                    &format!("{timer_id}:{delay_seconds}s"),
16673                    &format!("{fired_timer_id}:{fired_delay}s"),
16674                    "condition timeout fire does not match its durable schedule",
16675                ));
16676            }
16677        }
16678    }
16679
16680    let result = terminal.first().map(|event| {
16681        if event.event_type == "ConditionWaitTimedOut" {
16682            ConditionWaitResult::TimedOut
16683        } else {
16684            ConditionWaitResult::Satisfied
16685        }
16686    });
16687    let result = if !fired.is_empty() {
16688        if result == Some(ConditionWaitResult::Satisfied) {
16689            return Err(invalid_recorded_history(
16690                "condition_wait_terminal_conflict",
16691                sequence,
16692                "one satisfied or timed-out outcome",
16693                "satisfied event and fired timeout",
16694                "condition history records conflicting terminal outcomes",
16695            ));
16696        }
16697        Some(ConditionWaitResult::TimedOut)
16698    } else {
16699        result
16700    };
16701
16702    Ok(RecordedCommand::ConditionWait {
16703        sequence,
16704        occurrence_id,
16705        condition_key,
16706        predicate_identity,
16707        timeout_seconds,
16708        result,
16709        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16710    })
16711}
16712
16713fn recorded_condition_group_path(
16714    condition_events: &[&HistoryEvent],
16715    all_events: &[HistoryEvent],
16716    sequence: u64,
16717) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16718    let opened = condition_events
16719        .iter()
16720        .copied()
16721        .find(|event| event.event_type == "ConditionWaitOpened")
16722        .expect("canonical condition opener is validated first");
16723    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16724    let previous_events = all_events
16725        .iter()
16726        .take_while(|event| !std::ptr::eq(*event, opened))
16727        .collect::<Vec<_>>();
16728    let originals = previous_events
16729        .iter()
16730        .copied()
16731        .filter(|event| event.event_type == "ConditionWaitOpened")
16732        .filter(|event| {
16733            event
16734                .payload
16735                .get("condition_wait_occurrence_id")
16736                .and_then(Value::as_str)
16737                == Some(occurrence.as_str())
16738        })
16739        .collect::<Vec<_>>();
16740    let Some(original) = originals.first().copied() else {
16741        return recorded_parallel_group_path(condition_events, sequence);
16742    };
16743    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16744    if authored_sequence == sequence {
16745        return recorded_parallel_group_path(condition_events, sequence);
16746    }
16747    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16748    if original_path.is_none() {
16749        return recorded_parallel_group_path(condition_events, sequence);
16750    }
16751    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16752    let identity_matches = [
16753        "condition_key",
16754        "condition_definition_fingerprint",
16755        "timeout_seconds",
16756    ]
16757    .iter()
16758    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16759    let previous = originals
16760        .iter()
16761        .copied()
16762        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16763        .max_by_key(|event| durable_event_sequence(event));
16764    let previously_satisfied = previous.is_some_and(|previous| {
16765        previous_events.iter().any(|event| {
16766            event.event_type == "ConditionWaitSatisfied"
16767                && event.payload.get("condition_wait_id")
16768                    == previous.payload.get("condition_wait_id")
16769                && event.payload.get("condition_wait_occurrence_id")
16770                    == previous.payload.get("condition_wait_occurrence_id")
16771                && durable_event_sequence(event) == durable_event_sequence(previous)
16772        })
16773    });
16774    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16775        return Err(invalid_recorded_history(
16776            "condition_wait_group_reopen_mismatch",
16777            sequence,
16778            "same authored condition and group path after a satisfied physical wait",
16779            &opened.payload.to_string(),
16780            "grouped condition reopen has no matching recorded predecessor",
16781        ));
16782    }
16783    Ok(reopened_path)
16784}
16785
16786fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16787    event
16788        .payload
16789        .get("condition_wait_occurrence_id")
16790        .and_then(Value::as_str)
16791        .filter(|value| !value.is_empty())
16792        .map(str::to_string)
16793        .ok_or_else(|| {
16794            invalid_recorded_history(
16795                "condition_wait_occurrence_id_missing",
16796                sequence,
16797                "non-empty condition_wait_occurrence_id",
16798                &event.event_type,
16799                "condition history is missing authored occurrence identity",
16800            )
16801        })
16802}
16803
16804fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16805    event
16806        .payload
16807        .get("condition_wait_id")
16808        .and_then(Value::as_str)
16809        .filter(|value| !value.is_empty())
16810        .map(str::to_string)
16811        .ok_or_else(|| {
16812            invalid_recorded_history(
16813                "condition_wait_id_missing",
16814                sequence,
16815                "non-empty condition_wait_id",
16816                &event.event_type,
16817                "canonical condition history is missing its durable wait identity",
16818            )
16819        })
16820}
16821
16822fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
16823    event
16824        .payload
16825        .get(field)
16826        .and_then(Value::as_str)
16827        .filter(|value| !value.is_empty())
16828        .map(str::to_string)
16829}
16830
16831fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
16832    match event.payload.get(field) {
16833        None | Some(Value::Null) => Ok(None),
16834        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
16835            invalid_recorded_history(
16836                "condition_wait_definition_invalid",
16837                sequence,
16838                &format!("non-negative integer {field}"),
16839                &value.to_string(),
16840                "condition history contains an invalid numeric definition field",
16841            )
16842        }),
16843    }
16844}
16845
16846fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
16847    event
16848        .payload
16849        .get("signal_name")
16850        .or_else(|| event.raw.get("signal_name"))
16851        .and_then(Value::as_str)
16852        .filter(|value| !value.is_empty())
16853        .map(str::to_string)
16854        .ok_or_else(|| {
16855            invalid_recorded_history(
16856                "signal_wait_name_missing",
16857                sequence,
16858                "non-empty signal_name",
16859                &event.event_type,
16860                "canonical signal-wait history is missing its signal identity",
16861            )
16862        })
16863}
16864
16865fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
16866    // Applying a buffered control-plane signal has no authored call sequence.
16867    // Its outer sequence orders history events and must not become a wait.
16868    if event.event_type == "SignalApplied"
16869        && event
16870            .payload
16871            .get("signal_wait_id")
16872            .and_then(Value::as_str)
16873            .is_some_and(|id| id.starts_with("signal-command:"))
16874        && event.payload.get("sequence").is_none()
16875        && event.payload.get("workflow_sequence").is_none()
16876    {
16877        return false;
16878    }
16879    matches!(
16880        event.event_type.as_str(),
16881        "SignalWaitOpened" | "SignalApplied"
16882    )
16883}
16884
16885fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
16886    event
16887        .payload
16888        .get(field)
16889        .and_then(Value::as_str)
16890        .filter(|value| !value.is_empty())
16891        .map(str::to_string)
16892        .ok_or_else(|| {
16893            invalid_recorded_history(
16894                "timer_history_field_missing",
16895                sequence,
16896                field,
16897                &event.event_type,
16898                "timer history is missing a required identity field",
16899            )
16900        })
16901}
16902
16903fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
16904    event
16905        .payload
16906        .get(field)
16907        .and_then(value_as_u64)
16908        .ok_or_else(|| {
16909            invalid_recorded_history(
16910                "timer_history_field_missing",
16911                sequence,
16912                field,
16913                &event.event_type,
16914                "timer history is missing a required numeric field",
16915            )
16916        })
16917}
16918
16919fn recorded_search_attribute_types(
16920    payload: &Value,
16921    attributes: &Value,
16922    sequence: u64,
16923) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
16924    let Some(raw_types) = payload.get("attribute_types") else {
16925        // This is the explicit compatibility rule for histories recorded
16926        // before typed identity was persisted. Values still constrain replay;
16927        // the unknown type snapshot does not assert a typed match.
16928        return Ok(RecordedSnapshotValue::Unknown);
16929    };
16930    let Some(raw_types) = raw_types.as_object() else {
16931        return Err(invalid_recorded_history(
16932            "search_attribute_types_malformed",
16933            sequence,
16934            "canonical attribute type map",
16935            &raw_types.to_string(),
16936            "search-attribute history contains malformed type identity",
16937        ));
16938    };
16939    let attribute_keys = attributes
16940        .as_object()
16941        .expect("recorded search attributes were validated as an object");
16942    let mut types = BTreeMap::new();
16943    for (key, value) in raw_types {
16944        let Some(attribute_type) = value.as_str() else {
16945            return Err(invalid_recorded_history(
16946                "search_attribute_types_malformed",
16947                sequence,
16948                "canonical string type name",
16949                &value.to_string(),
16950                "search-attribute history contains a non-string type identity",
16951            ));
16952        };
16953        if !attribute_keys.contains_key(key)
16954            || !matches!(
16955                attribute_type,
16956                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
16957            )
16958        {
16959            return Err(invalid_recorded_history(
16960                "search_attribute_types_malformed",
16961                sequence,
16962                "canonical types for keys present in attributes",
16963                &format!("{key}:{attribute_type}"),
16964                "search-attribute history contains unsupported or orphaned type identity",
16965            ));
16966        }
16967        types.insert(key.clone(), attribute_type.to_string());
16968    }
16969    Ok(RecordedSnapshotValue::Known(types))
16970}
16971
16972fn invalid_recorded_history(
16973    reason: &str,
16974    sequence: u64,
16975    expected: &str,
16976    actual: &str,
16977    message: &str,
16978) -> Error {
16979    Error::NonDeterministicReplay(ReplayFailure::new(
16980        reason,
16981        Some(sequence),
16982        Some(expected.to_string()),
16983        Some(actual.to_string()),
16984        message,
16985    ))
16986}
16987
16988type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
16989
16990fn activity_outcome(
16991    event: &HistoryEvent,
16992    fallback_codec: &str,
16993    recorded_activity_type: Option<String>,
16994) -> Result<ActivityOutcome> {
16995    if event.event_type == "ActivityCompleted" {
16996        let codec = event
16997            .payload
16998            .get("payload_codec")
16999            .and_then(Value::as_str)
17000            .unwrap_or(fallback_codec);
17001        return Ok(Ok(decode_wire_avro_value(
17002            event.payload.get("result").unwrap_or(&Value::Null),
17003            codec,
17004        )?));
17005    }
17006
17007    let payload = &event.payload;
17008    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
17009        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
17010        "ActivityCancelled" => (
17011            ActivityFailureKind::Cancelled,
17012            "cancelled",
17013            "activity was cancelled",
17014        ),
17015        "ActivityTimedOut" => (
17016            ActivityFailureKind::TimedOut,
17017            "timeout",
17018            "activity timed out",
17019        ),
17020        _ => unreachable!("activity_outcome is called only for terminal activity events"),
17021    };
17022    let exception = payload
17023        .get("exception")
17024        .filter(|value| !value.is_null())
17025        .cloned();
17026    let failure_category = payload_string(payload, "failure_category");
17027    let timeout_kind = payload_string(payload, "timeout_kind");
17028    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
17029        ActivityFailureKind::Failed => failure_category
17030            .clone()
17031            .unwrap_or_else(|| fallback_reason.to_string()),
17032        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
17033        ActivityFailureKind::TimedOut => timeout_kind
17034            .clone()
17035            .unwrap_or_else(|| fallback_reason.to_string()),
17036    });
17037    let message = payload_string(payload, "message")
17038        .or_else(|| {
17039            exception
17040                .as_ref()
17041                .and_then(|value| payload_string(value, "message"))
17042        })
17043        .unwrap_or_else(|| fallback_message.to_string());
17044
17045    Ok(Err(ActivityFailure {
17046        kind,
17047        reason,
17048        message,
17049        activity_execution_id: payload_string(payload, "activity_execution_id"),
17050        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
17051        activity_type: payload_string(payload, "activity_type")
17052            .or_else(|| payload_string(payload, "activity_name"))
17053            .or(recorded_activity_type),
17054        activity_class: payload_string(payload, "activity_class"),
17055        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
17056        failure_id: payload_string(payload, "failure_id"),
17057        failure_category,
17058        timeout_kind,
17059        non_retryable: payload
17060            .get("non_retryable")
17061            .and_then(Value::as_bool)
17062            .unwrap_or(false),
17063        exception_type: payload_string(payload, "exception_type").or_else(|| {
17064            exception
17065                .as_ref()
17066                .and_then(|value| payload_string(value, "type"))
17067        }),
17068        exception_class: payload_string(payload, "exception_class").or_else(|| {
17069            exception
17070                .as_ref()
17071                .and_then(|value| payload_string(value, "class"))
17072        }),
17073        code: payload
17074            .get("code")
17075            .filter(|value| !value.is_null())
17076            .cloned(),
17077        exception,
17078    }))
17079}
17080
17081type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
17082
17083fn child_workflow_outcomes(
17084    events: &[HistoryEvent],
17085    fallback_codec: &str,
17086    parent: WorkflowIdentity,
17087) -> Result<Vec<ChildWorkflowOutcome>> {
17088    let mut outcomes = Vec::new();
17089
17090    for event in events {
17091        let kind = match event.event_type.as_str() {
17092            "ChildRunCompleted" => None,
17093            "ChildRunFailed" => Some((
17094                ChildWorkflowFailureKind::Failed,
17095                "child_workflow",
17096                "child workflow failed",
17097            )),
17098            "ChildRunCancelled" => Some((
17099                ChildWorkflowFailureKind::Cancelled,
17100                "cancelled",
17101                "child workflow was cancelled",
17102            )),
17103            "ChildRunTerminated" => Some((
17104                ChildWorkflowFailureKind::Terminated,
17105                "terminated",
17106                "child workflow was terminated",
17107            )),
17108            _ => continue,
17109        };
17110        let payload = &event.payload;
17111        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
17112        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
17113        let child_workflow_type = payload_string(payload, "child_workflow_type");
17114
17115        if let Some((kind, reason, fallback_message)) = kind {
17116            let exception = payload
17117                .get("exception")
17118                .filter(|value| !value.is_null())
17119                .cloned();
17120            let message = payload_string(payload, "message")
17121                .or_else(|| {
17122                    exception
17123                        .as_ref()
17124                        .and_then(|value| payload_string(value, "message"))
17125                })
17126                .unwrap_or_else(|| fallback_message.to_string());
17127            let exception_type = payload_string(payload, "exception_type").or_else(|| {
17128                exception
17129                    .as_ref()
17130                    .and_then(|value| payload_string(value, "type"))
17131            });
17132            let exception_class = payload_string(payload, "exception_class").or_else(|| {
17133                exception
17134                    .as_ref()
17135                    .and_then(|value| payload_string(value, "class"))
17136            });
17137            outcomes.push(Err(ChildWorkflowFailure {
17138                kind,
17139                reason: reason.to_string(),
17140                message,
17141                parent_workflow_id: parent.workflow_id.clone(),
17142                parent_workflow_run_id: parent.run_id.clone(),
17143                child_workflow_id,
17144                child_workflow_run_id,
17145                child_workflow_type,
17146                failure_id: payload_string(payload, "failure_id"),
17147                failure_category: payload_string(payload, "failure_category"),
17148                exception_type,
17149                exception_class,
17150                non_retryable: payload
17151                    .get("non_retryable")
17152                    .and_then(Value::as_bool)
17153                    .unwrap_or(false),
17154                code: payload
17155                    .get("code")
17156                    .filter(|value| !value.is_null())
17157                    .cloned(),
17158                exception,
17159            }));
17160            continue;
17161        }
17162
17163        let codec = payload
17164            .get("payload_codec")
17165            .and_then(Value::as_str)
17166            .unwrap_or(fallback_codec);
17167        let result = payload
17168            .get("result")
17169            .or_else(|| payload.get("output"))
17170            .unwrap_or(&Value::Null);
17171        outcomes.push(Ok(ChildWorkflowAvroResult {
17172            parent: parent.clone(),
17173            child: WorkflowIdentity {
17174                workflow_id: child_workflow_id,
17175                run_id: child_workflow_run_id,
17176            },
17177            child_workflow_type,
17178            result: decode_wire_avro_value(result, codec)?,
17179        }));
17180    }
17181
17182    Ok(outcomes)
17183}
17184
17185fn payload_string(payload: &Value, key: &str) -> Option<String> {
17186    payload
17187        .get(key)
17188        .and_then(Value::as_str)
17189        .filter(|value| !value.is_empty())
17190        .map(str::to_string)
17191}
17192
17193fn recorded_activity_failure_boundary(
17194    ctx: &WorkflowContext,
17195    error: &Error,
17196) -> Option<(u64, String)> {
17197    let Error::ActivityFailed(failure) = error else {
17198        return None;
17199    };
17200    if failure.kind != ActivityFailureKind::Failed {
17201        return None;
17202    }
17203    let activity_execution_id = failure
17204        .activity_execution_id
17205        .as_deref()
17206        .filter(|value| !value.is_empty())?;
17207    let state = ctx.state.lock().ok()?;
17208    let mut matches = state.recorded_commands.iter().filter_map(|command| {
17209        let RecordedCommand::Activity {
17210            sequence,
17211            outcome: Some(Err(recorded_failure)),
17212            ..
17213        } = command
17214        else {
17215            return None;
17216        };
17217        (*sequence > 0 && recorded_failure == failure)
17218            .then_some((*sequence, activity_execution_id.to_string()))
17219    });
17220    let boundary = matches.next()?;
17221    matches.next().is_none().then_some(boundary)
17222}
17223
17224fn workflow_failure_command(
17225    error: &Error,
17226    failed_activity_boundary: Option<(u64, String)>,
17227) -> Value {
17228    let (exception_type, exception_class, properties) = match error {
17229        Error::ActivityFailed(failure) => (
17230            match failure.kind {
17231                ActivityFailureKind::Failed => "ActivityFailed",
17232                ActivityFailureKind::Cancelled => "ActivityCancelled",
17233                ActivityFailureKind::TimedOut => "ActivityTimedOut",
17234            },
17235            "durable_workflow::ActivityFailure",
17236            json!({
17237                "reason": failure.reason,
17238                "activity_execution_id": failure.activity_execution_id,
17239                "activity_attempt_id": failure.activity_attempt_id,
17240                "activity_type": failure.activity_type,
17241                "activity_class": failure.activity_class,
17242                "attempt_number": failure.attempt_number,
17243                "failure_id": failure.failure_id,
17244                "failure_category": failure.failure_category,
17245                "timeout_kind": failure.timeout_kind,
17246                "activity_non_retryable": failure.non_retryable,
17247                "activity_exception_type": failure.exception_type,
17248                "activity_exception_class": failure.exception_class,
17249                "activity_code": failure.code,
17250                "activity_exception": failure.exception,
17251            }),
17252        ),
17253        Error::ChildWorkflowFailed(failure) => (
17254            match failure.kind {
17255                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17256                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17257                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17258            },
17259            "durable_workflow::ChildWorkflowFailure",
17260            json!({
17261                "reason": failure.reason,
17262                "parent_workflow_id": failure.parent_workflow_id,
17263                "parent_workflow_run_id": failure.parent_workflow_run_id,
17264                "child_workflow_id": failure.child_workflow_id,
17265                "child_workflow_run_id": failure.child_workflow_run_id,
17266                "child_workflow_type": failure.child_workflow_type,
17267                "failure_id": failure.failure_id,
17268                "failure_category": failure.failure_category,
17269                "child_exception_type": failure.exception_type,
17270                "child_exception_class": failure.exception_class,
17271                "child_non_retryable": failure.non_retryable,
17272                "child_code": failure.code,
17273                "child_exception": failure.exception,
17274            }),
17275        ),
17276        Error::ParallelFailed(failure) => (
17277            "ParallelFailed",
17278            "durable_workflow::ParallelFailure",
17279            json!({
17280                "parallel_group_id": failure.group_id,
17281                "parallel_member_path": failure.member_path,
17282                "parallel_group_path": failure.group_path,
17283                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
17284                "cause_type": workflow_error_type(&failure.cause),
17285                "cause_message": failure.cause.to_string(),
17286            }),
17287        ),
17288        Error::SagaCompensationFailed(failure) => (
17289            "SagaCompensationFailed",
17290            "durable_workflow::SagaCompensationFailure",
17291            json!({
17292                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
17293                "initiating_failure_message": failure.initiating_failure.to_string(),
17294                "compensation_activity_type": failure.compensation_activity_type,
17295                "compensation_registration_order": failure.compensation_registration_order,
17296                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
17297                "compensation_failure_message": failure.compensation_failure.to_string(),
17298            }),
17299        ),
17300        Error::WorkflowCancellationRequested(_) => (
17301            "WorkflowCancellationRequested",
17302            "durable_workflow::WorkflowCancellationRequested",
17303            json!({"reason": "cancelled"}),
17304        ),
17305        Error::CooperativeCancellationRequested(cancellation) => (
17306            "WorkflowCancellationRequested",
17307            "durable_workflow::CooperativeCancellationRequested",
17308            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
17309                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
17310        ),
17311        Error::CancellationScopeRequested(cancellation) => (
17312            "WorkflowCancellationRequested",
17313            "durable_workflow::CancellationScopeRequested",
17314            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
17315                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
17316                "cancellation":cancellation.context.to_value()}),
17317        ),
17318        Error::NonDeterministicReplay(_) => (
17319            "NonDeterministicReplay",
17320            "durable_workflow::Error",
17321            Value::Null,
17322        ),
17323        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
17324    };
17325    let non_retryable = match error {
17326        Error::ActivityFailed(failure) => failure.non_retryable,
17327        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17328        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17329        Error::SagaCompensationFailed(failure) => {
17330            workflow_error_non_retryable(&failure.compensation_failure)
17331        }
17332        Error::WorkflowCancellationRequested(_)
17333        | Error::CooperativeCancellationRequested(_)
17334        | Error::CancellationScopeRequested(_) => true,
17335        Error::NonDeterministicReplay(_) => true,
17336        _ => false,
17337    };
17338
17339    let mut command = json!({
17340        "type": "fail_workflow",
17341        "message": error.to_string(),
17342        "exception_type": exception_type,
17343        "exception_class": exception_class,
17344        "non_retryable": non_retryable,
17345        "exception": {
17346            "type": exception_type,
17347            "class": exception_class,
17348            "message": error.to_string(),
17349            "properties": properties,
17350        }
17351    });
17352
17353    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
17354        command["failed_step_sequence"] = json!(sequence);
17355        command["failed_activity_execution_id"] = json!(activity_execution_id);
17356    }
17357
17358    command
17359}
17360
17361fn workflow_error_type(error: &Error) -> &'static str {
17362    match error {
17363        Error::ActivityFailed(failure) => match failure.kind {
17364            ActivityFailureKind::Failed => "ActivityFailed",
17365            ActivityFailureKind::Cancelled => "ActivityCancelled",
17366            ActivityFailureKind::TimedOut => "ActivityTimedOut",
17367        },
17368        Error::ChildWorkflowFailed(failure) => match failure.kind {
17369            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17370            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17371            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17372        },
17373        Error::ParallelFailed(_) => "ParallelFailed",
17374        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
17375        Error::WorkflowCancellationRequested(_)
17376        | Error::CooperativeCancellationRequested(_)
17377        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
17378        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
17379        _ => "RustWorkflowError",
17380    }
17381}
17382
17383fn workflow_error_non_retryable(error: &Error) -> bool {
17384    match error {
17385        Error::ActivityFailed(failure) => failure.non_retryable,
17386        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17387        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17388        Error::SagaCompensationFailed(failure) => {
17389            workflow_error_non_retryable(&failure.compensation_failure)
17390        }
17391        Error::WorkflowCancellationRequested(_)
17392        | Error::CooperativeCancellationRequested(_)
17393        | Error::CancellationScopeRequested(_)
17394        | Error::NonDeterministicReplay(_) => true,
17395        _ => false,
17396    }
17397}
17398
17399fn workflow_task_integrity_error(error: &Error) -> bool {
17400    matches!(
17401        error,
17402        Error::NonDeterministicReplay(_)
17403            | Error::Protocol(_)
17404            | Error::CancellationScopeExecutionUnavailable
17405            | Error::MissingWorkflowCommandIdentity
17406            | Error::WorkflowStatePoisoned
17407    )
17408}
17409
17410fn decode_signal_event_arguments(
17411    event: &HistoryEvent,
17412    fallback_codec: &str,
17413) -> Result<Vec<AvroValue>> {
17414    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17415    validate_payload_codec(codec)?;
17416    let raw = signal_history_payload(&event.payload);
17417    let decoded = match raw.filter(|value| !value.is_null()) {
17418        Some(value) => decode_wire_avro_value(value, codec)?,
17419        None => AvroValue::Array(Vec::new()),
17420    };
17421    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17422        unreachable!("normalize_avro_arguments always returns an array");
17423    };
17424    Ok(arguments)
17425}
17426
17427fn decode_update_event_arguments(
17428    event: &HistoryEvent,
17429    fallback_codec: &str,
17430) -> Result<Vec<AvroValue>> {
17431    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17432    validate_payload_codec(codec)?;
17433    let decoded = match event
17434        .payload
17435        .get("arguments")
17436        .filter(|value| !value.is_null())
17437    {
17438        Some(value) => decode_wire_avro_value(value, codec)?,
17439        None => AvroValue::Array(Vec::new()),
17440    };
17441    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17442        unreachable!("normalize_avro_arguments always returns an array");
17443    };
17444    Ok(arguments)
17445}
17446
17447fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17448    let Some(export_events) = task
17449        .history_export
17450        .as_ref()
17451        .and_then(|export| export.get("history_events"))
17452        .and_then(Value::as_array)
17453    else {
17454        return Ok(());
17455    };
17456
17457    if export_events.len() > task.history_events.len() {
17458        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
17459    }
17460
17461    Ok(())
17462}
17463
17464fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17465    let Some(export) = task.history_export.as_ref() else {
17466        return Ok(());
17467    };
17468    let signals = export
17469        .get("signals")
17470        .and_then(Value::as_array)
17471        .cloned()
17472        .unwrap_or_default();
17473    let activities = export
17474        .get("activities")
17475        .and_then(Value::as_array)
17476        .cloned()
17477        .unwrap_or_default();
17478    let export_codec = export
17479        .get("payloads")
17480        .and_then(|payloads| payloads.get("codec"))
17481        .and_then(Value::as_str)
17482        .unwrap_or(&task.payload_codec)
17483        .to_string();
17484    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
17485
17486    for event in &mut task.history_events {
17487        if event.event_type == "ActivityCompleted" {
17488            let sequence = event
17489                .payload
17490                .get("sequence")
17491                .or_else(|| event.payload.get("workflow_sequence"))
17492                .and_then(value_as_u64);
17493            let Some(activity) = sequence.and_then(|sequence| {
17494                activities.iter().find(|activity| {
17495                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
17496                })
17497            }) else {
17498                continue;
17499            };
17500            let Some(payload) = event.payload.as_object_mut() else {
17501                continue;
17502            };
17503            if missing_payload(payload.get("result")) {
17504                if let Some(result) = activity
17505                    .get("result")
17506                    .filter(|value| !missing_payload(Some(value)))
17507                {
17508                    payload.insert("result".to_string(), result.clone());
17509                }
17510            }
17511            for field in ["payload_codec", "activity_type"] {
17512                if payload
17513                    .get(field)
17514                    .and_then(Value::as_str)
17515                    .unwrap_or_default()
17516                    .is_empty()
17517                {
17518                    if let Some(value) = activity.get(field) {
17519                        payload.insert(field.to_string(), value.clone());
17520                    }
17521                }
17522            }
17523            continue;
17524        }
17525
17526        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
17527            continue;
17528        }
17529        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17530        let command_id = event
17531            .payload
17532            .get("workflow_command_id")
17533            .or_else(|| event.raw.get("workflow_command_id"))
17534            .and_then(Value::as_str);
17535        let signal_name = event
17536            .payload
17537            .get("signal_name")
17538            .and_then(Value::as_str)
17539            .unwrap_or_default()
17540            .to_string();
17541        let matched = signals
17542            .iter()
17543            .find(|signal| {
17544                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
17545            })
17546            .or_else(|| {
17547                signals.iter().find(|signal| {
17548                    command_id.is_some()
17549                        && signal.get("command_id").and_then(Value::as_str) == command_id
17550                })
17551            })
17552            .or_else(|| {
17553                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
17554                let signal = signals
17555                    .iter()
17556                    .filter(|signal| {
17557                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
17558                    })
17559                    .nth(*offset);
17560                if signal.is_some() {
17561                    *offset += 1;
17562                }
17563                signal
17564            });
17565        let Some(signal) = matched else {
17566            continue;
17567        };
17568        let signal_codec = signal
17569            .get("payload_codec")
17570            .and_then(Value::as_str)
17571            .unwrap_or(&export_codec);
17572        let Some(payload) = event.payload.as_object_mut() else {
17573            continue;
17574        };
17575        if missing_payload(payload.get("arguments")) {
17576            if let Some(arguments) = signal
17577                .get("arguments")
17578                .filter(|value| !missing_payload(Some(value)))
17579            {
17580                let envelope = match arguments {
17581                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
17582                    other => other.clone(),
17583                };
17584                payload.insert("arguments".to_string(), envelope);
17585            }
17586        }
17587        if payload
17588            .get("payload_codec")
17589            .and_then(Value::as_str)
17590            .unwrap_or_default()
17591            .is_empty()
17592        {
17593            payload.insert("payload_codec".to_string(), json!(signal_codec));
17594        }
17595    }
17596
17597    Ok(())
17598}
17599
17600fn missing_payload(value: Option<&Value>) -> bool {
17601    match value {
17602        None | Some(Value::Null) => true,
17603        Some(Value::String(value)) => value.is_empty(),
17604        Some(_) => false,
17605    }
17606}
17607
17608fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
17609    history_signal_events(
17610        &task.history_events,
17611        task.history_export.as_ref(),
17612        &task.payload_codec,
17613    )
17614}
17615
17616fn history_signal_events(
17617    history_events: &[HistoryEvent],
17618    history_export: Option<&Value>,
17619    payload_codec: &str,
17620) -> Result<Vec<QuerySignal>> {
17621    let export_signals = history_export
17622        .and_then(|export| export.get("signals"))
17623        .and_then(Value::as_array)
17624        .cloned()
17625        .unwrap_or_default();
17626    let export_codec = history_export
17627        .and_then(|export| export.get("payloads"))
17628        .and_then(|payloads| payloads.get("codec"))
17629        .and_then(Value::as_str)
17630        .unwrap_or(payload_codec);
17631    let mut name_offsets: HashMap<String, usize> = HashMap::new();
17632    let mut signals: Vec<QuerySignal> = Vec::new();
17633    let mut signal_indices = HashMap::new();
17634    let mut command_indices = HashMap::new();
17635
17636    for event in history_events {
17637        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
17638            continue;
17639        }
17640
17641        let name = event
17642            .payload
17643            .get("signal_name")
17644            .and_then(Value::as_str)
17645            .unwrap_or_default();
17646        if name.is_empty() {
17647            continue;
17648        }
17649        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17650        let command_id = event
17651            .payload
17652            .get("workflow_command_id")
17653            .or_else(|| event.raw.get("workflow_command_id"))
17654            .and_then(Value::as_str);
17655        let matched_export = export_signals
17656            .iter()
17657            .find(|candidate| {
17658                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
17659            })
17660            .or_else(|| {
17661                export_signals.iter().find(|candidate| {
17662                    command_id.is_some()
17663                        && candidate.get("command_id").and_then(Value::as_str) == command_id
17664                })
17665            })
17666            .or_else(|| {
17667                let offset = name_offsets.entry(name.to_string()).or_default();
17668                let candidate = export_signals
17669                    .iter()
17670                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
17671                    .nth(*offset);
17672                if candidate.is_some() {
17673                    *offset += 1;
17674                }
17675                candidate
17676            });
17677        let codec = event
17678            .payload
17679            .get("payload_codec")
17680            .and_then(Value::as_str)
17681            .or_else(|| {
17682                matched_export
17683                    .and_then(|signal| signal.get("payload_codec"))
17684                    .and_then(Value::as_str)
17685            })
17686            .unwrap_or(export_codec);
17687        let raw_arguments = signal_history_payload(&event.payload)
17688            .filter(|value| !value.is_null())
17689            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
17690        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
17691        let workflow_sequence = event
17692            .payload
17693            .get("workflow_sequence")
17694            .and_then(value_as_u64)
17695            .or_else(|| {
17696                matched_export
17697                    .and_then(|signal| signal.get("workflow_sequence"))
17698                    .and_then(value_as_u64)
17699            });
17700
17701        let id = signal_id.or_else(|| {
17702            matched_export
17703                .and_then(|signal| signal.get("id"))
17704                .and_then(Value::as_str)
17705        });
17706        let command_id = command_id.or_else(|| {
17707            matched_export
17708                .and_then(|signal| signal.get("command_id"))
17709                .and_then(Value::as_str)
17710        });
17711        let duplicate = id
17712            .and_then(|id| signal_indices.get(id))
17713            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
17714            .copied();
17715        let index = duplicate.unwrap_or(signals.len());
17716        if let Some(index) = duplicate {
17717            let original = &mut signals[index];
17718            let same_arguments = if event.event_type == "SignalApplied" {
17719                if let Some(value) = event.payload.get("value") {
17720                    let expected = match original.avro_arguments.as_slice() {
17721                        [] => AvroValue::Boolean(true),
17722                        [value] => value.clone(),
17723                        values => AvroValue::Array(values.to_vec()),
17724                    };
17725                    let applied = decode_wire_avro_value(value, codec)?;
17726                    applied == expected
17727                        || applied == AvroValue::Array(original.avro_arguments.clone())
17728                } else {
17729                    original.avro_arguments == avro_arguments
17730                }
17731            } else {
17732                original.avro_arguments == avro_arguments
17733            };
17734            if original.name != name
17735                || !same_arguments
17736                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
17737            {
17738                return Err(Error::Codec("conflicting committed signal identity".into()));
17739            }
17740            if original.id.is_none() {
17741                original.id = id.map(str::to_string);
17742            }
17743            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
17744        } else {
17745            signals.push(QuerySignal {
17746                id: id.map(str::to_string),
17747                name: name.to_string(),
17748                arguments,
17749                avro_arguments,
17750                workflow_sequence,
17751            });
17752        }
17753        if let Some(id) = id {
17754            signal_indices.insert(id.to_string(), index);
17755        }
17756        if let Some(id) = command_id {
17757            command_indices.insert(id.to_string(), index);
17758        }
17759    }
17760
17761    if signals.is_empty() {
17762        for signal in export_signals {
17763            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17764                continue;
17765            }
17766            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17767                continue;
17768            };
17769            let codec = signal
17770                .get("payload_codec")
17771                .and_then(Value::as_str)
17772                .unwrap_or(export_codec);
17773            let (arguments, avro_arguments) =
17774                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17775            signals.push(QuerySignal {
17776                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17777                name: name.to_string(),
17778                arguments,
17779                avro_arguments,
17780                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17781            });
17782        }
17783        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17784    }
17785
17786    Ok(signals)
17787}
17788
17789fn decode_query_signal_arguments(
17790    raw: Option<&Value>,
17791    codec: &str,
17792) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17793    validate_payload_codec(codec)?;
17794    let decoded = match raw.filter(|value| !value.is_null()) {
17795        Some(value) => decode_wire_avro_value(value, codec)?,
17796        None => AvroValue::Array(Vec::new()),
17797    };
17798    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17799        unreachable!("normalize_avro_arguments always returns an array");
17800    };
17801    let arguments = avro_arguments
17802        .iter()
17803        .cloned()
17804        .map(AvroValue::into_json)
17805        .collect::<Result<Vec<_>>>()?;
17806    Ok((arguments, avro_arguments))
17807}
17808
17809fn value_as_u64(value: &Value) -> Option<u64> {
17810    value
17811        .as_u64()
17812        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17813}
17814
17815#[cfg(test)]
17816mod tests {
17817    use super::*;
17818    mod activity_cancellation_policies;
17819    mod cancellation_scope_admission;
17820    mod cancellation_scope_authoring;
17821    mod cancellation_scope_history;
17822    mod cancellation_scope_opening;
17823    mod cancellation_scope_replay;
17824    mod child_workflow_policies;
17825    mod cooperative_cancellation;
17826    mod local_activity;
17827    mod runtime_payloads;
17828    mod runtime_uploads;
17829    mod version_marker_contract;
17830    mod worker_session;
17831    use std::{
17832        fs,
17833        io::{Read, Write},
17834        net::{SocketAddr, TcpListener, TcpStream},
17835        process::Command as ProcessCommand,
17836        sync::atomic::AtomicUsize,
17837        thread,
17838    };
17839
17840    #[derive(Clone, Copy, Debug)]
17841    enum InvalidTaskPayloadCodec {
17842        Missing,
17843        Null,
17844        NonString,
17845    }
17846
17847    impl InvalidTaskPayloadCodec {
17848        fn label(self) -> &'static str {
17849            match self {
17850                Self::Missing => "missing",
17851                Self::Null => "null",
17852                Self::NonString => "non-string",
17853            }
17854        }
17855
17856        fn apply(self, task: &mut Value) {
17857            let task = task.as_object_mut().expect("task fixture object");
17858            match self {
17859                Self::Missing => {
17860                    task.remove("payload_codec");
17861                }
17862                Self::Null => {
17863                    task.insert("payload_codec".to_string(), Value::Null);
17864                }
17865                Self::NonString => {
17866                    task.insert("payload_codec".to_string(), json!(42));
17867                }
17868            }
17869        }
17870    }
17871
17872    fn fixture_envelope(value: Value) -> Value {
17873        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
17874    }
17875
17876    fn fixture_blob(value: Value) -> String {
17877        encode_payload(&value, DEFAULT_CODEC)
17878            .expect("encode Avro test fixture")
17879            .blob
17880    }
17881
17882    #[test]
17883    fn client_builder_rejects_the_sdk_owned_api_suffix() {
17884        for base_url in [
17885            "http://127.0.0.1:8080/api",
17886            "http://localhost:8080/api/",
17887            "https://runtime.example.test/namespaces/orders/api",
17888        ] {
17889            let error = Client::builder(base_url)
17890                .build()
17891                .expect_err("SDK-owned /api suffix must be rejected during build");
17892
17893            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
17894            assert!(
17895                error.to_string().contains("SDK appends /api automatically"),
17896                "the validation error must explain how to fix the endpoint"
17897            );
17898        }
17899    }
17900
17901    #[test]
17902    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
17903        for (base_url, expected) in [
17904            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
17905            (
17906                "http://localhost:8080/durable-workflow/",
17907                "http://localhost:8080/durable-workflow",
17908            ),
17909            (
17910                "https://runtime.example.test/namespaces/orders",
17911                "https://runtime.example.test/namespaces/orders",
17912            ),
17913            (
17914                "https://runtime.example.test/gateway/api/namespaces/orders",
17915                "https://runtime.example.test/gateway/api/namespaces/orders",
17916            ),
17917            (
17918                "https://api.example.test/runtime/orders/",
17919                "https://api.example.test/runtime/orders",
17920            ),
17921        ] {
17922            let client = Client::builder(base_url)
17923                .build()
17924                .expect("Server and Cloud runtime base URL must remain valid");
17925
17926            assert_eq!(client.base_url, expected);
17927        }
17928    }
17929
17930    #[test]
17931    fn workflow_completion_uses_the_additive_command_protocol_floor() {
17932        assert_eq!(
17933            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
17934            MINIMUM_WORKER_PROTOCOL_VERSION
17935        );
17936        assert_eq!(
17937            workflow_completion_protocol_version(&[json!({
17938                "type": "upsert_search_attributes",
17939                "attributes": {"OrderStatus": "waiting"},
17940            })]),
17941            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
17942        );
17943        assert_eq!(
17944            workflow_completion_protocol_version(&[json!({
17945                "type": "upsert_search_attributes",
17946                "attributes": {"OrderStatus": "waiting"},
17947                "attribute_types": {"OrderStatus": "keyword"},
17948            })]),
17949            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
17950        );
17951        assert_eq!(
17952            workflow_completion_protocol_version(&[
17953                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
17954                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17955            ]),
17956            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
17957        );
17958        assert_eq!(
17959            workflow_completion_protocol_version(&[
17960                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
17961                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17962            ]),
17963            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
17964        );
17965        assert_eq!(
17966            workflow_completion_protocol_version(&[json!({
17967                "type": "open_condition_wait",
17968                "condition_wait_occurrence_id": "rust:condition-wait:0",
17969                "condition_key": "ready",
17970            })]),
17971            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17972        );
17973        assert_eq!(
17974            workflow_completion_protocol_version_with_message_streams(
17975                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
17976                true,
17977            ),
17978            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
17979        );
17980        assert_eq!(
17981            workflow_completion_protocol_version_with_message_streams(
17982                &[json!({
17983                    "type": "open_condition_wait",
17984                    "condition_wait_occurrence_id": "rust:condition-wait:0",
17985                    "condition_key": "ready",
17986                })],
17987                true,
17988            ),
17989            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17990        );
17991    }
17992
17993    #[test]
17994    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
17995        let manifest = portable_worker_affinity_capability_manifest();
17996
17997        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
17998            assert_eq!(manifest[capability]["supported"], json!(false));
17999            assert_eq!(
18000                manifest[capability]["minimum_protocol_version"],
18001                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
18002            );
18003            assert!(manifest[capability]["reason"]
18004                .as_str()
18005                .is_some_and(|reason| !reason.is_empty()));
18006        }
18007    }
18008
18009    fn typed_fidelity_probe() -> AvroValue {
18010        AvroValue::Map(BTreeMap::from([
18011            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
18012            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
18013            (
18014                "numeric".to_string(),
18015                AvroValue::Map(BTreeMap::from([
18016                    ("0".to_string(), AvroValue::String("zero".to_string())),
18017                    ("1".to_string(), AvroValue::String("one".to_string())),
18018                ])),
18019            ),
18020            (
18021                "nested".to_string(),
18022                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
18023                    "enabled".to_string(),
18024                    AvroValue::Boolean(true),
18025                )]))]),
18026            ),
18027            (
18028                "projection_collisions".to_string(),
18029                AvroValue::Array(projection_collision_probe()),
18030            ),
18031        ]))
18032    }
18033
18034    fn projection_collision_probe() -> Vec<AvroValue> {
18035        vec![
18036            AvroValue::Map(BTreeMap::from([
18037                ("$type".to_string(), AvroValue::String("bytes".to_string())),
18038                (
18039                    "base64".to_string(),
18040                    AvroValue::String("ordinary user text".to_string()),
18041                ),
18042            ])),
18043            AvroValue::Map(BTreeMap::from([
18044                ("$type".to_string(), AvroValue::String("map".to_string())),
18045                (
18046                    "entries".to_string(),
18047                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
18048                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
18049                        (
18050                            "value".to_string(),
18051                            AvroValue::String("user map".to_string()),
18052                        ),
18053                    ]))]),
18054                ),
18055            ])),
18056        ]
18057    }
18058
18059    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18060    struct TypedContract {
18061        nested: TypedNested,
18062        mode: TypedMode,
18063        optional: Option<String>,
18064        absent: Option<String>,
18065        items: Vec<i64>,
18066        labels: BTreeMap<String, String>,
18067        bytes: serde_bytes::ByteBuf,
18068        signed: i64,
18069        finite: f64,
18070    }
18071
18072    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18073    struct TypedNested {
18074        enabled: bool,
18075    }
18076
18077    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18078    enum TypedMode {
18079        Detailed { label: String },
18080    }
18081
18082    fn typed_contract() -> TypedContract {
18083        TypedContract {
18084            nested: TypedNested { enabled: true },
18085            mode: TypedMode::Detailed {
18086                label: "compiler-checked".to_string(),
18087            },
18088            optional: Some("present".to_string()),
18089            absent: None,
18090            items: vec![i64::MIN, 0, i64::MAX],
18091            labels: BTreeMap::from([
18092                ("language".to_string(), "rust".to_string()),
18093                ("wire".to_string(), "avro".to_string()),
18094            ]),
18095            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
18096            signed: -9_223_372_036_854_775_000,
18097            finite: 12.5,
18098        }
18099    }
18100
18101    #[derive(Clone, Debug, Default, PartialEq)]
18102    struct ReplayCounterState {
18103        loaded: Option<String>,
18104        count: i64,
18105        finished: bool,
18106    }
18107
18108    fn replay_counter_worker() -> Worker {
18109        let client = Client::new("http://127.0.0.1:8080").expect("client");
18110        let mut worker = Worker::new(client, "rust-workers");
18111        worker.register_replayed_workflow(
18112            "replay-counter",
18113            ReplayCounterState::default,
18114            |ctx, _input, state| async move {
18115                let loaded = ctx.activity("load-counter", json!([])).await?;
18116                state.update(|current| {
18117                    current.loaded = loaded.as_str().map(str::to_string);
18118                })?;
18119                for _ in 0..2 {
18120                    let signal = ctx.wait_signal("increment").await?;
18121                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
18122                    state.update(|current| current.count += amount)?;
18123                }
18124                state.update(|current| current.finished = true)?;
18125                state.read(|current| Ok(json!(current.count)))?
18126            },
18127        );
18128        worker.register_replayed_query::<ReplayCounterState, _, _>(
18129            "replay-counter",
18130            "current",
18131            |_ctx, state, _args| async move {
18132                Ok(json!({
18133                    "loaded": state.loaded,
18134                    "count": state.count,
18135                    "finished": state.finished,
18136                }))
18137            },
18138        );
18139        worker.register_replayed_query::<ReplayCounterState, _, _>(
18140            "replay-counter",
18141            "detached-mutation",
18142            |_ctx, state, _args| async move {
18143                let mut detached = (*state).clone();
18144                detached.count = 999;
18145                Ok(json!(detached.count))
18146            },
18147        );
18148        worker.register_replayed_query::<ReplayCounterState, _, _>(
18149            "replay-counter",
18150            "failed-mutation",
18151            |_ctx, state, _args| async move {
18152                let mut detached = (*state).clone();
18153                detached.count = 999;
18154                Err(Error::WorkerLoop("query refused".to_string()))
18155            },
18156        );
18157        worker
18158    }
18159
18160    fn replay_counter_query(
18161        query_name: &str,
18162        history_events: Value,
18163        run_status: &str,
18164    ) -> QueryTask {
18165        let arguments = fixture_envelope(json!([]));
18166        serde_json::from_value(json!({
18167            "query_task_id": format!("query-{query_name}"),
18168            "workflow_type": "replay-counter",
18169            "query_name": query_name,
18170            "payload_codec": DEFAULT_CODEC,
18171            "workflow_arguments": arguments.clone(),
18172            "query_arguments": arguments,
18173            "history_events": history_events,
18174            "run_status": run_status,
18175        }))
18176        .expect("query task")
18177    }
18178
18179    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
18180        workflow_context_with_codec(history, DEFAULT_CODEC)
18181    }
18182
18183    fn workflow_context_with_codec(
18184        history: Vec<HistoryEvent>,
18185        payload_codec: &str,
18186    ) -> WorkflowContext {
18187        WorkflowContext {
18188            cancellation_scope_id: "root".into(),
18189            state: Arc::new(Mutex::new(
18190                WorkflowState::new_with_identity(
18191                    history,
18192                    None,
18193                    None,
18194                    "rust-workers".to_string(),
18195                    payload_codec.to_string(),
18196                    None,
18197                )
18198                .expect("valid workflow history"),
18199            )),
18200        }
18201    }
18202
18203    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
18204        HistoryEvent {
18205            event_type: event_type.to_string(),
18206            payload,
18207            raw: HashMap::new(),
18208        }
18209    }
18210
18211    fn parallel_path_entry(
18212        kind: &str,
18213        base: u64,
18214        size: usize,
18215        index: usize,
18216    ) -> ParallelGroupMetadata {
18217        parallel_group_entry(base, size, index, kind)
18218    }
18219
18220    fn parallel_history_event(
18221        event_type: &str,
18222        sequence: u64,
18223        identity_field: &str,
18224        identity: &str,
18225        path: Vec<ParallelGroupMetadata>,
18226        result: Option<Value>,
18227    ) -> HistoryEvent {
18228        let mut payload = serde_json::Map::from_iter([
18229            ("sequence".to_string(), json!(sequence)),
18230            (identity_field.to_string(), json!(identity)),
18231        ]);
18232        let inner = path.last().expect("parallel history path");
18233        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
18234        payload.insert("parallel_group_path".to_string(), json!(path));
18235        if let Some(result) = result {
18236            let field = if event_type == "ChildRunCompleted" {
18237                "result"
18238            } else {
18239                "result"
18240            };
18241            payload.insert(field.to_string(), fixture_envelope(result));
18242            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
18243        }
18244        history_event(event_type, Value::Object(payload))
18245    }
18246
18247    fn nested_parallel_operations() -> Vec<ParallelOperation> {
18248        vec![
18249            ParallelOperation::activity("first", json!([])),
18250            ParallelOperation::group(vec![
18251                ParallelOperation::child_workflow(
18252                    "second",
18253                    ChildWorkflowOptions::new("child-workers"),
18254                    json!([]),
18255                ),
18256                ParallelOperation::activity("third", json!([])),
18257            ]),
18258        ]
18259    }
18260
18261    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
18262        let outer = [
18263            parallel_path_entry("mixed", 1, 3, 0),
18264            parallel_path_entry("mixed", 1, 3, 1),
18265            parallel_path_entry("mixed", 1, 3, 2),
18266        ];
18267        [
18268            vec![outer[0].clone()],
18269            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
18270            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
18271        ]
18272    }
18273
18274    #[test]
18275    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
18276        let ctx = workflow_context(Vec::new());
18277        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18278        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18279
18280        assert!(matches!(
18281            call.as_mut().poll(&mut task_context),
18282            Poll::Pending
18283        ));
18284        let commands = ctx.take_commands().expect("parallel commands");
18285        assert_eq!(
18286            commands
18287                .iter()
18288                .map(|command| command["type"].as_str().unwrap_or_default())
18289                .collect::<Vec<_>>(),
18290            [
18291                "schedule_activity",
18292                "start_child_workflow",
18293                "schedule_activity"
18294            ]
18295        );
18296        let paths = nested_parallel_paths();
18297        for (command, path) in commands.iter().zip(paths) {
18298            assert_eq!(command["parallel_group_path"], json!(path));
18299            assert_eq!(
18300                command["parallel_group_id"],
18301                json!(path.last().expect("inner group").parallel_group_id)
18302            );
18303        }
18304    }
18305
18306    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
18307        let paths = nested_parallel_paths();
18308        let third = parallel_history_event(
18309            "ActivityCompleted",
18310            3,
18311            "activity_type",
18312            "third",
18313            paths[2].clone(),
18314            Some(json!("three")),
18315        );
18316        vec![
18317            parallel_history_event(
18318                "ActivityCompleted",
18319                1,
18320                "activity_type",
18321                "first",
18322                paths[0].clone(),
18323                Some(json!("one")),
18324            ),
18325            parallel_history_event(
18326                "ChildWorkflowScheduled",
18327                2,
18328                "child_workflow_type",
18329                "second",
18330                paths[1].clone(),
18331                None,
18332            ),
18333            parallel_history_event(
18334                "ChildRunCompleted",
18335                2,
18336                "child_workflow_type",
18337                "second",
18338                paths[1].clone(),
18339                Some(json!("two")),
18340            ),
18341            third.clone(),
18342            third,
18343        ]
18344    }
18345
18346    #[test]
18347    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
18348        for _restart_or_completed_replay in 0..2 {
18349            let ctx = workflow_context(completed_nested_parallel_history());
18350            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18351            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18352            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
18353                panic!("completed nested parallel history must replay");
18354            };
18355            assert_eq!(
18356                results,
18357                vec![
18358                    ParallelResult::Activity(json!("one")),
18359                    ParallelResult::Group(vec![
18360                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
18361                            parent: WorkflowIdentity {
18362                                workflow_id: None,
18363                                run_id: None,
18364                            },
18365                            child: WorkflowIdentity {
18366                                workflow_id: None,
18367                                run_id: None,
18368                            },
18369                            child_workflow_type: Some("second".to_string()),
18370                            result: json!("two"),
18371                        }),
18372                        ParallelResult::Activity(json!("three")),
18373                    ]),
18374                ]
18375            );
18376            assert!(ctx.take_commands().expect("commands").is_empty());
18377            ctx.ensure_history_consumed().expect("history consumed");
18378        }
18379    }
18380
18381    #[test]
18382    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
18383        let paths = nested_parallel_paths();
18384        let history = vec![
18385            parallel_history_event(
18386                "ActivityCompleted",
18387                1,
18388                "activity_type",
18389                "first",
18390                paths[0].clone(),
18391                Some(json!("one")),
18392            ),
18393            parallel_history_event(
18394                "ChildWorkflowScheduled",
18395                2,
18396                "child_workflow_type",
18397                "second",
18398                paths[1].clone(),
18399                None,
18400            ),
18401            parallel_history_event(
18402                "ChildRunFailed",
18403                2,
18404                "child_workflow_type",
18405                "second",
18406                paths[1].clone(),
18407                None,
18408            ),
18409            parallel_history_event(
18410                "ActivityCompleted",
18411                3,
18412                "activity_type",
18413                "third",
18414                paths[2].clone(),
18415                Some(json!("late")),
18416            ),
18417        ];
18418        let ctx = workflow_context(history);
18419        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18420        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18421        let outcome = call.as_mut().poll(&mut task_context);
18422        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
18423            panic!("one failed child must return a typed partial failure: {outcome:?}");
18424        };
18425        assert_eq!(failure.member_path, [1, 0]);
18426        assert_eq!(failure.group_id, "parallel-calls:1:3");
18427        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
18428        assert_eq!(
18429            failure
18430                .completed
18431                .iter()
18432                .map(|completion| completion.member_path.clone())
18433                .collect::<Vec<_>>(),
18434            [vec![0], vec![1, 1]]
18435        );
18436    }
18437
18438    #[test]
18439    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
18440        let paths = nested_parallel_paths();
18441        let history = vec![
18442            parallel_history_event(
18443                "ActivityScheduled",
18444                1,
18445                "activity_type",
18446                "first",
18447                paths[0].clone(),
18448                None,
18449            ),
18450            parallel_history_event(
18451                "ChildWorkflowScheduled",
18452                2,
18453                "child_workflow_type",
18454                "second",
18455                paths[1].clone(),
18456                None,
18457            ),
18458            parallel_history_event(
18459                "ActivityScheduled",
18460                3,
18461                "activity_type",
18462                "third",
18463                paths[2].clone(),
18464                None,
18465            ),
18466        ];
18467        for _restart in 0..2 {
18468            let ctx = workflow_context(history.clone());
18469            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18470            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18471            let outcome = call.as_mut().poll(&mut task_context);
18472            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
18473            assert!(ctx.take_commands().expect("commands").is_empty());
18474        }
18475    }
18476
18477    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
18478        vec![selection_group_entry(
18479            1,
18480            2,
18481            index,
18482            "activity",
18483            &SelectionMemberMetadata {
18484                key: SelectionKey::Name(key.to_string()),
18485                index,
18486                base_sequence: index as u64 + 1,
18487                size: 1,
18488                kind: "activity".to_string(),
18489            },
18490        )]
18491    }
18492
18493    fn selection_activity_event(
18494        event_type: &str,
18495        index: usize,
18496        key: &str,
18497        result: Option<Value>,
18498    ) -> HistoryEvent {
18499        let sequence = index as u64 + 1;
18500        let mut event = parallel_history_event(
18501            event_type,
18502            sequence,
18503            "activity_type",
18504            &format!("{key}-activity"),
18505            selection_path(index, key),
18506            result,
18507        );
18508        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
18509        event.raw.insert(
18510            "id".to_string(),
18511            json!(if event_type == "ActivityCompleted" {
18512                format!("event-{key}")
18513            } else {
18514                format!("{event_type}-{key}")
18515            }),
18516        );
18517        event
18518    }
18519
18520    fn selection_winner_marker() -> HistoryEvent {
18521        history_event(
18522            "SelectionResolved",
18523            json!({
18524                "selection_group_id": "select-calls:1:2",
18525                "selection_group_base_sequence": 1,
18526                "selection_group_size": 2,
18527                "member_key": "fast",
18528                "member_index": 1,
18529                "member_base_sequence": 2,
18530                "member_size": 1,
18531                "operation_kind": "activity",
18532                "operation_identity": "activity-fast",
18533                "outcome": "completed",
18534                "resolution_event_id": "event-fast",
18535                "resolution_event_type": "ActivityCompleted",
18536            }),
18537        )
18538    }
18539
18540    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
18541        ctx.select_keyed(vec![
18542            (
18543                "slow",
18544                ParallelOperation::activity_with_options(
18545                    "slow-activity",
18546                    ActivityOptions::new().task_queue("default"),
18547                    json!([]),
18548                ),
18549            ),
18550            (
18551                "fast",
18552                ParallelOperation::activity_with_options(
18553                    "fast-activity",
18554                    ActivityOptions::new().task_queue("default"),
18555                    json!([]),
18556                ),
18557            ),
18558        ])
18559    }
18560
18561    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
18562        let ctx = workflow_context(history);
18563        let mut call = Box::pin(keyed_activity_selection(&ctx));
18564        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18565        let selected = match call.as_mut().poll(&mut task_context) {
18566            Poll::Ready(Ok(selected)) => selected,
18567            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
18568            Poll::Pending => panic!("persisted selection winner must replay without pending"),
18569        };
18570        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
18571        assert_eq!(
18572            selected.value,
18573            Some(ParallelResult::Activity(json!("winner-value")))
18574        );
18575        let slow = selected
18576            .handle(&SelectionKey::Name("slow".to_string()))
18577            .expect("slow handle")
18578            .clone();
18579        let mut await_slow = Box::pin(slow.await_result());
18580        assert!(matches!(
18581            await_slow.as_mut().poll(&mut task_context),
18582            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
18583        ));
18584        assert!(ctx.take_commands().expect("commands").is_empty());
18585    }
18586
18587    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
18588
18589    fn canonical_selection_history() -> Vec<HistoryEvent> {
18590        const FIXTURE: &[u8] =
18591            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
18592        assert_eq!(
18593            format!("{:x}", Sha256::digest(FIXTURE)),
18594            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18595        );
18596        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
18597
18598        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
18599    }
18600
18601    #[test]
18602    fn selection_fresh_process_entrypoint() {
18603        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
18604            return;
18605        };
18606        let persisted = fs::read(path).expect("persisted selection history");
18607        assert_eq!(
18608            format!("{:x}", Sha256::digest(&persisted)),
18609            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18610        );
18611        let fixture: Value =
18612            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
18613        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
18614            .expect("valid persisted selection history");
18615
18616        assert_persisted_selection_replay(history);
18617    }
18618
18619    #[test]
18620    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
18621        let ctx = workflow_context(Vec::new());
18622        let mut call = Box::pin(keyed_activity_selection(&ctx));
18623        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18624
18625        assert!(matches!(
18626            call.as_mut().poll(&mut task_context),
18627            Poll::Pending
18628        ));
18629        let commands = ctx.take_commands().expect("selection commands");
18630        assert_eq!(commands.len(), 2);
18631        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
18632        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
18633        assert!(commands.iter().all(|command| {
18634            command["parallel_group_id"] == json!("select-calls:1:2")
18635                && command["parallel_group_mode"] == json!("select")
18636        }));
18637    }
18638
18639    #[test]
18640    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
18641        let ctx = workflow_context(Vec::new());
18642        let mut invalid = Box::pin(ctx.select_keyed(vec![(
18643            "",
18644            ParallelOperation::activity("invalid", json!([])),
18645        )]));
18646        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18647        assert!(matches!(
18648            invalid.as_mut().poll(&mut task_context),
18649            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
18650                reason: "selection_key_invalid",
18651                ..
18652            })))
18653        ));
18654
18655        for invalid_key in [json!(""), json!(-1)] {
18656            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
18657            event.payload["selection_member_key"] = invalid_key.clone();
18658            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
18659            assert!(matches!(
18660                WorkflowState::new_with_identity(
18661                    vec![event],
18662                    None,
18663                    None,
18664                    "rust-workers".to_string(),
18665                    DEFAULT_CODEC.to_string(),
18666                    None,
18667                ),
18668                Err(Error::NonDeterministicReplay(_))
18669            ));
18670        }
18671    }
18672
18673    #[test]
18674    fn selection_preserves_valid_named_and_numeric_keys() {
18675        let ctx = workflow_context(Vec::new());
18676        let mut selection = Box::pin(ctx.select_keyed(vec![
18677            (
18678                SelectionKey::Index(0),
18679                ParallelOperation::activity("numeric", json!([])),
18680            ),
18681            (
18682                SelectionKey::Name("named".to_string()),
18683                ParallelOperation::timer(Duration::from_secs(1)),
18684            ),
18685        ]));
18686        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18687
18688        assert!(matches!(
18689            selection.as_mut().poll(&mut task_context),
18690            Poll::Pending
18691        ));
18692        let commands = ctx.take_commands().expect("selection commands");
18693        assert_eq!(commands[0]["selection_member_key"], json!(0));
18694        assert_eq!(commands[1]["selection_member_key"], json!("named"));
18695    }
18696
18697    #[test]
18698    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
18699        let history = canonical_selection_history();
18700        assert_persisted_selection_replay(history.clone());
18701
18702        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18703            .join("tests/fixtures/durable_selection_runtime_history.json");
18704        let output =
18705            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
18706                .args([
18707                    "--exact",
18708                    "tests::selection_fresh_process_entrypoint",
18709                    "--nocapture",
18710                ])
18711                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
18712                .output()
18713                .expect("run fresh selection replay process");
18714
18715        assert!(
18716            output.status.success(),
18717            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
18718            String::from_utf8_lossy(&output.stdout),
18719            String::from_utf8_lossy(&output.stderr),
18720        );
18721    }
18722
18723    #[test]
18724    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
18725        let mut history = canonical_selection_history();
18726        history.retain(|event| event.event_type != "SelectionResolved");
18727        let ctx = workflow_context(history);
18728        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18729        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18730
18731        assert!(matches!(
18732            selection.as_mut().poll(&mut task_context),
18733            Poll::Pending
18734        ));
18735        assert!(ctx.take_commands().expect("commands").is_empty());
18736        assert!(
18737            ctx.matched_recorded_pending()
18738                .expect("selection pending state"),
18739            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
18740        );
18741    }
18742
18743    #[test]
18744    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
18745        for (terminal_event, predicate_satisfied, timeout_seconds) in [
18746            ("ConditionWaitSatisfied", true, None),
18747            ("ConditionWaitTimedOut", false, Some(0)),
18748        ] {
18749            let member = SelectionMemberMetadata {
18750                key: SelectionKey::Name("condition".to_string()),
18751                index: 0,
18752                base_sequence: 1,
18753                size: 1,
18754                kind: "condition".to_string(),
18755            };
18756            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
18757            let mut payload = json!({
18758                "sequence": 1,
18759                "condition_wait_id": "condition-1",
18760                "condition_wait_occurrence_id": "rust:condition-wait:0",
18761                "condition_key": "ready",
18762                "condition_definition_fingerprint": "sha256:ready-v1",
18763                "parallel_group_path": path,
18764            });
18765            payload
18766                .as_object_mut()
18767                .expect("condition history payload")
18768                .extend(
18769                    serde_json::to_value(&path[0])
18770                        .expect("condition selection metadata")
18771                        .as_object()
18772                        .expect("condition selection metadata object")
18773                        .clone(),
18774                );
18775            if let Some(timeout_seconds) = timeout_seconds {
18776                payload["timeout_seconds"] = json!(timeout_seconds);
18777            }
18778            let history = vec![
18779                history_event("ConditionWaitOpened", payload.clone()),
18780                history_event(terminal_event, payload),
18781            ];
18782            let ctx = workflow_context(history);
18783            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18784            if timeout_seconds.is_some() {
18785                options = options.timeout(Duration::ZERO);
18786            }
18787            let mut selection = Box::pin(ctx.select_keyed(vec![(
18788                "condition",
18789                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18790            )]));
18791            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18792
18793            assert!(matches!(
18794                selection.as_mut().poll(&mut task_context),
18795                Poll::Pending
18796            ));
18797            assert!(ctx.take_commands().expect("commands").is_empty());
18798            assert!(
18799                ctx.matched_recorded_pending()
18800                    .expect("condition selection pending state"),
18801                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18802            );
18803        }
18804    }
18805
18806    #[test]
18807    fn selection_immediate_condition_members_open_a_durable_wait() {
18808        for predicate_satisfied in [true, false] {
18809            let ctx = workflow_context(Vec::new());
18810            let mut selection = Box::pin(ctx.select_keyed(vec![(
18811                "condition",
18812                ParallelOperation::condition(
18813                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
18814                    move || Ok(predicate_satisfied),
18815                ),
18816            )]));
18817            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18818
18819            assert!(matches!(
18820                selection.as_mut().poll(&mut task_context),
18821                Poll::Pending
18822            ));
18823            let commands = ctx.take_commands().expect("condition selection command");
18824            assert_eq!(commands.len(), 1);
18825            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
18826            assert_eq!(commands[0]["timeout_seconds"], json!(0));
18827            assert_eq!(
18828                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
18829                json!("select")
18830            );
18831        }
18832    }
18833
18834    #[test]
18835    fn selection_loser_cancellation_is_explicit_and_idempotent() {
18836        let history = vec![
18837            selection_activity_event("ActivityScheduled", 0, "slow", None),
18838            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18839            selection_winner_marker(),
18840        ];
18841        let ctx = workflow_context(history.clone());
18842        let mut call = Box::pin(keyed_activity_selection(&ctx));
18843        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18844        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18845            panic!("winner must replay");
18846        };
18847        let slow = selected
18848            .handle(&SelectionKey::Name("slow".to_string()))
18849            .expect("slow handle")
18850            .clone();
18851        let mut cancel = Box::pin(slow.cancel());
18852        assert!(matches!(
18853            cancel.as_mut().poll(&mut task_context),
18854            Poll::Pending
18855        ));
18856        assert!(matches!(
18857            cancel.as_mut().poll(&mut task_context),
18858            Poll::Pending
18859        ));
18860        let commands = ctx.take_commands().expect("cancel command");
18861        assert_eq!(commands.len(), 1);
18862        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
18863        assert_eq!(commands[0]["member_key"], json!("slow"));
18864
18865        let mut cancelled_history = history;
18866        cancelled_history.push(history_event(
18867            "SelectionOperationCancelled",
18868            json!({
18869                "selection_group_id": "select-calls:1:2",
18870                "member_key": "slow",
18871                "member_index": 0,
18872                "member_base_sequence": 1,
18873                "member_size": 1,
18874                "operation_kind": "activity",
18875                "operation_identity": "activity-slow",
18876                "cancelled_at": "2026-08-27T00:00:00Z",
18877            }),
18878        ));
18879        let replayed = workflow_context(cancelled_history);
18880        let mut call = Box::pin(keyed_activity_selection(&replayed));
18881        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18882            panic!("winner must replay after cancellation");
18883        };
18884        let slow = selected
18885            .handle(&SelectionKey::Name("slow".to_string()))
18886            .expect("slow handle")
18887            .clone();
18888        let mut cancel = Box::pin(slow.cancel());
18889        assert!(matches!(
18890            cancel.as_mut().poll(&mut task_context),
18891            Poll::Ready(Ok(()))
18892        ));
18893        assert!(replayed.take_commands().expect("commands").is_empty());
18894    }
18895
18896    #[test]
18897    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
18898        let base_history = vec![
18899            selection_activity_event("ActivityScheduled", 0, "slow", None),
18900            selection_activity_event("ActivityScheduled", 1, "fast", None),
18901            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18902            selection_winner_marker(),
18903        ];
18904        for (field, corrupt) in [
18905            ("member_key", json!("fast")),
18906            ("member_index", json!(1)),
18907            ("member_base_sequence", json!(3)),
18908            ("member_size", json!(2)),
18909            ("operation_kind", json!("timer")),
18910            ("operation_identity", json!("forged")),
18911        ] {
18912            let mut cancellation = json!({
18913                "selection_group_id": "select-calls:1:2",
18914                "member_key": "slow",
18915                "member_index": 0,
18916                "member_base_sequence": 1,
18917                "member_size": 1,
18918                "operation_kind": "activity",
18919                "operation_identity": "activity-slow",
18920            });
18921            cancellation[field] = corrupt;
18922            let mut history = base_history.clone();
18923            history.push(history_event("SelectionOperationCancelled", cancellation));
18924            let ctx = workflow_context(history);
18925            let mut selection = Box::pin(keyed_activity_selection(&ctx));
18926            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18927
18928            assert!(matches!(
18929                selection.as_mut().poll(&mut task_context),
18930                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18931            ));
18932        }
18933    }
18934
18935    #[test]
18936    fn selection_child_identity_prefers_the_durable_run_id() {
18937        let ctx = workflow_context(vec![history_event(
18938            "ChildWorkflowScheduled",
18939            json!({
18940                "sequence": 1,
18941                "child_workflow_type": "child",
18942                "child_workflow_instance_id": "child-instance",
18943                "child_workflow_run_id": "child-run",
18944            }),
18945        )]);
18946        let state = ctx.state.lock().expect("workflow state");
18947
18948        assert_eq!(
18949            selection_operation_identity(&state, "child", 1, 1),
18950            "child-run"
18951        );
18952    }
18953
18954    #[test]
18955    fn selection_activity_identity_requires_canonical_execution_id() {
18956        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
18957        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
18958        let mut fast_completed =
18959            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
18960        for event in [&mut fast_open, &mut fast_completed] {
18961            event
18962                .payload
18963                .as_object_mut()
18964                .expect("activity payload")
18965                .remove("activity_execution_id");
18966            event.payload["activity_id"] = json!("forged-activity-id");
18967        }
18968        let mut marker = selection_winner_marker();
18969        marker.payload["operation_identity"] = json!("forged-activity-id");
18970        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
18971        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18972        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18973
18974        assert!(matches!(
18975            selection.as_mut().poll(&mut task_context),
18976            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18977        ));
18978    }
18979
18980    #[test]
18981    fn selection_completion_before_cancellation_remains_awaitable() {
18982        let history = vec![
18983            selection_activity_event("ActivityScheduled", 0, "slow", None),
18984            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18985            selection_winner_marker(),
18986            selection_activity_event(
18987                "ActivityCompleted",
18988                0,
18989                "slow",
18990                Some(json!("completed-first")),
18991            ),
18992        ];
18993        let ctx = workflow_context(history);
18994        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18995        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18996        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18997            panic!("winner must replay");
18998        };
18999        let slow = selected
19000            .handle(&SelectionKey::Name("slow".to_string()))
19001            .expect("slow handle")
19002            .clone();
19003        let mut cancel = Box::pin(slow.cancel());
19004        assert!(matches!(
19005            cancel.as_mut().poll(&mut task_context),
19006            Poll::Ready(Ok(()))
19007        ));
19008        let mut await_slow = Box::pin(slow.await_result());
19009        assert!(matches!(
19010            await_slow.as_mut().poll(&mut task_context),
19011            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
19012        ));
19013        let commands = ctx.take_commands().expect("commands");
19014        assert!(commands.is_empty());
19015    }
19016
19017    #[test]
19018    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
19019        let nested_member = SelectionMemberMetadata {
19020            key: SelectionKey::Name("nested".to_string()),
19021            index: 0,
19022            base_sequence: 1,
19023            size: 2,
19024            kind: "group".to_string(),
19025        };
19026        let deadline_member = SelectionMemberMetadata {
19027            key: SelectionKey::Name("deadline".to_string()),
19028            index: 1,
19029            base_sequence: 3,
19030            size: 1,
19031            kind: "timer".to_string(),
19032        };
19033        let nested_paths = [
19034            vec![
19035                selection_group_entry(1, 3, 0, "mixed", &nested_member),
19036                parallel_group_entry(1, 2, 0, "activity"),
19037            ],
19038            vec![
19039                selection_group_entry(1, 3, 1, "mixed", &nested_member),
19040                parallel_group_entry(1, 2, 1, "activity"),
19041            ],
19042        ];
19043        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
19044        let mut timer_fired = parallel_history_event(
19045            "TimerFired",
19046            3,
19047            "timer_id",
19048            "timer-3",
19049            deadline_path.clone(),
19050            None,
19051        );
19052        timer_fired.payload["delay_seconds"] = json!(0);
19053        timer_fired
19054            .raw
19055            .insert("id".to_string(), json!("timer-fired"));
19056        let mut timer_scheduled = parallel_history_event(
19057            "TimerScheduled",
19058            3,
19059            "timer_id",
19060            "timer-3",
19061            deadline_path,
19062            None,
19063        );
19064        timer_scheduled.payload["delay_seconds"] = json!(0);
19065        let history = vec![
19066            parallel_history_event(
19067                "ActivityScheduled",
19068                1,
19069                "activity_type",
19070                "nested-first",
19071                nested_paths[0].clone(),
19072                None,
19073            ),
19074            parallel_history_event(
19075                "ActivityScheduled",
19076                2,
19077                "activity_type",
19078                "nested-second",
19079                nested_paths[1].clone(),
19080                None,
19081            ),
19082            timer_scheduled,
19083            timer_fired,
19084            history_event(
19085                "SelectionResolved",
19086                json!({
19087                    "selection_group_id": "select-calls:1:3",
19088                    "selection_group_base_sequence": 1,
19089                    "selection_group_size": 3,
19090                    "member_key": "deadline",
19091                    "member_index": 1,
19092                    "member_base_sequence": 3,
19093                    "member_size": 1,
19094                    "operation_kind": "timer",
19095                    "operation_identity": "timer-3",
19096                    "outcome": "completed",
19097                    "resolution_event_id": "timer-fired",
19098                    "resolution_event_type": "TimerFired",
19099                }),
19100            ),
19101            parallel_history_event(
19102                "ActivityFailed",
19103                2,
19104                "activity_type",
19105                "nested-second",
19106                nested_paths[1].clone(),
19107                None,
19108            ),
19109        ];
19110        let ctx = workflow_context(history);
19111        let mut selection = Box::pin(ctx.select_keyed(vec![
19112            (
19113                "nested",
19114                ParallelOperation::group(vec![
19115                    ParallelOperation::activity("nested-first", json!([])),
19116                    ParallelOperation::activity("nested-second", json!([])),
19117                ]),
19118            ),
19119            ("deadline", ParallelOperation::timer(Duration::ZERO)),
19120        ]));
19121        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19122        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19123            panic!("deadline winner must replay");
19124        };
19125        let nested = selected
19126            .handle(&SelectionKey::Name("nested".to_string()))
19127            .expect("nested handle")
19128            .clone();
19129        let mut cancel = Box::pin(nested.cancel());
19130        assert!(matches!(
19131            cancel.as_mut().poll(&mut task_context),
19132            Poll::Ready(Ok(()))
19133        ));
19134        let mut await_nested = Box::pin(nested.await_result());
19135
19136        assert!(matches!(
19137            await_nested.as_mut().poll(&mut task_context),
19138            Poll::Ready(Err(Error::ActivityFailed(_)))
19139        ));
19140        assert!(ctx.take_commands().expect("commands").is_empty());
19141    }
19142
19143    #[test]
19144    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
19145        let ctx = workflow_context(Vec::new());
19146        let mut call = Box::pin(ctx.select(vec![
19147            ParallelOperation::child_workflow(
19148                "child",
19149                ChildWorkflowOptions::new("children"),
19150                json!([]),
19151            ),
19152            ParallelOperation::timer(Duration::from_secs(30)),
19153            ParallelOperation::signal("approval"),
19154            ParallelOperation::condition(
19155                ConditionWaitOptions::new("ready", "sha256:ready"),
19156                || Ok(false),
19157            ),
19158            ParallelOperation::group(vec![
19159                ParallelOperation::activity("nested-one", json!([])),
19160                ParallelOperation::activity("nested-two", json!([])),
19161            ]),
19162        ]));
19163        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19164        assert!(matches!(
19165            call.as_mut().poll(&mut task_context),
19166            Poll::Pending
19167        ));
19168        let commands = ctx.take_commands().expect("selection commands");
19169        assert_eq!(
19170            commands
19171                .iter()
19172                .map(|command| command["type"].as_str().unwrap_or_default())
19173                .collect::<Vec<_>>(),
19174            [
19175                "start_child_workflow",
19176                "start_timer",
19177                "open_signal_wait",
19178                "open_condition_wait",
19179                "schedule_activity",
19180                "schedule_activity",
19181            ]
19182        );
19183        assert!(commands.iter().all(|command| {
19184            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
19185        }));
19186        assert_eq!(
19187            commands[4]["parallel_group_path"].as_array().map(Vec::len),
19188            Some(2)
19189        );
19190        assert_eq!(
19191            commands[4]["parallel_group_path"][0]["selection_member_kind"],
19192            json!("group")
19193        );
19194        assert_eq!(
19195            commands[5]["parallel_group_path"][0]["selection_member_kind"],
19196            json!("group")
19197        );
19198
19199        let one_leaf_ctx = workflow_context(Vec::new());
19200        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
19201            ParallelOperation::activity("nested-only", json!([])),
19202        ])]));
19203        assert!(matches!(
19204            one_leaf.as_mut().poll(&mut task_context),
19205            Poll::Pending
19206        ));
19207        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
19208        assert_eq!(one_leaf_commands.len(), 1);
19209        assert_eq!(
19210            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
19211            json!("group")
19212        );
19213        assert_eq!(
19214            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
19215            json!(1)
19216        );
19217    }
19218
19219    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
19220        let mut saga = ctx.saga();
19221        let outcome = async {
19222            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19223            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19224            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
19225            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
19226            ctx.activity("trip.charge", json!([])).await?;
19227            Ok(json!({"status": "booked"}))
19228        }
19229        .await;
19230        saga.finish(outcome).await
19231    }
19232
19233    fn saga_activity(
19234        event_type: &str,
19235        sequence: u64,
19236        activity_type: &str,
19237        result: Option<Value>,
19238    ) -> HistoryEvent {
19239        let mut payload = json!({
19240            "sequence": sequence,
19241            "activity_type": activity_type,
19242            "message": format!("{activity_type} failed"),
19243            "exception_type": "PlannedFailure",
19244            "non_retryable": true,
19245        });
19246        if let Some(result) = result {
19247            payload["result"] = fixture_envelope(result);
19248        }
19249        history_event(event_type, payload)
19250    }
19251
19252    #[test]
19253    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
19254        let completed_hotel_compensation = saga_activity(
19255            "ActivityCompleted",
19256            4,
19257            "trip.cancel-hotel",
19258            Some(Value::Null),
19259        );
19260        let history = vec![
19261            saga_activity(
19262                "ActivityCompleted",
19263                1,
19264                "trip.reserve-flight",
19265                Some(json!("flight-1")),
19266            ),
19267            saga_activity(
19268                "ActivityCompleted",
19269                2,
19270                "trip.reserve-hotel",
19271                Some(json!("hotel-1")),
19272            ),
19273            saga_activity("ActivityFailed", 3, "trip.charge", None),
19274            completed_hotel_compensation.clone(),
19275            completed_hotel_compensation,
19276        ];
19277
19278        for _restart in 0..2 {
19279            let ctx = workflow_context(history.clone());
19280            let mut future = Box::pin(trip_saga(ctx.clone()));
19281            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19282            assert!(matches!(
19283                future.as_mut().poll(&mut task_context),
19284                Poll::Pending
19285            ));
19286            let commands = ctx.take_commands().expect("compensation command");
19287            assert_eq!(commands.len(), 1);
19288            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19289        }
19290    }
19291
19292    #[test]
19293    fn saga_compensation_failure_preserves_both_typed_failures() {
19294        let history = vec![
19295            saga_activity(
19296                "ActivityCompleted",
19297                1,
19298                "trip.reserve-flight",
19299                Some(json!("flight-1")),
19300            ),
19301            saga_activity(
19302                "ActivityCompleted",
19303                2,
19304                "trip.reserve-hotel",
19305                Some(json!("hotel-1")),
19306            ),
19307            saga_activity("ActivityFailed", 3, "trip.charge", None),
19308            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
19309        ];
19310        let ctx = workflow_context(history);
19311        let mut future = Box::pin(trip_saga(ctx));
19312        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19313        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
19314            future.as_mut().poll(&mut task_context)
19315        else {
19316            panic!("compensation failure must remain structured");
19317        };
19318        assert!(matches!(
19319            *failure.initiating_failure,
19320            Error::ActivityFailed(_)
19321        ));
19322        assert!(matches!(
19323            *failure.compensation_failure,
19324            Error::ActivityFailed(_)
19325        ));
19326        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
19327        assert_eq!(failure.compensation_registration_order, 2);
19328    }
19329
19330    #[test]
19331    fn saga_compensates_cooperative_cancellation() {
19332        let ctx = workflow_context(vec![saga_activity(
19333            "ActivityCompleted",
19334            1,
19335            "trip.reserve-flight",
19336            Some(json!("flight-1")),
19337        )]);
19338        ctx.state.lock().expect("state").cancel_requested = true;
19339        let run = {
19340            let ctx = ctx.clone();
19341            async move {
19342                let mut saga = ctx.saga();
19343                let outcome = async {
19344                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19345                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19346                    ctx.throw_if_cancellation_requested()?;
19347                    Ok(json!("unexpected"))
19348                }
19349                .await;
19350                saga.finish(outcome).await
19351            }
19352        };
19353        let mut future = Box::pin(run);
19354        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19355        assert!(matches!(
19356            future.as_mut().poll(&mut task_context),
19357            Poll::Pending
19358        ));
19359        let commands = ctx.take_commands().expect("cancellation compensation");
19360        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19361    }
19362
19363    fn workflow_task(
19364        workflow_type: &str,
19365        history_events: Vec<HistoryEvent>,
19366        payload_codec: &str,
19367    ) -> WorkflowTask {
19368        WorkflowTask {
19369            task_id: format!("wft-{workflow_type}"),
19370            workflow_command_id: None,
19371            workflow_id: Some(format!("wf-{workflow_type}")),
19372            run_id: Some(format!("run-{workflow_type}")),
19373            workflow_type: workflow_type.to_string(),
19374            cancel_requested: false,
19375            payload_codec: payload_codec.to_string(),
19376            arguments: Some(
19377                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
19378            ),
19379            total_history_events: Some(history_events.len() as u64),
19380            history_size_bytes: None,
19381            continue_as_new_recommended: None,
19382            history_budget_pressure: None,
19383            history_events,
19384            next_history_page_token: None,
19385            workflow_task_attempt: 1,
19386            workflow_signal_id: None,
19387            signal_name: None,
19388            signal_arguments: None,
19389            workflow_update_id: None,
19390            update_name: None,
19391            lease_owner: Some("rust-worker".to_string()),
19392        }
19393    }
19394
19395    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19396    struct SideEffectProbe {
19397        request_id: String,
19398        attempt: u32,
19399    }
19400
19401    #[test]
19402    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
19403        let calls = AtomicUsize::new(0);
19404        let ctx = workflow_context(Vec::new());
19405        let value = ctx
19406            .side_effect(|| {
19407                calls.fetch_add(1, Ordering::SeqCst);
19408                SideEffectProbe {
19409                    request_id: "request-42".to_string(),
19410                    attempt: 3,
19411                }
19412            })
19413            .expect("first side effect");
19414        assert_eq!(value.attempt, 3);
19415        assert_eq!(calls.load(Ordering::SeqCst), 1);
19416        let commands = ctx.take_commands().expect("commands");
19417        assert_eq!(commands.len(), 1);
19418        assert_eq!(commands[0]["type"], "record_side_effect");
19419        assert_eq!(
19420            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19421            serde_json::to_value(&value).expect("value")
19422        );
19423
19424        let replay = workflow_context(vec![history_event(
19425            "SideEffectRecorded",
19426            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19427        )]);
19428        let replayed: SideEffectProbe = replay
19429            .side_effect(|| {
19430                calls.fetch_add(1, Ordering::SeqCst);
19431                panic!("committed side-effect callbacks must not run during replay")
19432            })
19433            .expect("replayed side effect");
19434        assert_eq!(replayed, value);
19435        assert_eq!(calls.load(Ordering::SeqCst), 1);
19436        assert!(replay.take_commands().expect("commands").is_empty());
19437        replay.ensure_history_consumed().expect("history consumed");
19438    }
19439
19440    #[test]
19441    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
19442        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19443        let value = ctx
19444            .side_effect(|| SideEffectProbe {
19445                request_id: "avro-request".to_string(),
19446                attempt: 1,
19447            })
19448            .expect("Avro side effect");
19449        let uuid = ctx.uuid_v4().expect("deterministic UUID");
19450        let commands = ctx.take_commands().expect("commands");
19451        assert_eq!(commands.len(), 2);
19452        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
19453        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
19454        assert_eq!(
19455            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19456            serde_json::to_value(&value).expect("value")
19457        );
19458
19459        let replay = workflow_context_with_codec(
19460            vec![
19461                history_event(
19462                    "SideEffectRecorded",
19463                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19464                ),
19465                history_event(
19466                    "SideEffectRecorded",
19467                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
19468                ),
19469            ],
19470            DEFAULT_CODEC,
19471        );
19472        let replayed: SideEffectProbe = replay
19473            .side_effect(|| panic!("Avro callback must not run"))
19474            .expect("replayed Avro value");
19475        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
19476        assert_eq!(replayed, value);
19477        assert_eq!(replayed_uuid, uuid);
19478        assert!(replay.take_commands().expect("commands").is_empty());
19479    }
19480
19481    #[test]
19482    fn typed_side_effect_replay_preserves_bytes_and_maps() {
19483        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19484        let value = ctx
19485            .side_effect_avro_value(typed_fidelity_probe)
19486            .expect("typed side effect");
19487        let commands = ctx.take_commands().expect("side-effect command");
19488        assert_eq!(
19489            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19490                .expect("recorded side effect"),
19491            value
19492        );
19493
19494        let replay = workflow_context_with_codec(
19495            vec![history_event(
19496                "SideEffectRecorded",
19497                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19498            )],
19499            DEFAULT_CODEC,
19500        );
19501        assert_eq!(
19502            replay
19503                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
19504                .expect("replayed typed side effect"),
19505            value
19506        );
19507    }
19508
19509    #[test]
19510    fn ordered_side_effects_share_the_durable_command_stream() {
19511        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
19512        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
19513        let ctx = workflow_context(vec![
19514            history_event(
19515                "SideEffectRecorded",
19516                json!({"sequence": 1, "result": first}),
19517            ),
19518            history_event(
19519                "SideEffectRecorded",
19520                json!({"sequence": 2, "result": second}),
19521            ),
19522        ]);
19523        let first: String = ctx
19524            .side_effect(|| panic!("first callback must not run"))
19525            .expect("first replay");
19526        let second: i32 = ctx
19527            .side_effect(|| panic!("second callback must not run"))
19528            .expect("second replay");
19529        assert_eq!(first, "first");
19530        assert_eq!(second, 29);
19531        ctx.ensure_history_consumed().expect("ordered history");
19532
19533        let reordered = workflow_context(vec![history_event(
19534            "VersionMarkerRecorded",
19535            json!({
19536                "sequence": 1,
19537                "change_id": "before-side-effect",
19538                "version": 1,
19539                "min_supported": 1,
19540                "max_supported": 1,
19541            }),
19542        )]);
19543        let error = reordered
19544            .side_effect(|| "new".to_string())
19545            .expect_err("command reordering must fail");
19546        assert!(matches!(
19547            error,
19548            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19549                if reason == "recorded_command_mismatch"
19550        ));
19551    }
19552
19553    #[test]
19554    fn legacy_patch_preserves_pending_and_completed_activity_history() {
19555        for completed in [false, true] {
19556            let mut history = vec![history_event(
19557                "ActivityScheduled",
19558                json!({"sequence": 1, "activity_type": "old"}),
19559            )];
19560            if completed {
19561                history.push(history_event(
19562                    "ActivityCompleted",
19563                    json!({
19564                        "sequence": 1,
19565                        "activity_type": "old",
19566                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
19567                    }),
19568                ));
19569            }
19570            for _cold_replay in 0..2 {
19571                let ctx = workflow_context(history.clone());
19572                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
19573                assert!(!ctx.patched("added-step").expect("same frozen decision"));
19574                ctx.deprecate_patch("added-step")
19575                    .expect("retained boundary");
19576                let mut activity = Box::pin(ctx.activity("old", json!([])));
19577                let mut context = TaskContext::from_waker(noop_waker_ref());
19578                match activity.as_mut().poll(&mut context) {
19579                    Poll::Ready(result) => {
19580                        assert!(completed);
19581                        assert_eq!(result.expect("recorded result"), json!(41));
19582                        ctx.ensure_history_consumed().expect("old command retained");
19583                    }
19584                    Poll::Pending => assert!(!completed),
19585                }
19586                assert!(ctx.take_commands().expect("commands").is_empty());
19587            }
19588        }
19589    }
19590
19591    #[test]
19592    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
19593        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
19594        assert!(!ctx.patched("added-step").expect("legacy completed run"));
19595        ctx.deprecate_patch("added-step")
19596            .expect("same legacy decision");
19597        assert!(ctx.take_commands().expect("commands").is_empty());
19598        ctx.ensure_history_consumed().expect("completed history");
19599    }
19600
19601    #[test]
19602    fn legacy_patch_rejects_a_range_without_the_original_branch() {
19603        let ctx = workflow_context(vec![history_event(
19604            "ActivityScheduled",
19605            json!({"sequence": 1, "activity_type": "old"}),
19606        )]);
19607        let error = ctx
19608            .get_version("added-step", 0, 1)
19609            .expect_err("legacy is unsupported");
19610        assert!(matches!(
19611            error,
19612            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19613                if reason == "version_marker_incompatible_range"
19614        ));
19615        assert!(!ctx
19616            .patched("supported-step")
19617            .expect("failed check did not consume history"));
19618        assert!(ctx.take_commands().expect("commands").is_empty());
19619    }
19620
19621    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
19622        let mut event = history_event(
19623            "VersionMarkerRecorded",
19624            json!({
19625                "sequence": sequence,
19626                "change_id": "retained-patch",
19627                "version": version,
19628                "min_supported": -1,
19629                "max_supported": 1,
19630            }),
19631        );
19632        event.raw.insert("timestamp".into(), json!(time));
19633        event
19634    }
19635
19636    #[test]
19637    fn retained_patch_markers_preserve_each_original_boundary() {
19638        for completed in [false, true] {
19639            let mut history = vec![
19640                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19641                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19642                history_event(
19643                    "ActivityScheduled",
19644                    json!({"sequence": 3, "activity_type": "old"}),
19645                ),
19646            ];
19647            if completed {
19648                history.push(history_event(
19649                    "ActivityCompleted",
19650                    json!({
19651                        "sequence": 3,
19652                        "activity_type": "old",
19653                        "result": fixture_envelope(json!(41)),
19654                    }),
19655                ));
19656            }
19657            for _cold_replay in 0..2 {
19658                let ctx = workflow_context(history.clone());
19659                assert!(ctx.patched("retained-patch").unwrap());
19660                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19661                assert!(ctx.patched("retained-patch").unwrap());
19662                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19663                ctx.deprecate_patch("retained-patch").unwrap();
19664                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19665                let mut activity = Box::pin(ctx.activity("old", json!([])));
19666                let mut context = TaskContext::from_waker(noop_waker_ref());
19667                match activity.as_mut().poll(&mut context) {
19668                    Poll::Ready(result) => {
19669                        assert!(completed);
19670                        assert_eq!(result.unwrap(), json!(41));
19671                        ctx.ensure_history_consumed().unwrap();
19672                    }
19673                    Poll::Pending => assert!(!completed),
19674                }
19675                assert!(ctx.take_commands().unwrap().is_empty());
19676                let state = ctx.state.lock().unwrap();
19677                for (actual, original) in state.history_events.iter().zip(&history) {
19678                    assert_eq!(actual.payload, original.payload);
19679                    assert_eq!(actual.raw, original.raw);
19680                }
19681            }
19682        }
19683    }
19684
19685    #[test]
19686    fn retained_patch_aliases_do_not_skip_intervening_operations() {
19687        let ctx = workflow_context(vec![
19688            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19689            history_event(
19690                "SideEffectRecorded",
19691                json!({
19692                    "sequence": 2, "result": fixture_envelope(json!("between")),
19693                }),
19694            ),
19695            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
19696            history_event(
19697                "VersionMarkerRecorded",
19698                json!({
19699                    "sequence": 4, "change_id": "other-patch", "version": 1,
19700                    "min_supported": -1, "max_supported": 1,
19701                }),
19702            ),
19703        ]);
19704        assert!(ctx.patched("retained-patch").unwrap());
19705        assert!(ctx.patched("retained-patch").unwrap());
19706        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19707        assert_eq!(
19708            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19709            "between"
19710        );
19711        ctx.deprecate_patch("retained-patch").unwrap();
19712        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19713        ctx.deprecate_patch("retained-patch").unwrap();
19714        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19715        assert!(ctx.patched("other-patch").unwrap());
19716        ctx.ensure_history_consumed().unwrap();
19717        assert!(ctx.take_commands().unwrap().is_empty());
19718    }
19719
19720    #[test]
19721    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
19722        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19723        alias.payload["max_supported"] = json!(3);
19724        let ctx = workflow_context(vec![
19725            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19726            alias,
19727        ]);
19728        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
19729        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
19730        assert!(matches!(error,
19731            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19732                if reason == "version_marker_incompatible_range"));
19733        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19734        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
19735        ctx.ensure_history_consumed().unwrap();
19736        assert!(ctx.take_commands().unwrap().is_empty());
19737    }
19738
19739    #[test]
19740    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
19741        let ctx = workflow_context(Vec::new());
19742        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
19743        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
19744        assert!(ctx.patched("new-search").expect("patch"));
19745        ctx.deprecate_patch("new-search").expect("deprecate patch");
19746        let commands = ctx.take_commands().expect("commands");
19747        assert_eq!(commands.len(), 2);
19748        assert_eq!(commands[0]["type"], "record_version_marker");
19749        assert_eq!(commands[0]["version"], 2);
19750        assert_eq!(commands[1]["change_id"], "new-search");
19751
19752        let replay = workflow_context(vec![history_event(
19753            "VersionMarkerRecorded",
19754            json!({
19755                "sequence": 1,
19756                "change_id": "checkout-v2",
19757                "version": 2,
19758                "min_supported": 1,
19759                "max_supported": 2,
19760            }),
19761        )]);
19762        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
19763        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
19764        assert!(replay.take_commands().expect("commands").is_empty());
19765        replay.ensure_history_consumed().expect("history consumed");
19766    }
19767
19768    #[test]
19769    fn version_markers_reject_incompatible_or_malformed_history() {
19770        let incompatible = workflow_context(vec![history_event(
19771            "VersionMarkerRecorded",
19772            json!({
19773                "sequence": 1,
19774                "change_id": "checkout-v2",
19775                "version": 1,
19776                "min_supported": 1,
19777                "max_supported": 2,
19778            }),
19779        )]);
19780        let error = incompatible
19781            .get_version("checkout-v2", 2, 3)
19782            .expect_err("old version is unsupported");
19783        assert!(matches!(
19784            error,
19785            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19786                if reason == "version_marker_incompatible_range"
19787        ));
19788
19789        for (history, reason) in [
19790            (
19791                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
19792                "side_effect_result_missing",
19793            ),
19794            (
19795                vec![history_event(
19796                    "SideEffectRecorded",
19797                    json!({
19798                        "sequence": 1,
19799                        "result": {"codec": "avro", "blob": "not-base64"},
19800                    }),
19801                )],
19802                "side_effect_payload_incompatible",
19803            ),
19804            (
19805                vec![history_event(
19806                    "SideEffectRecorded",
19807                    json!({"sequence": 1, "result": {"unwrapped": true}}),
19808                )],
19809                "side_effect_payload_malformed",
19810            ),
19811            (
19812                vec![history_event(
19813                    "VersionMarkerRecorded",
19814                    json!({
19815                        "sequence": 1,
19816                        "change_id": "change",
19817                        "version": 1,
19818                        "min_supported": 2,
19819                        "max_supported": 1,
19820                    }),
19821                )],
19822                "version_marker_history_range_invalid",
19823            ),
19824        ] {
19825            let error = WorkflowState::new(
19826                history,
19827                "rust-workers".to_string(),
19828                DEFAULT_CODEC.to_string(),
19829                None,
19830            )
19831            .expect_err("malformed history must fail");
19832            assert!(matches!(
19833                error,
19834                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
19835                    if actual == reason
19836            ));
19837        }
19838    }
19839
19840    #[test]
19841    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
19842        let history = vec![history_event(
19843            "SearchAttributesUpserted",
19844            json!({
19845                "sequence": 1,
19846                "attributes": {"customer_tier": "gold"},
19847                "attribute_types": {"customer_tier": "keyword"},
19848                "merged": {"customer_tier": "gold"}
19849            }),
19850        )];
19851
19852        let matching = workflow_context(history.clone());
19853        matching
19854            .upsert_search_attributes(
19855                SearchAttributeUpdate::new()
19856                    .keyword("customer_tier", "gold")
19857                    .expect("keyword update"),
19858            )
19859            .expect("matching typed update must replay");
19860        matching
19861            .ensure_history_consumed()
19862            .expect("history consumed");
19863
19864        let changed_type = workflow_context(history.clone());
19865        let error = changed_type
19866            .upsert_search_attributes(
19867                SearchAttributeUpdate::new()
19868                    .string("customer_tier", "gold")
19869                    .expect("string update"),
19870            )
19871            .expect_err("same JSON value with a different declaration must be nondeterministic");
19872        let Error::NonDeterministicReplay(failure) = error else {
19873            panic!("typed identity drift must be a replay failure");
19874        };
19875        assert_eq!(failure.reason, "search_attribute_type_mismatch");
19876        assert_eq!(failure.sequence, Some(1));
19877
19878        let changed_value = workflow_context(history);
19879        let error = changed_value
19880            .upsert_search_attributes(
19881                SearchAttributeUpdate::new()
19882                    .keyword("customer_tier", "platinum")
19883                    .expect("keyword update"),
19884            )
19885            .expect_err("changed values must be nondeterministic");
19886        let Error::NonDeterministicReplay(failure) = error else {
19887            panic!("value drift must be a replay failure");
19888        };
19889        assert_eq!(failure.reason, "search_attribute_value_mismatch");
19890    }
19891
19892    #[test]
19893    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
19894        let history = vec![history_event(
19895            "SearchAttributesUpserted",
19896            json!({
19897                "sequence": 1,
19898                "attributes": {"customer_tier": "gold"},
19899                "merged": {"customer_tier": "gold"}
19900            }),
19901        )];
19902
19903        for update in [
19904            SearchAttributeUpdate::new()
19905                .keyword("customer_tier", "gold")
19906                .expect("keyword update"),
19907            SearchAttributeUpdate::new()
19908                .string("customer_tier", "gold")
19909                .expect("string update"),
19910        ] {
19911            let restarted = workflow_context(history.clone());
19912            restarted
19913                .upsert_search_attributes(update)
19914                .expect("legacy history constrains values but has unknown type identity");
19915            restarted
19916                .ensure_history_consumed()
19917                .expect("history consumed");
19918        }
19919    }
19920
19921    #[test]
19922    fn search_attribute_command_emits_canonical_types() {
19923        let ctx = workflow_context(Vec::new());
19924        ctx.upsert_search_attributes(
19925            SearchAttributeUpdate::new()
19926                .keyword("customer_tier", "gold")
19927                .expect("keyword update")
19928                .int("attempts", 3)
19929                .expect("int update")
19930                .delete("obsolete")
19931                .expect("delete update"),
19932        )
19933        .expect("valid search attributes");
19934
19935        assert_eq!(
19936            ctx.take_commands().expect("commands"),
19937            vec![json!({
19938                "type": "upsert_search_attributes",
19939                "attributes": {
19940                    "attempts": 3,
19941                    "customer_tier": "gold",
19942                    "obsolete": null
19943                },
19944                "attribute_types": {
19945                    "attempts": "int",
19946                    "customer_tier": "keyword"
19947                }
19948            })]
19949        );
19950    }
19951
19952    #[test]
19953    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
19954        let duplicate_side_effect = WorkflowState::new(
19955            vec![
19956                history_event(
19957                    "SideEffectRecorded",
19958                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
19959                ),
19960                history_event(
19961                    "SideEffectRecorded",
19962                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
19963                ),
19964            ],
19965            "rust-workers".to_string(),
19966            DEFAULT_CODEC.to_string(),
19967            None,
19968        )
19969        .expect_err("duplicate side effect");
19970        assert!(matches!(
19971            duplicate_side_effect,
19972            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19973                if reason == "duplicate_side_effect_record"
19974        ));
19975
19976        let marker = |sequence, version| {
19977            history_event(
19978                "VersionMarkerRecorded",
19979                json!({
19980                    "sequence": sequence,
19981                    "change_id": "same-change",
19982                    "version": version,
19983                    "min_supported": -1,
19984                    "max_supported": 1,
19985                }),
19986            )
19987        };
19988        let duplicate_marker = WorkflowState::new(
19989            vec![marker(1, 1), marker(3, -1)],
19990            "rust-workers".to_string(),
19991            DEFAULT_CODEC.to_string(),
19992            None,
19993        )
19994        .expect_err("conflicting marker");
19995        assert!(matches!(
19996            duplicate_marker,
19997            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19998                if reason == "version_marker_conflict"
19999        ));
20000    }
20001
20002    #[test]
20003    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
20004        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
20005        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20006        invalid_alias.payload["max_supported"] = json!(0);
20007        for (history, expected_reason) in [
20008            (
20009                vec![marker.clone(), marker.clone()],
20010                "duplicate_version_marker_record",
20011            ),
20012            (
20013                vec![marker, invalid_alias],
20014                "version_marker_history_range_invalid",
20015            ),
20016        ] {
20017            let error =
20018                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
20019                    .expect_err("invalid historical alias");
20020            assert!(matches!(error,
20021                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
20022                    if reason == expected_reason));
20023        }
20024    }
20025
20026    #[test]
20027    fn retained_patch_aliases_require_the_original_call_boundary() {
20028        let ctx = workflow_context(vec![
20029            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20030            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20031        ]);
20032        assert!(ctx.patched("retained-patch").unwrap());
20033        assert!(ctx.ensure_history_consumed().is_err());
20034        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20035        ctx.deprecate_patch("retained-patch").unwrap();
20036        ctx.ensure_history_consumed().unwrap();
20037        assert!(ctx.take_commands().unwrap().is_empty());
20038    }
20039
20040    #[test]
20041    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
20042        let ctx = workflow_context(vec![
20043            history_event(
20044                "SideEffectRecorded",
20045                json!({
20046                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
20047                }),
20048            ),
20049            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20050        ]);
20051        assert!(!ctx.patched("retained-patch").unwrap());
20052        assert_eq!(
20053            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20054            "old-operation"
20055        );
20056        let error = ctx.patched("retained-patch").unwrap_err();
20057        assert!(matches!(error,
20058            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20059                if reason == "version_marker_conflict"));
20060        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20061        assert!(ctx.take_commands().unwrap().is_empty());
20062    }
20063
20064    #[test]
20065    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
20066        let mut state = WorkflowState::new(
20067            Vec::new(),
20068            "rust-workers".to_string(),
20069            DEFAULT_CODEC.to_string(),
20070            None,
20071        )
20072        .expect("workflow state");
20073        state.workflow_command_identity = "command-7".to_string();
20074        let context = WorkflowContext {
20075            state: Arc::new(Mutex::new(state)),
20076            cancellation_scope_id: "root".into(),
20077        };
20078        let item =
20079            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
20080
20081        context
20082            .append_workflow_stream("output", &[item], Some(10))
20083            .expect("append command");
20084        context
20085            .error_workflow_stream("output", "producer failed", None)
20086            .expect("error command");
20087        let commands = context.take_commands().expect("commands");
20088
20089        assert_eq!(commands[0]["type"], "record_side_effect");
20090        assert_eq!(
20091            commands[0]["workflow_stream"]["command_identity"],
20092            "command-7"
20093        );
20094        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
20095        assert_eq!(
20096            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20097            "dw-stream:command-7:0:0"
20098        );
20099        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
20100
20101        let recorded = history_event(
20102            "SideEffectRecorded",
20103            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
20104        );
20105        let mut replay_state = WorkflowState::new(
20106            vec![recorded],
20107            "rust-workers".to_string(),
20108            DEFAULT_CODEC.to_string(),
20109            None,
20110        )
20111        .expect("replay state");
20112        replay_state.workflow_command_identity = "command-7".to_string();
20113        let replay_context = WorkflowContext {
20114            state: Arc::new(Mutex::new(replay_state)),
20115            cancellation_scope_id: "root".into(),
20116        };
20117        replay_context
20118            .append_workflow_stream(
20119                "output",
20120                &[WorkflowStreamAppendItem::from_reference(
20121                    "s3://bucket/item.avro",
20122                )],
20123                Some(10),
20124            )
20125            .expect("replayed append");
20126        assert!(replay_context
20127            .take_commands()
20128            .expect("replayed commands")
20129            .is_empty());
20130    }
20131
20132    #[test]
20133    fn workflow_stream_authoring_requires_server_durable_command_identity() {
20134        let context = workflow_context(Vec::new());
20135        let error = context
20136            .append_workflow_stream(
20137                "output",
20138                &[WorkflowStreamAppendItem::from_reference(
20139                    "s3://bucket/item.avro",
20140                )],
20141                None,
20142            )
20143            .expect_err("stream append without durable command identity must fail closed");
20144
20145        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
20146        assert!(context.take_commands().expect("commands").is_empty());
20147    }
20148
20149    #[test]
20150    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
20151        let client = Client::builder("http://localhost:8080").build().unwrap();
20152        let mut worker = Worker::new(client, "rust-workers");
20153        worker.register_workflow("streams.worker", |ctx, _| async move {
20154            ctx.append_workflow_stream(
20155                "output",
20156                &[WorkflowStreamAppendItem::new(json!("hello"))?],
20157                None,
20158            )?;
20159            ctx.close_workflow_stream("output", None)?;
20160            Ok(json!("done"))
20161        });
20162        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
20163            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20164            task.workflow_command_id = command_id.clone();
20165            let expected_identity = command_id
20166                .as_deref()
20167                .filter(|id| !id.is_empty())
20168                .unwrap_or(&task.task_id)
20169                .to_string();
20170            let commands = worker
20171                .execute_workflow_task(task)
20172                .expect("ordinary worker stream output");
20173            assert_eq!(commands.len(), 3);
20174            assert_eq!(
20175                commands[0]["workflow_stream"]["command_identity"],
20176                expected_identity
20177            );
20178            assert_eq!(
20179                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20180                format!("dw-stream:{expected_identity}:0:0")
20181            );
20182            assert_eq!(
20183                commands[1]["workflow_stream"]["command_identity"],
20184                expected_identity
20185            );
20186            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
20187            let history = commands[..2]
20188                .iter()
20189                .enumerate()
20190                .map(|(index, command)| {
20191                    history_event(
20192                        "SideEffectRecorded",
20193                        json!({"sequence":index + 1,"result":command["result"]}),
20194                    )
20195                })
20196                .collect();
20197            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
20198            replay.task_id = "replacement-task".to_string();
20199            let replayed = worker
20200                .execute_workflow_task(replay)
20201                .expect("replacement worker consumes recorded stream effects");
20202            assert_eq!(replayed.len(), 1);
20203            assert_eq!(replayed[0]["type"], "complete_workflow");
20204        }
20205        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20206        missing.task_id.clear();
20207        assert!(matches!(
20208            worker.execute_workflow_task(missing),
20209            Err(Error::MissingWorkflowCommandIdentity)
20210        ));
20211    }
20212
20213    #[test]
20214    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
20215        fn worker(calls: Arc<AtomicUsize>) -> Worker {
20216            let client = Client::new("http://127.0.0.1:8080").expect("client");
20217            let mut worker = Worker::new(client, "rust-workers");
20218            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
20219                let calls = Arc::clone(&calls);
20220                async move {
20221                    let captured = ctx.side_effect(|| {
20222                        calls.fetch_add(1, Ordering::SeqCst);
20223                        "captured-once".to_string()
20224                    })?;
20225                    let version = ctx.get_version("cold-restart", 1, 2)?;
20226                    Ok(json!({"captured": captured, "version": version}))
20227                }
20228            });
20229            worker
20230        }
20231
20232        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
20233            WorkflowTask {
20234                task_id: "wft-side-effect-version".to_string(),
20235                workflow_command_id: None,
20236                workflow_id: Some("wf-side-effect-version".to_string()),
20237                run_id: Some("run-side-effect-version".to_string()),
20238                workflow_type: "rust.side-effect-version".to_string(),
20239                cancel_requested: false,
20240                payload_codec: DEFAULT_CODEC.to_string(),
20241                arguments: Some(
20242                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
20243                ),
20244                history_events,
20245                total_history_events: None,
20246                history_size_bytes: None,
20247                continue_as_new_recommended: None,
20248                history_budget_pressure: None,
20249                next_history_page_token: None,
20250                workflow_task_attempt: 1,
20251                workflow_signal_id: None,
20252                signal_name: None,
20253                signal_arguments: None,
20254                workflow_update_id: None,
20255                update_name: None,
20256                lease_owner: Some("rust-worker".to_string()),
20257            }
20258        }
20259
20260        let calls = Arc::new(AtomicUsize::new(0));
20261        let initial = worker(Arc::clone(&calls))
20262            .execute_workflow_task(task(Vec::new()))
20263            .expect("initial execution");
20264        assert_eq!(
20265            initial
20266                .iter()
20267                .map(|command| &command["type"])
20268                .collect::<Vec<_>>(),
20269            vec![
20270                "record_side_effect",
20271                "record_version_marker",
20272                "complete_workflow"
20273            ]
20274        );
20275        assert_eq!(calls.load(Ordering::SeqCst), 1);
20276
20277        let restarted = worker(Arc::clone(&calls));
20278        let replayed = restarted
20279            .execute_workflow_task(task(vec![
20280                history_event(
20281                    "SideEffectRecorded",
20282                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
20283                ),
20284                history_event(
20285                    "VersionMarkerRecorded",
20286                    json!({
20287                        "sequence": 2,
20288                        "change_id": "cold-restart",
20289                        "version": 2,
20290                        "min_supported": 1,
20291                        "max_supported": 2,
20292                    }),
20293                ),
20294            ]))
20295            .expect("cold replay");
20296        assert_eq!(replayed.len(), 1);
20297        assert_eq!(replayed[0]["type"], "complete_workflow");
20298        assert_eq!(calls.load(Ordering::SeqCst), 1);
20299    }
20300
20301    #[test]
20302    fn side_effect_replay_rejects_changed_rust_value_type() {
20303        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
20304        let ctx = workflow_context(vec![history_event(
20305            "SideEffectRecorded",
20306            json!({"sequence": 1, "result": result}),
20307        )]);
20308        let error = ctx
20309            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
20310            .expect_err("changed type must fail replay");
20311        assert!(matches!(
20312            error,
20313            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20314                if reason == "side_effect_type_mismatch"
20315        ));
20316    }
20317
20318    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
20319        vec![
20320            history_event(
20321                "ActivityScheduled",
20322                json!({
20323                    "sequence": 1,
20324                    "activity_type": "flaky",
20325                    "activity_execution_id": "act-1",
20326                    "activity": {
20327                        "id": "act-1",
20328                        "sequence": 1,
20329                        "type": "flaky",
20330                        "queue": "critical-activities",
20331                        "execution_mode": null,
20332                        "retry_policy": {
20333                            "snapshot_version": 1,
20334                            "max_attempts": 3,
20335                            "backoff_seconds": [2, 4],
20336                            "start_to_close_timeout": 30,
20337                            "schedule_to_start_timeout": 5,
20338                            "schedule_to_close_timeout": 90,
20339                            "heartbeat_timeout": 10,
20340                            "non_retryable_error_types": ["PermanentError"]
20341                        }
20342                    }
20343                }),
20344            ),
20345            history_event(
20346                "ActivityStarted",
20347                json!({
20348                    "sequence": 1,
20349                    "activity_type": "flaky",
20350                    "activity_execution_id": "act-1",
20351                    "activity_attempt_id": "attempt-1",
20352                    "attempt_number": 1
20353                }),
20354            ),
20355            history_event(
20356                "ActivityRetryScheduled",
20357                json!({
20358                    "sequence": 1,
20359                    "activity_type": "flaky",
20360                    "activity_execution_id": "act-1",
20361                    "activity_attempt_id": "attempt-1",
20362                    "attempt_number": 1,
20363                    "retry_after_attempt": 1,
20364                    "retry_backoff_seconds": 2,
20365                    "failure_category": "activity",
20366                    "exception_type": "TransientError"
20367                }),
20368            ),
20369            history_event(
20370                "ActivityStarted",
20371                json!({
20372                    "sequence": 1,
20373                    "activity_type": "flaky",
20374                    "activity_execution_id": "act-1",
20375                    "activity_attempt_id": "attempt-2",
20376                    "attempt_number": 2
20377                }),
20378            ),
20379            history_event(
20380                "ActivityCompleted",
20381                json!({
20382                    "sequence": 1,
20383                    "activity_type": "flaky",
20384                    "activity_execution_id": "act-1",
20385                    "activity_attempt_id": "attempt-2",
20386                    "attempt_number": 2,
20387                    "payload_codec": DEFAULT_CODEC,
20388                    "result": fixture_envelope(json!({"status":"recovered"}))
20389                }),
20390            ),
20391        ]
20392    }
20393
20394    fn retry_activity_options() -> ActivityOptions {
20395        ActivityOptions::new()
20396            .task_queue("critical-activities")
20397            .retry_policy(
20398                ActivityRetryPolicy::new(3)
20399                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
20400                    .non_retryable_error_type("PermanentError"),
20401            )
20402            .start_to_close_timeout(Duration::from_secs(30))
20403            .schedule_to_start_timeout(Duration::from_secs(5))
20404            .schedule_to_close_timeout(Duration::from_secs(90))
20405            .heartbeat_timeout(Duration::from_secs(10))
20406    }
20407
20408    #[test]
20409    fn fixed_avro_value_round_trips_json_values() {
20410        let value = json!({"greeting": "hello", "count": 3, "ok": true});
20411        let envelope = PayloadEnvelope::avro(&value).expect("encode");
20412        assert_eq!(envelope.codec, DEFAULT_CODEC);
20413        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
20414    }
20415
20416    #[tokio::test]
20417    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
20418        let client = Client::new("http://127.0.0.1:8080").expect("client");
20419        let mut worker = Worker::new(client, "rust-workers");
20420        worker.register_typed_workflow(
20421            "typed.contract.workflow",
20422            |_ctx, input: TypedContract| async move { Ok(input) },
20423        );
20424        worker.register_typed_activity(
20425            "typed.contract.activity",
20426            |_ctx, input: TypedContract| async move { Ok(input) },
20427        );
20428
20429        let expected = typed_contract();
20430        let arguments = AvroValue::Array(vec![
20431            AvroValue::from_serialize(&expected).expect("typed request")
20432        ]);
20433        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
20434        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
20435        workflow.arguments = Some(envelope.clone());
20436        let commands = worker
20437            .execute_workflow_task(workflow)
20438            .expect("typed workflow task");
20439        let workflow_result: TypedContract =
20440            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20441                .expect("workflow result envelope")
20442                .deserialize()
20443                .expect("workflow result type");
20444        assert_eq!(workflow_result, expected);
20445
20446        let activity = ActivityTask {
20447            task_id: "typed-contract-activity".to_string(),
20448            activity_attempt_id: Some("typed-contract-attempt".to_string()),
20449            attempt_id: None,
20450            activity_type: "typed.contract.activity".to_string(),
20451            payload_codec: DEFAULT_CODEC.to_string(),
20452            arguments: Some(envelope),
20453            attempt_number: 1,
20454            lease_owner: Some("rust-worker".to_string()),
20455        };
20456        let activity_result: TypedContract = worker
20457            .execute_activity_task(activity)
20458            .await
20459            .expect("typed activity task")
20460            .deserialize()
20461            .expect("activity result type");
20462        assert_eq!(activity_result, expected);
20463    }
20464
20465    #[tokio::test]
20466    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
20467        let client = Client::new("http://127.0.0.1:8080").expect("client");
20468        let mut worker = Worker::new(client, "rust-workers");
20469        worker.register_typed_workflow(
20470            "typed.shape.workflow",
20471            |_ctx, input: TypedContract| async move { Ok(input) },
20472        );
20473        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
20474            Ok(f64::NAN)
20475        });
20476
20477        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
20478        workflow.arguments = Some(
20479            encode_typed_envelope(
20480                &AvroValue::Array(vec![
20481                    AvroValue::String("first".to_string()),
20482                    AvroValue::String("second".to_string()),
20483                ]),
20484                DEFAULT_CODEC,
20485            )
20486            .expect("malformed typed arguments"),
20487        );
20488        let commands = worker
20489            .execute_workflow_task(workflow)
20490            .expect("shape mismatch becomes a workflow failure");
20491        let message = commands[0]["message"].as_str().expect("failure message");
20492        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
20493        assert!(message.contains(type_name::<TypedContract>()));
20494        assert!(message.contains("task carried 2 arguments"));
20495
20496        let activity = ActivityTask {
20497            task_id: "typed-unsupported-activity".to_string(),
20498            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
20499            attempt_id: None,
20500            activity_type: "typed.unsupported.activity".to_string(),
20501            payload_codec: DEFAULT_CODEC.to_string(),
20502            arguments: Some(
20503                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20504                    .expect("unit arguments"),
20505            ),
20506            attempt_number: 1,
20507            lease_owner: Some("rust-worker".to_string()),
20508        };
20509        let Error::HandlerType {
20510            handler_kind,
20511            handler_name,
20512            value_kind,
20513            rust_type,
20514            message,
20515        } = worker
20516            .execute_activity_task(activity)
20517            .await
20518            .expect_err("non-finite handler output must fail")
20519        else {
20520            panic!("expected contextual handler type failure");
20521        };
20522        assert_eq!(handler_kind, HandlerKind::Activity);
20523        assert_eq!(handler_name, "typed.unsupported.activity");
20524        assert_eq!(value_kind, HandlerValueKind::Result);
20525        assert_eq!(rust_type, type_name::<f64>());
20526        assert!(message.contains("non_finite_float"));
20527    }
20528
20529    #[tokio::test]
20530    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
20531        #[derive(Clone, Default)]
20532        struct State {
20533            observed: Option<TypedContract>,
20534        }
20535
20536        let client = Client::new("http://127.0.0.1:8080").expect("client");
20537        let mut worker = Worker::new(client, "rust-workers");
20538        worker.register_typed_replayed_workflow(
20539            "typed.contract.replayed",
20540            State::default,
20541            |ctx, input: TypedContract, state| async move {
20542                let result: TypedContract =
20543                    ctx.activity_typed("typed.contract.activity", input).await?;
20544                state.update(|current| current.observed = Some(result.clone()))?;
20545                Ok(result)
20546            },
20547        );
20548        worker.register_replayed_query::<State, _, _>(
20549            "typed.contract.replayed",
20550            "observed",
20551            |_ctx, state, _args| async move {
20552                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
20553            },
20554        );
20555
20556        let expected = typed_contract();
20557        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
20558        let workflow_arguments =
20559            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
20560                .expect("workflow arguments");
20561        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
20562        let task = QueryTask {
20563            query_task_id: "typed-replay-query".to_string(),
20564            query_task_attempt: 1,
20565            lease_owner: Some("rust-worker".to_string()),
20566            workflow_id: Some("typed-replay".to_string()),
20567            run_id: Some("typed-replay-run".to_string()),
20568            workflow_type: "typed.contract.replayed".to_string(),
20569            query_name: "observed".to_string(),
20570            payload_codec: DEFAULT_CODEC.to_string(),
20571            workflow_arguments: Some(workflow_arguments),
20572            query_arguments: Some(
20573                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20574                    .expect("query arguments"),
20575            ),
20576            history_events: vec![
20577                history_event(
20578                    "ActivityScheduled",
20579                    json!({
20580                        "sequence": 1,
20581                        "activity_type": "typed.contract.activity"
20582                    }),
20583                ),
20584                history_event(
20585                    "ActivityCompleted",
20586                    json!({
20587                        "sequence": 1,
20588                        "activity_type": "typed.contract.activity",
20589                        "payload_codec": DEFAULT_CODEC,
20590                        "result": result
20591                    }),
20592                ),
20593            ],
20594            history_export: None,
20595            run_status: Some("completed".to_string()),
20596        };
20597
20598        assert_eq!(
20599            worker
20600                .execute_query_task(task)
20601                .await
20602                .expect("typed replay query")
20603                .deserialize::<i64>()
20604                .expect("query result"),
20605            expected.signed
20606        );
20607    }
20608
20609    #[tokio::test]
20610    async fn update_context_preserves_workflow_input_and_committed_signals() {
20611        let client = Client::new("http://127.0.0.1:8080").expect("client");
20612        let mut worker = Worker::new(client, "rust-workers");
20613        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20614        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
20615        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
20616        let expected_input = workflow_input.clone();
20617        let expected_signals = signal_arguments.clone();
20618        let handler = move |context: QueryContext, arguments: AvroValue| {
20619            let expected_input = expected_input.clone();
20620            let expected_signals = expected_signals.clone();
20621            async move {
20622                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
20623                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
20624                assert_eq!(context.workflow_input_avro_value(), &expected_input);
20625                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
20626                assert_eq!(
20627                    context.signals_avro_value("changed"),
20628                    vec![expected_signals.clone()]
20629                );
20630                assert_eq!(
20631                    context.signals("changed"),
20632                    vec![expected_signals
20633                        .into_iter()
20634                        .map(AvroValue::into_json)
20635                        .collect::<Result<Vec<_>>>()?]
20636                );
20637                assert_eq!(
20638                    context.signal_events()[0].id.as_deref(),
20639                    Some("signal-original")
20640                );
20641                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
20642                Ok(arguments)
20643            }
20644        };
20645        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
20646        worker.register_update_avro_value("snapshot", "inspect", handler);
20647        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
20648        let update_envelope =
20649            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
20650        let mut task = workflow_task(
20651            "snapshot",
20652            vec![
20653                history_event(
20654                    "SignalReceived",
20655                    json!({
20656                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
20657                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
20658                    }),
20659                ),
20660                history_event(
20661                    "UpdateAccepted",
20662                    json!({
20663                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
20664                    }),
20665                ),
20666            ],
20667            DEFAULT_CODEC,
20668        );
20669        task.arguments =
20670            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
20671        task.workflow_update_id = Some("update-original".into());
20672        task.update_name = Some("inspect".into());
20673        let query = QueryTask {
20674            query_task_id: "query-snapshot".into(),
20675            query_task_attempt: 1,
20676            lease_owner: None,
20677            workflow_id: task.workflow_id.clone(),
20678            run_id: task.run_id.clone(),
20679            workflow_type: task.workflow_type.clone(),
20680            query_name: "inspect".into(),
20681            payload_codec: DEFAULT_CODEC.into(),
20682            workflow_arguments: task.arguments.clone(),
20683            query_arguments: Some(update_envelope),
20684            history_events: task.history_events.clone(),
20685            history_export: None,
20686            run_status: Some("running".into()),
20687        };
20688        assert_eq!(
20689            worker
20690                .execute_query_task(query)
20691                .await
20692                .expect("query snapshot"),
20693            update_arguments
20694        );
20695        for _ in 0..2 {
20696            let commands = worker
20697                .execute_workflow_task(task.clone())
20698                .expect("cold update snapshot");
20699            assert_eq!(commands[0]["type"], "complete_update");
20700            assert_eq!(commands[0]["update_id"], "update-original");
20701            assert_eq!(
20702                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20703                    .expect("update result"),
20704                update_arguments
20705            );
20706        }
20707    }
20708
20709    #[test]
20710    fn committed_signal_snapshot_counts_identities_once() {
20711        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
20712        let received = history_event(
20713            "SignalReceived",
20714            json!({
20715                "signal_id": "signal-first", "workflow_command_id": "command-first",
20716                "signal_name": "changed", "arguments": arguments.clone(),
20717            }),
20718        );
20719        let applied = history_event(
20720            "SignalApplied",
20721            json!({
20722                "signal_id": "signal-first", "workflow_command_id": "command-first",
20723                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
20724            }),
20725        );
20726        let distinct = history_event(
20727            "SignalReceived",
20728            json!({
20729                "signal_id": "signal-second", "workflow_command_id": "command-second",
20730                "signal_name": "changed", "arguments": arguments,
20731            }),
20732        );
20733        let history = vec![received.clone(), applied.clone(), distinct];
20734        let signals =
20735            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
20736        assert_eq!(signals.len(), 2);
20737        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20738        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
20739        assert_eq!(signals[0].workflow_sequence, Some(1));
20740        assert_eq!(signals[0].arguments, signals[1].arguments);
20741        let mut command_only = received.clone();
20742        command_only
20743            .payload
20744            .as_object_mut()
20745            .expect("payload")
20746            .remove("signal_id");
20747        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
20748            .expect("command identity");
20749        assert_eq!(signals.len(), 1);
20750        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20751        let mut conflicting = applied;
20752        conflicting.payload["value"] =
20753            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
20754        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
20755    }
20756
20757    #[test]
20758    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
20759        for arguments in [
20760            vec![],
20761            vec![AvroValue::Array(vec![
20762                AvroValue::Long(1),
20763                AvroValue::Long(2),
20764            ])],
20765            vec![AvroValue::Bytes(vec![0, 255])],
20766            vec![AvroValue::Null],
20767            vec![AvroValue::Boolean(false)],
20768            vec![
20769                AvroValue::Long(1),
20770                AvroValue::Array(vec![AvroValue::Long(2)]),
20771            ],
20772        ] {
20773            let applied = match arguments.as_slice() {
20774                [] => AvroValue::Boolean(true),
20775                [value] => value.clone(),
20776                values => AvroValue::Array(values.to_vec()),
20777            };
20778            for applied in [applied, AvroValue::Array(arguments.clone())] {
20779                let events = vec![
20780                    history_event(
20781                        "SignalReceived",
20782                        json!({
20783                            "signal_id": "original", "signal_name": "changed",
20784                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
20785                        }),
20786                    ),
20787                    history_event(
20788                        "SignalApplied",
20789                        json!({
20790                            "signal_id": "original", "signal_name": "changed",
20791                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
20792                        }),
20793                    ),
20794                ];
20795                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
20796                    .expect("canonical signal snapshot");
20797                assert_eq!(signals.len(), 1);
20798                assert_eq!(signals[0].avro_arguments, arguments);
20799            }
20800        }
20801    }
20802
20803    #[tokio::test]
20804    async fn update_context_rejects_malformed_snapshot_before_handler() {
20805        let client = Client::new("http://127.0.0.1:8080").expect("client");
20806        let mut worker = Worker::new(client, "rust-workers");
20807        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20808        let calls = Arc::new(AtomicUsize::new(0));
20809        let observed = Arc::clone(&calls);
20810        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
20811            observed.fetch_add(1, Ordering::SeqCst);
20812            async { Ok(Value::Null) }
20813        });
20814        let mut task = workflow_task(
20815            "snapshot",
20816            vec![history_event(
20817                "UpdateAccepted",
20818                json!({
20819                    "update_id": "update-original", "update_name": "inspect",
20820                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
20821                }),
20822            )],
20823            DEFAULT_CODEC,
20824        );
20825        task.workflow_update_id = Some("update-original".into());
20826        task.update_name = Some("inspect".into());
20827        let mut bad_input = task.clone();
20828        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
20829        assert!(worker.execute_workflow_task(bad_input).is_err());
20830        task.history_events.insert(0, history_event("SignalReceived", json!({
20831            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
20832        })));
20833        assert!(worker.execute_workflow_task(task).is_err());
20834        assert_eq!(calls.load(Ordering::SeqCst), 0);
20835    }
20836
20837    #[tokio::test]
20838    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
20839        let client = Client::new("http://127.0.0.1:8080").expect("client");
20840        let mut worker = Worker::new(client, "rust-workers");
20841        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
20842        worker
20843            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
20844        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
20845            Ok(input)
20846        });
20847        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
20848            Ok(input)
20849        });
20850        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
20851            Ok(AvroValue::Array(
20852                ctx.wait_signal_avro_value("changed").await?,
20853            ))
20854        });
20855
20856        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
20857        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
20858
20859        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
20860        workflow.arguments = Some(envelope.clone());
20861        let commands = worker
20862            .execute_workflow_task(workflow)
20863            .expect("typed workflow task");
20864        assert_eq!(commands[0]["type"], "complete_workflow");
20865        assert_eq!(
20866            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20867                .expect("typed workflow result"),
20868            arguments
20869        );
20870
20871        let activity = ActivityTask {
20872            task_id: "activity-typed".to_string(),
20873            activity_attempt_id: Some("attempt-typed".to_string()),
20874            attempt_id: None,
20875            activity_type: "typed.activity".to_string(),
20876            payload_codec: DEFAULT_CODEC.to_string(),
20877            arguments: Some(envelope.clone()),
20878            attempt_number: 1,
20879            lease_owner: Some("rust-worker".to_string()),
20880        };
20881        assert_eq!(
20882            worker
20883                .execute_activity_task(activity)
20884                .await
20885                .expect("typed activity result"),
20886            arguments
20887        );
20888
20889        let query = QueryTask {
20890            query_task_id: "query-typed".to_string(),
20891            query_task_attempt: 1,
20892            lease_owner: Some("rust-worker".to_string()),
20893            workflow_id: Some("typed-1".to_string()),
20894            run_id: Some("run-typed".to_string()),
20895            workflow_type: "typed.echo".to_string(),
20896            query_name: "inspect".to_string(),
20897            payload_codec: DEFAULT_CODEC.to_string(),
20898            workflow_arguments: Some(
20899                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20900                    .expect("workflow input"),
20901            ),
20902            query_arguments: Some(envelope.clone()),
20903            history_events: Vec::new(),
20904            history_export: None,
20905            run_status: Some("running".to_string()),
20906        };
20907        assert_eq!(
20908            worker
20909                .execute_query_task(query)
20910                .await
20911                .expect("typed query result"),
20912            arguments
20913        );
20914
20915        let mut update = workflow_task(
20916            "typed.echo",
20917            vec![history_event(
20918                "UpdateAccepted",
20919                json!({
20920                    "update_id": "update-typed",
20921                    "update_name": "replace",
20922                    "arguments": envelope.clone(),
20923                }),
20924            )],
20925            DEFAULT_CODEC,
20926        );
20927        update.workflow_update_id = Some("update-typed".to_string());
20928        update.update_name = Some("replace".to_string());
20929        let commands = worker
20930            .execute_workflow_task(update)
20931            .expect("typed update task");
20932        assert_eq!(commands[0]["type"], "complete_update");
20933        assert_eq!(
20934            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20935                .expect("typed update result"),
20936            arguments
20937        );
20938
20939        let mut signal = workflow_task(
20940            "typed.signal",
20941            vec![history_event(
20942                "SignalReceived",
20943                json!({
20944                    "signal_id": "signal-typed",
20945                    "signal_name": "changed",
20946                    "arguments": envelope.clone(),
20947                }),
20948            )],
20949            DEFAULT_CODEC,
20950        );
20951        signal.workflow_signal_id = Some("signal-typed".to_string());
20952        signal.signal_name = Some("changed".to_string());
20953        signal.signal_arguments = Some(envelope);
20954        let commands = worker
20955            .execute_workflow_task(signal)
20956            .expect("typed signal resume");
20957        assert_eq!(
20958            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20959                .expect("typed signal result"),
20960            arguments
20961        );
20962    }
20963
20964    #[tokio::test]
20965    async fn typed_helpers_never_parse_json_inspection_projection() {
20966        let collision_values = projection_collision_probe();
20967        let expected = AvroValue::Array(collision_values.clone());
20968        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
20969
20970        let activity_context = workflow_context_with_codec(
20971            vec![history_event(
20972                "ActivityCompleted",
20973                json!({
20974                    "sequence": 1,
20975                    "activity_type": "collision.activity",
20976                    "payload_codec": DEFAULT_CODEC,
20977                    "result": envelope.clone(),
20978                }),
20979            )],
20980            DEFAULT_CODEC,
20981        );
20982        assert_eq!(
20983            activity_context
20984                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
20985                .await
20986                .expect("typed activity collision result"),
20987            expected
20988        );
20989
20990        let signal_context = workflow_context_with_codec(
20991            vec![
20992                history_event(
20993                    "SignalWaitOpened",
20994                    json!({"sequence": 1, "signal_name": "collision"}),
20995                ),
20996                history_event(
20997                    "SignalApplied",
20998                    json!({
20999                        "sequence": 1,
21000                        "signal_name": "collision",
21001                        "payload_codec": DEFAULT_CODEC,
21002                        "value": envelope.clone(),
21003                    }),
21004                ),
21005            ],
21006            DEFAULT_CODEC,
21007        );
21008        assert_eq!(
21009            signal_context
21010                .wait_signal_avro_value("collision")
21011                .await
21012                .expect("typed signal collision arguments"),
21013            collision_values
21014        );
21015
21016        let child_context = workflow_context_with_codec(
21017            vec![
21018                history_event(
21019                    "ChildWorkflowScheduled",
21020                    json!({
21021                        "sequence": 1,
21022                        "child_workflow_instance_id": "collision-child",
21023                        "child_workflow_run_id": "collision-run",
21024                        "child_workflow_type": "collision.child",
21025                    }),
21026                ),
21027                history_event(
21028                    "ChildRunCompleted",
21029                    json!({
21030                        "sequence": 1,
21031                        "child_workflow_instance_id": "collision-child",
21032                        "child_workflow_run_id": "collision-run",
21033                        "child_workflow_type": "collision.child",
21034                        "payload_codec": DEFAULT_CODEC,
21035                        "result": envelope,
21036                    }),
21037                ),
21038            ],
21039            DEFAULT_CODEC,
21040        );
21041        let child = child_context
21042            .start_child_workflow_avro_value(
21043                "collision.child",
21044                ChildWorkflowOptions::new("collision-workers"),
21045                AvroValue::Array(Vec::new()),
21046            )
21047            .await
21048            .expect("typed child collision result");
21049        assert_eq!(child.result, expected);
21050    }
21051
21052    #[tokio::test]
21053    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
21054        let client = Client::new("http://127.0.0.1:8080").expect("client");
21055        let mut worker = Worker::new(client, "rust-workers");
21056        worker.register_replayed_workflow_avro_value(
21057            "typed.replayed",
21058            || (),
21059            |_ctx, input, _state| async move { Ok(input) },
21060        );
21061        worker.register_replayed_query_avro_value::<(), _, _>(
21062            "typed.replayed",
21063            "inspect",
21064            |ctx, _state, args| async move {
21065                let mut signals = ctx.signals_avro_value("collision");
21066                let signal = signals
21067                    .pop()
21068                    .map(AvroValue::Array)
21069                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
21070                Ok(AvroValue::Array(vec![
21071                    ctx.workflow_input_avro_value().clone(),
21072                    signal,
21073                    args,
21074                ]))
21075            },
21076        );
21077        let arguments = AvroValue::Array(projection_collision_probe());
21078        let signal_arguments =
21079            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
21080        let task = QueryTask {
21081            query_task_id: "query-typed-replay".to_string(),
21082            query_task_attempt: 1,
21083            lease_owner: Some("rust-worker".to_string()),
21084            workflow_id: Some("typed-replay".to_string()),
21085            run_id: Some("run-typed-replay".to_string()),
21086            workflow_type: "typed.replayed".to_string(),
21087            query_name: "inspect".to_string(),
21088            payload_codec: DEFAULT_CODEC.to_string(),
21089            workflow_arguments: Some(
21090                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
21091            ),
21092            query_arguments: Some(
21093                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
21094            ),
21095            history_events: vec![history_event(
21096                "SignalReceived",
21097                json!({
21098                    "signal_id": "collision-signal",
21099                    "signal_name": "collision",
21100                    "workflow_sequence": 1,
21101                    "payload_codec": DEFAULT_CODEC,
21102                    "arguments": signal_arguments,
21103                }),
21104            )],
21105            history_export: None,
21106            run_status: Some("completed".to_string()),
21107        };
21108
21109        assert_eq!(
21110            worker
21111                .execute_query_task(task)
21112                .await
21113                .expect("typed replay query"),
21114            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
21115        );
21116    }
21117
21118    #[test]
21119    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
21120        let value = BTreeMap::from([(1_i32, "integer key")]);
21121        let error = PayloadEnvelope::avro(&value)
21122            .expect_err("integer map keys must fail")
21123            .to_string();
21124
21125        assert!(error.contains("invalid_map_key"));
21126    }
21127
21128    #[test]
21129    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
21130        let envelope = PayloadEnvelope {
21131            codec: "json".to_string(),
21132            blob: r#"{"greeting":"hello"}"#.to_string(),
21133        };
21134
21135        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
21136        let diagnostic = error.to_string();
21137        assert!(diagnostic.contains("unsupported_payload_codec"));
21138        assert!(diagnostic.contains("codec=\"avro\""));
21139        assert!(diagnostic.contains("HTTP document transport"));
21140    }
21141
21142    #[test]
21143    fn untagged_json_payload_value_fails_closed() {
21144        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
21145            .expect_err("untagged JSON payload values must fail");
21146        let diagnostic = error.to_string();
21147        assert!(diagnostic.contains("unsupported_payload_codec"));
21148        assert!(diagnostic.contains("untagged durable payload"));
21149        assert!(diagnostic.contains("HTTP document transport"));
21150    }
21151
21152    #[test]
21153    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
21154        let envelope = PayloadEnvelope {
21155            codec: DEFAULT_CODEC.to_string(),
21156            blob: BASE64.encode([0x01]),
21157        };
21158
21159        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
21160        assert!(error.to_string().contains("invalid_payload_framing"));
21161    }
21162
21163    #[tokio::test]
21164    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
21165        let server = MockWorkerServer::start();
21166        let client = Client::builder(server.base_url())
21167            .timeout(Duration::from_secs(2))
21168            .build()
21169            .expect("client");
21170        let invalid_commands = [
21171            json!({
21172                "type": "complete_workflow",
21173                "result": {"codec": "json", "blob": null}
21174            }),
21175            json!({
21176                "type": "schedule_activity",
21177                "arguments": {"codec": "yaml", "blob": "ignored"}
21178            }),
21179            json!({
21180                "type": "start_child_workflow",
21181                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
21182            }),
21183            json!({"type": "continue_as_new", "arguments": []}),
21184            json!({"type": "complete_update"}),
21185            json!({"type": "record_side_effect", "result": null}),
21186            json!({
21187                "type": "start_service_operation",
21188                "payload_codec": DEFAULT_CODEC,
21189                "request_payload": "raw-avro-bytes"
21190            }),
21191        ];
21192
21193        for command in invalid_commands {
21194            let error = client
21195                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
21196                .await
21197                .expect_err("invalid durable payload must fail locally");
21198            let diagnostic = error.to_string();
21199            assert!(
21200                diagnostic.contains("unsupported_payload_codec")
21201                    || diagnostic.contains("invalid_payload_envelope")
21202                    || diagnostic.contains("untagged durable payload"),
21203                "unexpected validation diagnostic: {diagnostic}"
21204            );
21205        }
21206
21207        assert_eq!(
21208            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
21209            0,
21210            "invalid command payloads must not reach HTTP transport"
21211        );
21212    }
21213
21214    #[test]
21215    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
21216        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
21217        let commands = [
21218            json!({"type": "complete_workflow", "result": envelope.clone()}),
21219            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
21220            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
21221            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
21222            json!({"type": "complete_update", "result": envelope.clone()}),
21223            json!({"type": "record_side_effect", "result": envelope.clone()}),
21224            json!({
21225                "type": "start_service_operation",
21226                "payload_codec": DEFAULT_CODEC,
21227                "request_payload": envelope.clone()
21228            }),
21229            json!({
21230                "type": "complete_workflow",
21231                "result": envelope,
21232                "metadata": {
21233                    "codec": "json",
21234                    "payload_codec": "customer-codec",
21235                    "result": {"codec": "yaml", "blob": null}
21236                }
21237            }),
21238        ];
21239
21240        validate_workflow_task_commands(&commands)
21241            .expect("customer metadata must not become a protocol codec declaration");
21242    }
21243
21244    #[test]
21245    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
21246        assert_eq!(
21247            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
21248            AvroValue::Array(Vec::new())
21249        );
21250        assert_eq!(
21251            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
21252            AvroValue::Array(Vec::new())
21253        );
21254
21255        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21256        signal.signal_name = Some("empty-signal".to_string());
21257        signal.signal_arguments = None;
21258        let decoded = decode_resume_signal(&signal)
21259            .expect("valid Avro signal")
21260            .expect("named signal resumes the workflow");
21261        assert!(decoded.arguments.is_empty());
21262    }
21263
21264    #[tokio::test]
21265    async fn malformed_task_level_codecs_become_pre_handler_failures() {
21266        let client = Client::new("http://127.0.0.1:8080").expect("client");
21267        let mut worker = Worker::new(client, "rust-workers");
21268        let handler_calls = Arc::new(AtomicUsize::new(0));
21269
21270        let calls = Arc::clone(&handler_calls);
21271        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21272            calls.fetch_add(1, Ordering::SeqCst);
21273            async move { Ok(Value::Null) }
21274        });
21275        let calls = Arc::clone(&handler_calls);
21276        worker.register_activity("codec.activity", move |_ctx, _args| {
21277            calls.fetch_add(1, Ordering::SeqCst);
21278            async move { Ok(Value::Null) }
21279        });
21280        let calls = Arc::clone(&handler_calls);
21281        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21282            calls.fetch_add(1, Ordering::SeqCst);
21283            async move { Ok(Value::Null) }
21284        });
21285
21286        let mut failures = Vec::new();
21287        for codec_case in [
21288            InvalidTaskPayloadCodec::Missing,
21289            InvalidTaskPayloadCodec::Null,
21290            InvalidTaskPayloadCodec::NonString,
21291        ] {
21292            let mut workflow = json!({
21293                "task_id": format!("workflow-{}", codec_case.label()),
21294                "workflow_type": "codec.workflow"
21295            });
21296            codec_case.apply(&mut workflow);
21297            match serde_json::from_value::<WorkflowTask>(workflow) {
21298                Ok(task) => match worker.execute_workflow_task(task) {
21299                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21300                    outcome => failures.push(format!(
21301                        "workflow {} codec returned {outcome:?}",
21302                        codec_case.label()
21303                    )),
21304                },
21305                Err(error) => failures.push(format!(
21306                    "workflow {} codec failed transport deserialization: {error}",
21307                    codec_case.label()
21308                )),
21309            }
21310
21311            let mut activity = json!({
21312                "task_id": format!("activity-{}", codec_case.label()),
21313                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
21314                "activity_type": "codec.activity",
21315                "attempt_number": 1
21316            });
21317            codec_case.apply(&mut activity);
21318            match serde_json::from_value::<ActivityTask>(activity) {
21319                Ok(task) => match worker.execute_activity_task(task).await {
21320                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21321                    outcome => failures.push(format!(
21322                        "activity {} codec returned {outcome:?}",
21323                        codec_case.label()
21324                    )),
21325                },
21326                Err(error) => failures.push(format!(
21327                    "activity {} codec failed transport deserialization: {error}",
21328                    codec_case.label()
21329                )),
21330            }
21331
21332            let mut query = json!({
21333                "query_task_id": format!("query-{}", codec_case.label()),
21334                "workflow_type": "codec.workflow",
21335                "query_name": "known"
21336            });
21337            codec_case.apply(&mut query);
21338            match serde_json::from_value::<QueryTask>(query) {
21339                Ok(task) => match worker.execute_query_task(task).await {
21340                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
21341                    outcome => failures.push(format!(
21342                        "query {} codec returned {outcome:?}",
21343                        codec_case.label()
21344                    )),
21345                },
21346                Err(error) => failures.push(format!(
21347                    "query {} codec failed transport deserialization: {error}",
21348                    codec_case.label()
21349                )),
21350            }
21351        }
21352
21353        assert!(failures.is_empty(), "{}", failures.join("\n"));
21354        assert_eq!(
21355            handler_calls.load(Ordering::SeqCst),
21356            0,
21357            "invalid task codecs must not invoke a handler"
21358        );
21359    }
21360
21361    #[tokio::test]
21362    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
21363        for codec_case in [
21364            InvalidTaskPayloadCodec::Missing,
21365            InvalidTaskPayloadCodec::Null,
21366            InvalidTaskPayloadCodec::NonString,
21367        ] {
21368            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
21369            let client = Client::builder(server.base_url())
21370                .timeout(Duration::from_secs(2))
21371                .build()
21372                .expect("client");
21373            let mut worker = Worker::new(client, "rust-workers")
21374                .worker_id("codec-worker")
21375                .poll_timeout(Duration::from_millis(10));
21376            let handler_calls = Arc::new(AtomicUsize::new(0));
21377
21378            let calls = Arc::clone(&handler_calls);
21379            worker.register_workflow("codec.workflow", move |_ctx, _args| {
21380                calls.fetch_add(1, Ordering::SeqCst);
21381                async move { Ok(Value::Null) }
21382            });
21383            let calls = Arc::clone(&handler_calls);
21384            worker.register_activity("codec.activity", move |_ctx, _args| {
21385                calls.fetch_add(1, Ordering::SeqCst);
21386                async move { Ok(Value::Null) }
21387            });
21388            let calls = Arc::clone(&handler_calls);
21389            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21390                calls.fetch_add(1, Ordering::SeqCst);
21391                async move { Ok(Value::Null) }
21392            });
21393
21394            assert_eq!(
21395                worker.run_once().await.expect("invalid tasks are settled"),
21396                3,
21397                "all {} codec tasks must be handled",
21398                codec_case.label()
21399            );
21400            assert_eq!(
21401                handler_calls.load(Ordering::SeqCst),
21402                0,
21403                "{} task codecs must fail before every handler",
21404                codec_case.label()
21405            );
21406
21407            for path in [
21408                "/api/worker/workflow-tasks/codec-workflow/fail",
21409                "/api/worker/activity-tasks/codec-activity/fail",
21410                "/api/worker/query-tasks/codec-query/fail",
21411            ] {
21412                let body = server.request_body(path);
21413                assert!(
21414                    body["failure"]["message"]
21415                        .as_str()
21416                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
21417                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
21418                    codec_case.label()
21419                );
21420            }
21421            assert_eq!(
21422                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
21423                    ["reason"],
21424                "query_payload_decode_failed"
21425            );
21426            for path in [
21427                "/api/worker/workflow-tasks/codec-workflow/complete",
21428                "/api/worker/activity-tasks/codec-activity/complete",
21429                "/api/worker/query-tasks/codec-query/complete",
21430            ] {
21431                assert_eq!(
21432                    server.request_count(path),
21433                    0,
21434                    "invalid {} codec task reached {path}",
21435                    codec_case.label()
21436                );
21437            }
21438        }
21439    }
21440
21441    #[tokio::test]
21442    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
21443        let client = Client::new("http://127.0.0.1:8080").expect("client");
21444        let mut worker = Worker::new(client, "rust-workers");
21445        let handler_calls = Arc::new(AtomicUsize::new(0));
21446
21447        let calls = Arc::clone(&handler_calls);
21448        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21449            calls.fetch_add(1, Ordering::SeqCst);
21450            async move { Ok(Value::Null) }
21451        });
21452        let calls = Arc::clone(&handler_calls);
21453        worker.register_activity("codec.activity", move |_ctx, _args| {
21454            calls.fetch_add(1, Ordering::SeqCst);
21455            async move { Ok(Value::Null) }
21456        });
21457        let calls = Arc::clone(&handler_calls);
21458        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
21459            calls.fetch_add(1, Ordering::SeqCst);
21460            async move { Ok(Value::Null) }
21461        });
21462        let calls = Arc::clone(&handler_calls);
21463        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21464            calls.fetch_add(1, Ordering::SeqCst);
21465            async move { Ok(Value::Null) }
21466        });
21467
21468        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21469        workflow.payload_codec = "json".to_string();
21470        workflow.arguments = None;
21471        let error = worker
21472            .execute_workflow_task(workflow)
21473            .expect_err("task codec must be checked before workflow invocation");
21474        assert!(error.to_string().contains("unsupported_payload_codec"));
21475
21476        let activity = ActivityTask {
21477            task_id: "activity-invalid-codec".to_string(),
21478            activity_attempt_id: None,
21479            attempt_id: None,
21480            activity_type: "codec.activity".to_string(),
21481            payload_codec: "unknown".to_string(),
21482            arguments: None,
21483            attempt_number: 1,
21484            lease_owner: None,
21485        };
21486        let error = worker
21487            .execute_activity_task(activity)
21488            .await
21489            .expect_err("task codec must be checked before activity invocation");
21490        assert!(error.to_string().contains("unsupported_payload_codec"));
21491
21492        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21493        update.workflow_update_id = Some("update-invalid-codec".to_string());
21494        update.update_name = Some("known".to_string());
21495        update.history_events.push(history_event(
21496            "UpdateAccepted",
21497            json!({
21498                "update_id": "update-invalid-codec",
21499                "update_name": "known",
21500                "arguments": {"codec": "json", "blob": null}
21501            }),
21502        ));
21503        let error = worker
21504            .execute_workflow_task(update)
21505            .expect_err("nested update codec must be checked before handler lookup");
21506        assert!(error.to_string().contains("unsupported_payload_codec"));
21507
21508        let query: QueryTask = serde_json::from_value(json!({
21509            "query_task_id": "query-invalid-codec",
21510            "workflow_type": "codec.workflow",
21511            "query_name": "known",
21512            "payload_codec": DEFAULT_CODEC,
21513            "workflow_arguments": null,
21514            "query_arguments": null,
21515            "history_export": {
21516                "payloads": {"codec": DEFAULT_CODEC},
21517                "signals": [{
21518                    "name": "empty",
21519                    "payload_codec": "json",
21520                    "arguments": null
21521                }]
21522            }
21523        }))
21524        .expect("query task");
21525        let failure = worker
21526            .execute_query_task(query)
21527            .await
21528            .expect_err("exported signal codec must be checked before query invocation");
21529        assert_eq!(failure.reason, "query_payload_decode_failed");
21530        assert!(failure.message.contains("unsupported_payload_codec"));
21531
21532        let exported_history: QueryTask = serde_json::from_value(json!({
21533            "query_task_id": "query-invalid-history-codec",
21534            "workflow_type": "codec.workflow",
21535            "query_name": "known",
21536            "payload_codec": DEFAULT_CODEC,
21537            "history_export": {
21538                "payloads": {"codec": DEFAULT_CODEC},
21539                "history_events": [{
21540                    "type": "ActivityCompleted",
21541                    "payload": {"payload_codec": "unknown", "result": null}
21542                }]
21543            }
21544        }))
21545        .expect("query task");
21546        let failure = worker
21547            .execute_query_task(exported_history)
21548            .await
21549            .expect_err("exported history codec must be checked before query invocation");
21550        assert_eq!(failure.reason, "query_payload_decode_failed");
21551        assert!(failure.message.contains("unsupported_payload_codec"));
21552        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
21553
21554        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21555        unknown_workflow.arguments = None;
21556        unknown_workflow.history_events.push(history_event(
21557            "SignalReceived",
21558            json!({
21559                "signal_name": "empty",
21560                "payload_codec": "json",
21561                "arguments": null
21562            }),
21563        ));
21564        let error = worker
21565            .execute_workflow_task(unknown_workflow)
21566            .expect_err("history codec must precede unknown workflow outcome");
21567        assert!(error.to_string().contains("unsupported_payload_codec"));
21568
21569        let unknown_activity = ActivityTask {
21570            task_id: "activity-unknown".to_string(),
21571            activity_attempt_id: None,
21572            attempt_id: None,
21573            activity_type: "missing".to_string(),
21574            payload_codec: "json".to_string(),
21575            arguments: None,
21576            attempt_number: 1,
21577            lease_owner: None,
21578        };
21579        let error = worker
21580            .execute_activity_task(unknown_activity)
21581            .await
21582            .expect_err("codec must precede unknown activity outcome");
21583        assert!(error.to_string().contains("unsupported_payload_codec"));
21584
21585        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21586        unknown_update.payload_codec = "json".to_string();
21587        unknown_update.arguments = None;
21588        unknown_update.workflow_update_id = Some("update-unknown".to_string());
21589        unknown_update.update_name = Some("missing".to_string());
21590        let error = worker
21591            .execute_workflow_task(unknown_update)
21592            .expect_err("codec must precede fail_update shortcut");
21593        assert!(error.to_string().contains("unsupported_payload_codec"));
21594
21595        let unknown_query: QueryTask = serde_json::from_value(json!({
21596            "query_task_id": "query-unknown",
21597            "workflow_type": "missing",
21598            "query_name": "missing",
21599            "payload_codec": "json",
21600            "workflow_arguments": null,
21601            "query_arguments": null
21602        }))
21603        .expect("query task");
21604        let failure = worker
21605            .execute_query_task(unknown_query)
21606            .await
21607            .expect_err("codec must precede unknown query outcome");
21608        assert_eq!(failure.reason, "query_payload_decode_failed");
21609        assert!(failure.message.contains("unsupported_payload_codec"));
21610    }
21611
21612    #[tokio::test]
21613    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
21614        let client = Client::new("http://127.0.0.1:8080").expect("client");
21615        let worker = Worker::new(client, "rust-workers");
21616
21617        for event_type in ["SignalReceived", "SignalApplied"] {
21618            for (payload_field, codec) in [
21619                ("value", "json"),
21620                ("input", "unknown"),
21621                ("arguments", "json"),
21622            ] {
21623                let payload = json!({
21624                    "signal_name": "empty",
21625                    payload_field: {"codec": codec, "blob": null}
21626                });
21627                let workflow = workflow_task(
21628                    "missing",
21629                    vec![history_event(event_type, payload.clone())],
21630                    DEFAULT_CODEC,
21631                );
21632                let error = worker
21633                    .execute_workflow_task(workflow)
21634                    .expect_err("signal payload codec must precede unknown workflow outcome");
21635                assert!(
21636                    error.to_string().contains("unsupported_payload_codec"),
21637                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
21638                );
21639
21640                let query: QueryTask = serde_json::from_value(json!({
21641                    "query_task_id": format!("query-{event_type}-{payload_field}"),
21642                    "workflow_type": "missing",
21643                    "query_name": "missing",
21644                    "payload_codec": DEFAULT_CODEC,
21645                    "workflow_arguments": null,
21646                    "query_arguments": null,
21647                    "history_events": [{
21648                        "event_type": event_type,
21649                        "payload": payload
21650                    }]
21651                }))
21652                .expect("query task");
21653                let failure = worker
21654                    .execute_query_task(query)
21655                    .await
21656                    .expect_err("signal payload codec must precede unknown query outcome");
21657                assert_eq!(
21658                    failure.reason, "query_payload_decode_failed",
21659                    "{event_type}.{payload_field} returned an unrelated query outcome"
21660                );
21661                assert!(
21662                    failure.message.contains("unsupported_payload_codec"),
21663                    "{event_type}.{payload_field} returned an unrelated query error: {}",
21664                    failure.message
21665                );
21666            }
21667        }
21668    }
21669
21670    #[test]
21671    fn workflow_context_schedules_activity_until_completion_is_in_history() {
21672        let ctx = WorkflowContext {
21673            cancellation_scope_id: "root".into(),
21674            state: Arc::new(Mutex::new(
21675                WorkflowState::new_with_identity(
21676                    Vec::new(),
21677                    Some("wf-parent".to_string()),
21678                    Some("run-parent".to_string()),
21679                    "rust-workers".to_string(),
21680                    DEFAULT_CODEC.to_string(),
21681                    None,
21682                )
21683                .expect("workflow state"),
21684            )),
21685        };
21686
21687        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
21688        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21689        assert!(matches!(
21690            call.as_mut().poll(&mut task_context),
21691            Poll::Pending
21692        ));
21693
21694        let commands = ctx.take_commands().expect("commands");
21695        assert_eq!(commands[0]["type"], "schedule_activity");
21696        assert_eq!(commands[0]["activity_type"], "hello.activity");
21697    }
21698
21699    #[test]
21700    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
21701        let ctx = workflow_context(Vec::new());
21702        let options = ActivityOptions::new()
21703            .task_queue("payments")
21704            .retry_policy(
21705                ActivityRetryPolicy::new(4)
21706                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
21707                    .non_retryable_error_type("ValidationError"),
21708            )
21709            .start_to_close_timeout(Duration::from_secs(120))
21710            .schedule_to_start_timeout(Duration::from_secs(10))
21711            .schedule_to_close_timeout(Duration::from_secs(300))
21712            .heartbeat_timeout(Duration::from_secs(15));
21713        let mut call = Box::pin(ctx.activity_with_options(
21714            "charge-card",
21715            options,
21716            json!([{"order_id": "o-1"}]),
21717        ));
21718        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21719
21720        assert!(matches!(
21721            call.as_mut().poll(&mut task_context),
21722            Poll::Pending
21723        ));
21724        assert!(matches!(
21725            call.as_mut().poll(&mut task_context),
21726            Poll::Pending
21727        ));
21728
21729        let commands = ctx.take_commands().expect("activity command");
21730        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
21731        assert_eq!(commands[0]["queue"], "payments");
21732        assert_eq!(
21733            commands[0]["retry_policy"],
21734            json!({
21735                "max_attempts": 4,
21736                "backoff_seconds": [1, 3, 9],
21737                "non_retryable_error_types": ["ValidationError"],
21738            })
21739        );
21740        assert_eq!(commands[0]["start_to_close_timeout"], 120);
21741        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
21742        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
21743        assert_eq!(commands[0]["heartbeat_timeout"], 15);
21744    }
21745
21746    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
21747        vec![
21748            history_event(
21749                "ActivityScheduled",
21750                json!({"sequence":1,"activity_type":"render",
21751                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
21752            ),
21753            history_event(
21754                "ActivityCompleted",
21755                json!({"sequence":1,"activity_type":"render",
21756                "payload_codec":DEFAULT_CODEC,
21757                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
21758            ),
21759        ]
21760    }
21761
21762    #[test]
21763    fn worker_session_activity_routes_to_session_queue_once() {
21764        let ctx = workflow_context(Vec::new());
21765        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21766        let mut call = Box::pin(
21767            ctx.activity("render", json!([]))
21768                .in_worker_session(session.clone()),
21769        );
21770        let mut cx = TaskContext::from_waker(noop_waker_ref());
21771        assert!(call.as_mut().poll(&mut cx).is_pending());
21772        assert!(call.as_mut().poll(&mut cx).is_pending());
21773        let commands = ctx.take_commands().unwrap();
21774        assert_eq!(commands.len(), 1);
21775        assert_eq!(commands[0]["queue"], "gpu-workers");
21776        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
21777    }
21778
21779    #[tokio::test]
21780    async fn worker_session_cold_replay_uses_recorded_avro_result() {
21781        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21782        for _replacement in 0..2 {
21783            let ctx = workflow_context(completed_worker_session_history(&session));
21784            let result: i64 = ctx
21785                .activity("render", json!([]))
21786                .in_worker_session(session.clone())
21787                .typed()
21788                .await
21789                .unwrap();
21790            assert_eq!(result, 42);
21791            assert!(ctx.take_commands().unwrap().is_empty());
21792        }
21793    }
21794
21795    #[test]
21796    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
21797        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21798        for changed in [
21799            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
21800            Some(original.clone().ttl_seconds(60)),
21801            Some(original.clone().requirements(["gpu:l4"])),
21802            None,
21803        ] {
21804            let ctx = workflow_context(completed_worker_session_history(&original));
21805            let mut call = ctx.activity_with_options(
21806                "render",
21807                ActivityOptions::new().task_queue("gpu-workers"),
21808                json!([]),
21809            );
21810            if let Some(changed) = changed {
21811                call = call.in_worker_session(changed);
21812            }
21813            let mut call = Box::pin(call);
21814            let mut cx = TaskContext::from_waker(noop_waker_ref());
21815            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21816                call.as_mut().poll(&mut cx)
21817            else {
21818                panic!("changed session must fail replay");
21819            };
21820            assert_eq!(failure.reason, "activity_worker_session_mismatch");
21821            assert!(ctx.take_commands().unwrap().is_empty());
21822        }
21823    }
21824
21825    #[test]
21826    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
21827        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21828        let ctx = workflow_context(Vec::new());
21829        let mut local = Box::pin(
21830            ctx.local_activity("render", json!([]))
21831                .in_worker_session(session.clone()),
21832        );
21833        let mut cx = TaskContext::from_waker(noop_waker_ref());
21834        assert!(matches!(
21835            local.as_mut().poll(&mut cx),
21836            Poll::Ready(Err(Error::WorkerLoop(_)))
21837        ));
21838        assert!(ctx.take_commands().unwrap().is_empty());
21839        let mut remote = Box::pin(
21840            ctx.activity_with_options(
21841                "render",
21842                ActivityOptions::new().task_queue("other"),
21843                json!([]),
21844            )
21845            .in_worker_session(session),
21846        );
21847        assert!(matches!(
21848            remote.as_mut().poll(&mut cx),
21849            Poll::Ready(Err(Error::WorkerLoop(_)))
21850        ));
21851        assert!(ctx.take_commands().unwrap().is_empty());
21852    }
21853
21854    #[test]
21855    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
21856        let ctx = workflow_context(Vec::new());
21857        let options = ActivityOptions::new().retry_policy(
21858            ActivityRetryPolicy::new(3)
21859                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
21860        );
21861        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21862        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21863
21864        assert!(matches!(
21865            call.as_mut().poll(&mut task_context),
21866            Poll::Pending
21867        ));
21868        assert_eq!(
21869            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
21870            json!([1, 2])
21871        );
21872    }
21873
21874    #[test]
21875    fn activity_options_preserve_unused_explicit_backoff_entries() {
21876        for max_attempts in [1, 2, 10] {
21877            let ctx = workflow_context(Vec::new());
21878            let options =
21879                ActivityOptions::new()
21880                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
21881                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
21882                    ));
21883            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21884            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21885            assert!(matches!(
21886                call.as_mut().poll(&mut task_context),
21887                Poll::Pending
21888            ));
21889            let commands = ctx.take_commands().expect("command");
21890            assert_eq!(commands.len(), 1);
21891            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
21892            assert_eq!(
21893                commands[0]["retry_policy"]["backoff_seconds"],
21894                json!([1, 2, 5, 10, 15, 30, 60, 120])
21895            );
21896        }
21897        let default_options = ActivityOptions::new().validate().expect("default options");
21898        let default_policy = current_activity_retry_snapshot(&default_options);
21899        assert_eq!(
21900            default_policy.max_attempts,
21901            RecordedSnapshotValue::Known(Some(1))
21902        );
21903        assert_eq!(
21904            default_policy.backoff_seconds,
21905            RecordedSnapshotValue::Known(Vec::new())
21906        );
21907    }
21908
21909    #[test]
21910    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
21911        let fixture: Value = serde_json::from_str(include_str!(
21912            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
21913        ))
21914        .expect("published PHP fixture");
21915        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
21916            .expect("unchanged published history");
21917        let matching = ActivityOptions::new().task_queue("default").retry_policy(
21918            ActivityRetryPolicy::new(1)
21919                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
21920        );
21921        let mut changed_tail = matching.clone();
21922        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
21923            [1, 2, 5, 10, 15, 30, 60, 121]
21924                .map(Duration::from_secs)
21925                .to_vec(),
21926        ));
21927        let mut changed_first = matching.clone();
21928        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
21929            [2, 2, 5, 10, 15, 30, 60, 120]
21930                .map(Duration::from_secs)
21931                .to_vec(),
21932        ));
21933        let mut changed_attempts = matching.clone();
21934        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
21935        let mut changed_types = matching.clone();
21936        changed_types
21937            .retry_policy
21938            .as_mut()
21939            .unwrap()
21940            .non_retryable_error_types = vec!["ChangedError".into()];
21941        let mut changed_start = matching.clone();
21942        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
21943        let mut changed_schedule_start = matching.clone();
21944        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
21945        let mut changed_schedule_close = matching.clone();
21946        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
21947        let mut changed_heartbeat = matching;
21948        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
21949        let unchanged_defaults = ActivityOptions::new().task_queue("default");
21950        for options in [
21951            changed_tail,
21952            changed_first,
21953            changed_attempts,
21954            changed_types,
21955            changed_start,
21956            changed_schedule_start,
21957            changed_schedule_close,
21958            changed_heartbeat,
21959            unchanged_defaults,
21960        ] {
21961            let ctx = workflow_context(history.clone());
21962            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
21963            assert!(!ctx.patched("frozen-zero").unwrap());
21964            ctx.deprecate_patch("frozen-zero").unwrap();
21965            let mut call =
21966                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
21967            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21968            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21969                call.as_mut().poll(&mut task_context)
21970            else {
21971                panic!("changed explicit policy must fail replay")
21972            };
21973            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
21974            assert_eq!(failure.sequence, Some(2));
21975            assert!(ctx.take_commands().unwrap().is_empty());
21976        }
21977    }
21978
21979    #[test]
21980    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
21981        let cases = [
21982            (
21983                ActivityOptions::new().task_queue("  "),
21984                ActivityOptionsErrorKind::EmptyTaskQueue,
21985            ),
21986            (
21987                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
21988                ActivityOptionsErrorKind::EmptyRetryPolicy,
21989            ),
21990            (
21991                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
21992                ActivityOptionsErrorKind::InvalidMaxAttempts,
21993            ),
21994            (
21995                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
21996                    max_attempts: None,
21997                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
21998                    non_retryable_error_types: Vec::new(),
21999                }),
22000                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
22001            ),
22002            (
22003                ActivityOptions::new().retry_policy(
22004                    ActivityRetryPolicy::new(2).exponential_backoff(
22005                        Duration::from_secs(1),
22006                        0,
22007                        None,
22008                    ),
22009                ),
22010                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
22011            ),
22012            (
22013                ActivityOptions::new()
22014                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
22015                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
22016            ),
22017            (
22018                ActivityOptions::new().retry_policy(
22019                    ActivityRetryPolicy::new(10_002).exponential_backoff(
22020                        Duration::from_secs(1),
22021                        1,
22022                        None,
22023                    ),
22024                ),
22025                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
22026            ),
22027            (
22028                ActivityOptions::new().retry_policy(
22029                    ActivityRetryPolicy::new(2)
22030                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
22031                ),
22032                ActivityOptionsErrorKind::BackoffOverflow,
22033            ),
22034        ];
22035
22036        for (options, expected_kind) in cases {
22037            let ctx = workflow_context(Vec::new());
22038            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
22039            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22040            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
22041                call.as_mut().poll(&mut task_context)
22042            else {
22043                panic!("expected typed activity validation error");
22044            };
22045            assert_eq!(error.kind, expected_kind);
22046            assert!(ctx.take_commands().expect("commands").is_empty());
22047        }
22048    }
22049
22050    #[test]
22051    fn activity_options_validate_positive_and_ordered_timeouts() {
22052        let zero_timeout_cases = [
22053            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
22054            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
22055            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
22056            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
22057        ];
22058        for options in zero_timeout_cases {
22059            assert_eq!(
22060                options.validate().expect_err("zero timeout").kind,
22061                ActivityOptionsErrorKind::TimeoutNotPositive
22062            );
22063        }
22064
22065        let ordering_cases = [
22066            ActivityOptions::new()
22067                .heartbeat_timeout(Duration::from_secs(11))
22068                .start_to_close_timeout(Duration::from_secs(10)),
22069            ActivityOptions::new()
22070                .start_to_close_timeout(Duration::from_secs(31))
22071                .schedule_to_close_timeout(Duration::from_secs(30)),
22072            ActivityOptions::new()
22073                .schedule_to_start_timeout(Duration::from_secs(31))
22074                .schedule_to_close_timeout(Duration::from_secs(30)),
22075        ];
22076        for options in ordering_cases {
22077            assert_eq!(
22078                options.validate().expect_err("timeout order").kind,
22079                ActivityOptionsErrorKind::TimeoutOrder
22080            );
22081        }
22082
22083        assert_eq!(
22084            ActivityOptions::new()
22085                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
22086                .validate()
22087                .expect_err("protocol integer overflow")
22088                .kind,
22089            ActivityOptionsErrorKind::TimeoutOverflow
22090        );
22091    }
22092
22093    #[test]
22094    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
22095        let ctx = workflow_context(completed_retry_activity_history());
22096        let mut call =
22097            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22098        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22099
22100        assert!(matches!(
22101            call.as_mut().poll(&mut task_context),
22102            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22103        ));
22104        assert!(ctx.take_commands().expect("commands").is_empty());
22105        ctx.ensure_history_consumed().expect("history consumed");
22106    }
22107
22108    #[test]
22109    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
22110        let mut options = retry_activity_options();
22111        options
22112            .retry_policy
22113            .as_mut()
22114            .expect("retry policy")
22115            .non_retryable_error_types
22116            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
22117
22118        let new_ctx = workflow_context(Vec::new());
22119        let mut new_call =
22120            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
22121        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22122        assert!(matches!(
22123            new_call.as_mut().poll(&mut task_context),
22124            Poll::Pending
22125        ));
22126        let commands = new_ctx.take_commands().expect("commands");
22127        assert_eq!(commands.len(), 1);
22128        assert_eq!(
22129            commands[0]["retry_policy"]["non_retryable_error_types"],
22130            json!(["PermanentError"])
22131        );
22132
22133        let replay_ctx = workflow_context(completed_retry_activity_history());
22134        let mut replay_call =
22135            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
22136        assert!(matches!(
22137            replay_call.as_mut().poll(&mut task_context),
22138            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22139        ));
22140        assert!(replay_ctx.take_commands().expect("commands").is_empty());
22141        replay_ctx
22142            .ensure_history_consumed()
22143            .expect("history consumed");
22144    }
22145
22146    #[test]
22147    fn replayed_intermediate_retry_remains_pending_across_restarts() {
22148        let history = completed_retry_activity_history()
22149            .into_iter()
22150            .take(3)
22151            .collect::<Vec<_>>();
22152
22153        for _restart in 0..2 {
22154            let ctx = workflow_context(history.clone());
22155            let mut call =
22156                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22157            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22158            assert!(matches!(
22159                call.as_mut().poll(&mut task_context),
22160                Poll::Pending
22161            ));
22162            assert!(ctx.take_commands().expect("commands").is_empty());
22163        }
22164    }
22165
22166    #[test]
22167    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
22168        let mut changed_queue = retry_activity_options();
22169        changed_queue.task_queue = Some("different-queue".to_string());
22170
22171        let mut changed_max_attempts = retry_activity_options();
22172        let retry_policy = changed_max_attempts
22173            .retry_policy
22174            .as_mut()
22175            .expect("retry policy");
22176        retry_policy.max_attempts = Some(4);
22177
22178        let mut changed_backoff = retry_activity_options();
22179        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
22180        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
22181            Duration::from_secs(3),
22182            Duration::from_secs(4),
22183        ]));
22184
22185        let mut changed_non_retryable_types = retry_activity_options();
22186        let retry_policy = changed_non_retryable_types
22187            .retry_policy
22188            .as_mut()
22189            .expect("retry policy");
22190        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
22191
22192        let mut changed_start_to_close = retry_activity_options();
22193        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
22194        let mut changed_schedule_to_start = retry_activity_options();
22195        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
22196        let mut changed_schedule_to_close = retry_activity_options();
22197        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
22198        let mut changed_heartbeat = retry_activity_options();
22199        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
22200
22201        let cases = [
22202            (changed_queue, "activity_task_queue_mismatch"),
22203            (changed_max_attempts, "activity_retry_policy_mismatch"),
22204            (changed_backoff, "activity_retry_policy_mismatch"),
22205            (
22206                changed_non_retryable_types,
22207                "activity_retry_policy_mismatch",
22208            ),
22209            (changed_start_to_close, "activity_retry_policy_mismatch"),
22210            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
22211            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
22212            (changed_heartbeat, "activity_retry_policy_mismatch"),
22213        ];
22214
22215        for (options, expected_reason) in cases {
22216            let ctx = workflow_context(completed_retry_activity_history());
22217            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
22218            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22219            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22220                call.as_mut().poll(&mut task_context)
22221            else {
22222                panic!("changed activity options must fail replay");
22223            };
22224            assert_eq!(failure.reason, expected_reason);
22225            assert_eq!(failure.sequence, Some(1));
22226            assert!(ctx.take_commands().expect("commands").is_empty());
22227        }
22228    }
22229
22230    #[test]
22231    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
22232        let cases = [
22233            (
22234                "execution_mode",
22235                json!("local"),
22236                "activity_execution_mode_mismatch",
22237            ),
22238            (
22239                "snapshot_version",
22240                json!(2),
22241                "activity_retry_policy_mismatch",
22242            ),
22243        ];
22244
22245        for (field, value, expected_reason) in cases {
22246            let mut history = completed_retry_activity_history();
22247            let activity = history[0].payload["activity"]
22248                .as_object_mut()
22249                .expect("activity snapshot");
22250            if field == "execution_mode" {
22251                activity.insert(field.to_string(), value);
22252            } else {
22253                activity["retry_policy"]
22254                    .as_object_mut()
22255                    .expect("retry snapshot")
22256                    .insert(field.to_string(), value);
22257            }
22258
22259            let ctx = workflow_context(history);
22260            let mut call =
22261                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22262            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22263            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22264                call.as_mut().poll(&mut task_context)
22265            else {
22266                panic!("changed {field} must fail replay");
22267            };
22268            assert_eq!(failure.reason, expected_reason);
22269            assert_eq!(failure.sequence, Some(1));
22270            assert!(ctx.take_commands().expect("commands").is_empty());
22271        }
22272    }
22273
22274    #[test]
22275    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
22276        for (nested, field, value, terminal_only) in [
22277            (false, "execution_mode", json!("local"), false),
22278            (false, "local_activity", json!(true), false),
22279            (true, "local_activity", json!(true), false),
22280            (false, "local_activity", json!(true), true),
22281        ] {
22282            let mut history = completed_retry_activity_history();
22283            history[0]
22284                .payload
22285                .as_object_mut()
22286                .unwrap()
22287                .remove("activity");
22288            let event = if terminal_only {
22289                history.last_mut().unwrap()
22290            } else {
22291                &mut history[0]
22292            };
22293            if nested {
22294                event.payload["activity"] = json!({(field): value});
22295            } else {
22296                event.payload[field] = value;
22297            }
22298            let ctx = workflow_context(history);
22299            let mut call =
22300                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22301            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22302            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22303                call.as_mut().poll(&mut task_context)
22304            else {
22305                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
22306            };
22307            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
22308            assert_eq!(failure.sequence, Some(1));
22309            assert!(ctx.take_commands().expect("commands").is_empty());
22310        }
22311    }
22312
22313    #[test]
22314    fn activity_history_rejects_conflicting_local_execution_markers() {
22315        let mut history = completed_retry_activity_history();
22316        history.last_mut().unwrap().payload["local_activity"] = json!(true);
22317        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
22318            .expect_err("remote schedule cannot become a local completion");
22319        assert!(
22320            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
22321            if reason == "activity_execution_mode_conflict")
22322        );
22323    }
22324
22325    #[test]
22326    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
22327        let mut history = completed_retry_activity_history();
22328        let activity = history[0].payload["activity"]
22329            .as_object_mut()
22330            .expect("activity snapshot");
22331        activity.remove("execution_mode");
22332        activity.remove("retry_policy");
22333
22334        let mut current = retry_activity_options();
22335        current.start_to_close_timeout = Some(Duration::from_secs(45));
22336        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
22337        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
22338        current.heartbeat_timeout = Some(Duration::from_secs(12));
22339
22340        let ctx = workflow_context(history);
22341        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
22342        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22343        assert!(matches!(
22344            call.as_mut().poll(&mut task_context),
22345            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22346        ));
22347        assert!(ctx.take_commands().expect("commands").is_empty());
22348        ctx.ensure_history_consumed().expect("history consumed");
22349    }
22350
22351    #[test]
22352    fn terminal_activity_failed_after_start_returns_typed_failure() {
22353        let history = vec![
22354            history_event(
22355                "ActivityScheduled",
22356                json!({
22357                    "sequence": 1,
22358                    "activity_type": "flaky",
22359                    "activity_execution_id": "act-terminal",
22360                    "activity": {
22361                        "id": "act-terminal",
22362                        "sequence": 1,
22363                        "type": "flaky",
22364                        "queue": "critical-activities",
22365                        "retry_policy": {
22366                            "snapshot_version": 1,
22367                            "max_attempts": 3,
22368                            "backoff_seconds": [2, 4],
22369                            "non_retryable_error_types": ["PermanentError"]
22370                        }
22371                    }
22372                }),
22373            ),
22374            history_event(
22375                "ActivityStarted",
22376                json!({
22377                    "sequence": 1,
22378                    "activity_type": "flaky",
22379                    "activity_execution_id": "act-terminal",
22380                    "activity_attempt_id": "attempt-1",
22381                    "attempt_number": 1
22382                }),
22383            ),
22384            history_event(
22385                "ActivityFailed",
22386                json!({
22387                    "sequence": 1,
22388                    "activity_type": "flaky",
22389                    "activity_execution_id": "act-terminal",
22390                    "activity_attempt_id": "attempt-1",
22391                    "attempt_number": 1,
22392                    "failure_id": "failure-terminal",
22393                    "failure_category": "activity",
22394                    "exception_type": "PermanentError",
22395                    "message": "cannot retry",
22396                    "non_retryable": true
22397                }),
22398            ),
22399        ];
22400        let ctx = workflow_context(history);
22401        let mut call =
22402            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22403        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22404
22405        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22406            call.as_mut().poll(&mut task_context)
22407        else {
22408            panic!("terminal ActivityFailed must settle the activity future");
22409        };
22410        assert_eq!(failure.kind, ActivityFailureKind::Failed);
22411        assert_eq!(
22412            failure.activity_execution_id.as_deref(),
22413            Some("act-terminal")
22414        );
22415        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
22416        assert!(failure.non_retryable);
22417        assert!(ctx.take_commands().expect("commands").is_empty());
22418        ctx.ensure_history_consumed().expect("history consumed");
22419    }
22420
22421    #[test]
22422    fn activity_terminal_events_return_machine_readable_failures() {
22423        let cases = [
22424            (
22425                "ActivityFailed",
22426                json!({
22427                    "sequence": 1,
22428                    "activity_type": "charge-card",
22429                    "activity_execution_id": "act-1",
22430                    "activity_attempt_id": "attempt-2",
22431                    "attempt_number": 2,
22432                    "failure_id": "failure-1",
22433                    "failure_category": "activity",
22434                    "exception_type": "PaymentDeclined",
22435                    "exception_class": "payments.PaymentDeclined",
22436                    "message": "card declined",
22437                    "non_retryable": true
22438                }),
22439                ActivityFailureKind::Failed,
22440                "activity",
22441            ),
22442            (
22443                "ActivityCancelled",
22444                json!({
22445                    "sequence": 1,
22446                    "activity_type": "charge-card",
22447                    "activity_execution_id": "act-1",
22448                    "activity_attempt_id": "attempt-1"
22449                }),
22450                ActivityFailureKind::Cancelled,
22451                "cancelled",
22452            ),
22453        ];
22454
22455        for (event_type, payload, expected_kind, expected_reason) in cases {
22456            let ctx = workflow_context(vec![history_event(event_type, payload)]);
22457            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
22458            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22459            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22460                call.as_mut().poll(&mut task_context)
22461            else {
22462                panic!("expected terminal activity failure");
22463            };
22464            assert_eq!(failure.kind, expected_kind);
22465            assert_eq!(failure.reason, expected_reason);
22466            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
22467            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
22468        }
22469    }
22470
22471    #[test]
22472    fn every_activity_timeout_class_is_typed() {
22473        for timeout_kind in [
22474            "start_to_close",
22475            "schedule_to_start",
22476            "schedule_to_close",
22477            "heartbeat",
22478        ] {
22479            let ctx = workflow_context(vec![history_event(
22480                "ActivityTimedOut",
22481                json!({
22482                    "sequence": 1,
22483                    "activity_type": "slow",
22484                    "activity_execution_id": "act-timeout",
22485                    "activity_attempt_id": "attempt-timeout",
22486                    "failure_category": "timeout",
22487                    "timeout_kind": timeout_kind,
22488                    "message": "deadline expired"
22489                }),
22490            )]);
22491            let mut call = Box::pin(ctx.activity("slow", json!([])));
22492            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22493            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22494                call.as_mut().poll(&mut task_context)
22495            else {
22496                panic!("expected timeout failure");
22497            };
22498            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
22499            assert_eq!(failure.reason, timeout_kind);
22500            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
22501            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
22502        }
22503    }
22504
22505    #[test]
22506    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
22507        let ctx = workflow_context(Vec::new());
22508        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
22509        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22510
22511        assert!(matches!(
22512            sleep.as_mut().poll(&mut task_context),
22513            Poll::Pending
22514        ));
22515        assert!(matches!(
22516            sleep.as_mut().poll(&mut task_context),
22517            Poll::Pending
22518        ));
22519
22520        let commands = ctx.take_commands().expect("timer command");
22521        assert_eq!(
22522            commands,
22523            vec![json!({
22524                "type": "start_timer",
22525                "delay_seconds": 2,
22526            })]
22527        );
22528    }
22529
22530    #[test]
22531    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
22532        let history = vec![
22533            history_event(
22534                "TimerScheduled",
22535                json!({
22536                    "sequence": 1,
22537                    "timer_id": "timer-1",
22538                    "delay_seconds": 5,
22539                    "fire_at": "2026-07-11T12:00:05Z",
22540                }),
22541            ),
22542            history_event(
22543                "TimerFired",
22544                json!({
22545                    "sequence": 1,
22546                    "timer_id": "timer-1",
22547                    "delay_seconds": 5,
22548                    "fire_at": "2026-07-11T12:00:05Z",
22549                    "fired_at": "2026-07-11T12:00:05Z",
22550                }),
22551            ),
22552        ];
22553
22554        for _restart in 0..2 {
22555            let ctx = workflow_context(history.clone());
22556            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
22557            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22558            assert!(matches!(
22559                sleep.as_mut().poll(&mut task_context),
22560                Poll::Ready(Ok(()))
22561            ));
22562            assert!(ctx.take_commands().expect("commands").is_empty());
22563            ctx.ensure_history_consumed().expect("history consumed");
22564        }
22565    }
22566
22567    #[test]
22568    fn workflow_sleep_rejects_changed_delay_during_replay() {
22569        let ctx = workflow_context(vec![
22570            history_event(
22571                "TimerScheduled",
22572                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22573            ),
22574            history_event(
22575                "TimerFired",
22576                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22577            ),
22578        ]);
22579        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
22580        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22581
22582        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22583            sleep.as_mut().poll(&mut task_context)
22584        else {
22585            panic!("changed timer delay must be rejected");
22586        };
22587        assert_eq!(failure.reason, "timer_delay_mismatch");
22588        assert_eq!(failure.sequence, Some(1));
22589    }
22590
22591    #[test]
22592    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
22593        let ctx = workflow_context(Vec::new());
22594        let mut wait = Box::pin(
22595            ctx.wait_condition(
22596                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
22597                    .timeout(Duration::from_millis(60_001)),
22598                || Ok(false),
22599            ),
22600        );
22601        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22602
22603        assert!(matches!(
22604            wait.as_mut().poll(&mut task_context),
22605            Poll::Pending
22606        ));
22607        assert!(matches!(
22608            wait.as_mut().poll(&mut task_context),
22609            Poll::Pending
22610        ));
22611        assert_eq!(
22612            ctx.take_commands().expect("condition command"),
22613            vec![json!({
22614                "type": "open_condition_wait",
22615                "condition_wait_occurrence_id": "rust:condition-wait:0",
22616                "condition_key": "approval.ready",
22617                "condition_definition_fingerprint": "sha256:approval-v1",
22618                "timeout_seconds": 61,
22619            })]
22620        );
22621    }
22622
22623    #[test]
22624    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
22625        let ctx = workflow_context(Vec::new());
22626        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
22627        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22628        assert!(matches!(
22629            satisfied.as_mut().poll(&mut task_context),
22630            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22631        ));
22632
22633        let mut timed_out = Box::pin(wait_condition!(
22634            ctx,
22635            "no-wait",
22636            timeout: Duration::ZERO,
22637            || Ok(false),
22638        ));
22639        assert!(matches!(
22640            timed_out.as_mut().poll(&mut task_context),
22641            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22642        ));
22643        assert!(ctx.take_commands().expect("commands").is_empty());
22644    }
22645
22646    #[test]
22647    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
22648        let signal_history = vec![
22649            history_event(
22650                "ConditionWaitOpened",
22651                json!({
22652                    "sequence": 4,
22653                    "condition_wait_id": "condition:4",
22654                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22655                    "condition_key": "approval",
22656                    "condition_definition_fingerprint": "sha256:approval-v1",
22657                    "timeout_seconds": 30,
22658                }),
22659            ),
22660            history_event(
22661                "SignalReceived",
22662                json!({
22663                    "workflow_sequence": 4,
22664                    "signal_name": "approve",
22665                    "arguments": fixture_envelope(json!(["Ada"])),
22666                }),
22667            ),
22668        ];
22669        for _worker_before_or_after_restart in 0..2 {
22670            let ctx = workflow_context(signal_history.clone());
22671            let predicate_ctx = ctx.clone();
22672            let mut wait = Box::pin(
22673                ctx.wait_condition(
22674                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
22675                        .timeout(Duration::from_secs(30)),
22676                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
22677                ),
22678            );
22679            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22680            assert!(matches!(
22681                wait.as_mut().poll(&mut task_context),
22682                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22683            ));
22684            assert!(ctx.take_commands().expect("commands").is_empty());
22685            ctx.ensure_history_consumed().expect("condition consumed");
22686        }
22687
22688        let update_history = vec![
22689            history_event(
22690                "ConditionWaitOpened",
22691                json!({
22692                    "sequence": 7,
22693                    "condition_wait_id": "condition:7",
22694                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22695                    "condition_key": "update-approval",
22696                    "condition_definition_fingerprint": "sha256:update-approval-v1",
22697                }),
22698            ),
22699            history_event(
22700                "UpdateApplied",
22701                json!({
22702                    "sequence": 7,
22703                    "update_id": "update-1",
22704                    "update_name": "approve",
22705                    "arguments": fixture_envelope(json!([true])),
22706                }),
22707            ),
22708        ];
22709        let ctx = workflow_context(update_history);
22710        let predicate_ctx = ctx.clone();
22711        let mut wait = Box::pin(ctx.wait_condition(
22712            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
22713            move || {
22714                Ok(predicate_ctx
22715                    .updates("approve")?
22716                    .first()
22717                    .and_then(|arguments| arguments.first())
22718                    .and_then(Value::as_bool)
22719                    == Some(true))
22720            },
22721        ));
22722        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22723        assert!(matches!(
22724            wait.as_mut().poll(&mut task_context),
22725            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22726        ));
22727        assert!(ctx.take_commands().expect("commands").is_empty());
22728        ctx.ensure_history_consumed().expect("condition consumed");
22729    }
22730
22731    #[test]
22732    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
22733        let open_history = vec![
22734            history_event(
22735                "ConditionWaitOpened",
22736                json!({
22737                    "sequence": 3,
22738                    "condition_wait_id": "condition:3",
22739                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22740                    "condition_key": "two-votes",
22741                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22742                    "timeout_seconds": 120,
22743                }),
22744            ),
22745            history_event(
22746                "SignalReceived",
22747                json!({
22748                    "workflow_sequence": 3,
22749                    "signal_name": "vote",
22750                    "arguments": fixture_envelope(json!(["first"])),
22751                }),
22752            ),
22753        ];
22754        for _worker_before_or_after_restart in 0..2 {
22755            let ctx = workflow_context(open_history.clone());
22756            let predicate_ctx = ctx.clone();
22757            let mut wait = Box::pin(
22758                ctx.wait_condition(
22759                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22760                        .timeout(Duration::from_secs(120)),
22761                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
22762                ),
22763            );
22764            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22765            assert!(matches!(
22766                wait.as_mut().poll(&mut task_context),
22767                Poll::Pending
22768            ));
22769            assert_eq!(
22770                ctx.take_commands().expect("reopened condition"),
22771                vec![json!({
22772                    "type": "open_condition_wait",
22773                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22774                    "condition_key": "two-votes",
22775                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22776                    "timeout_seconds": 120,
22777                })]
22778            );
22779        }
22780
22781        let satisfied_ctx = workflow_context(vec![
22782            history_event(
22783                "ConditionWaitOpened",
22784                json!({
22785                    "sequence": 5,
22786                    "condition_wait_id": "condition:5",
22787                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22788                    "condition_key": "approval",
22789                    "condition_definition_fingerprint": "sha256:approval-v1",
22790                }),
22791            ),
22792            history_event(
22793                "ConditionWaitSatisfied",
22794                json!({
22795                    "sequence": 5,
22796                    "condition_wait_id": "condition:5",
22797                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22798                    "condition_key": "approval",
22799                    "condition_definition_fingerprint": "sha256:approval-v1",
22800                }),
22801            ),
22802        ]);
22803        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
22804            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
22805            || Ok(false),
22806        ));
22807        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22808        assert!(matches!(
22809            satisfied.as_mut().poll(&mut task_context),
22810            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22811        ));
22812
22813        let timed_out_ctx = workflow_context(vec![
22814            history_event(
22815                "ConditionWaitOpened",
22816                json!({
22817                    "sequence": 8,
22818                    "condition_wait_id": "condition:8",
22819                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22820                    "condition_key": "approval-timeout",
22821                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
22822                    "timeout_seconds": 5,
22823                }),
22824            ),
22825            history_event(
22826                "TimerScheduled",
22827                json!({
22828                    "sequence": 9,
22829                    "timer_id": "condition-timer:9",
22830                    "timer_kind": "condition_timeout",
22831                    "condition_wait_id": "condition:8",
22832                    "delay_seconds": 5,
22833                }),
22834            ),
22835            history_event(
22836                "TimerFired",
22837                json!({
22838                    "sequence": 9,
22839                    "timer_id": "condition-timer:9",
22840                    "timer_kind": "condition_timeout",
22841                    "condition_wait_id": "condition:8",
22842                    "delay_seconds": 5,
22843                }),
22844            ),
22845        ]);
22846        let mut timed_out = Box::pin(
22847            timed_out_ctx.wait_condition(
22848                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
22849                    .timeout(Duration::from_secs(5)),
22850                || Ok(true),
22851            ),
22852        );
22853        assert!(matches!(
22854            timed_out.as_mut().poll(&mut task_context),
22855            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22856        ));
22857    }
22858
22859    #[test]
22860    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
22861        let ctx = workflow_context(reopened_selection_condition_history());
22862        {
22863            let state = ctx.state.lock().unwrap();
22864            assert!(matches!(
22865                selection_member_recorded_command(&state, 2),
22866                Some(RecordedCommand::ConditionWait {
22867                    sequence: 3,
22868                    result: None,
22869                    ..
22870                })
22871            ));
22872        }
22873        let mut selected = Box::pin(ctx.select_keyed(vec![
22874            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22875            (
22876                "votes",
22877                ParallelOperation::condition(
22878                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
22879                    || Ok(true),
22880                ),
22881            ),
22882        ]));
22883        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22884        assert!(selected.as_mut().poll(&mut task_context).is_pending());
22885        assert!(
22886            ctx.take_commands().unwrap().is_empty(),
22887            "true predicate must not reopen the recorded wait"
22888        );
22889        ctx.ensure_history_consumed()
22890            .expect("physical reopens are consumed while canonical selection is pending");
22891    }
22892
22893    #[test]
22894    fn reopened_selection_condition_replays_its_latest_physical_winner() {
22895        for (terminal_type, acknowledge_timeout) in [
22896            ("ConditionWaitSatisfied", false),
22897            ("ConditionWaitTimedOut", false),
22898            ("TimerFired", false),
22899            ("TimerFired", true),
22900        ] {
22901            let mut history = reopened_selection_condition_history();
22902            let original_identity = history[1].payload["condition_wait_id"].clone();
22903            let uses_timer = terminal_type == "TimerFired";
22904            let mut resolution_payload = history[3].payload.clone();
22905            if uses_timer {
22906                for event in &mut history[1..] {
22907                    event.payload["timeout_seconds"] = json!(3);
22908                }
22909                resolution_payload = history[3].payload.clone();
22910                resolution_payload["timer_kind"] = json!("condition_timeout");
22911                resolution_payload["timer_id"] = json!("condition-timeout-3");
22912                resolution_payload["delay_seconds"] = json!(3);
22913                history.push(history_event("TimerScheduled", resolution_payload.clone()));
22914            }
22915            let mut resolution = history_event(terminal_type, resolution_payload.clone());
22916            resolution
22917                .raw
22918                .insert("id".into(), json!("latest-condition-resolution"));
22919            history.push(resolution);
22920            history.push(history_event(
22921                "SelectionResolved",
22922                json!({
22923                    "selection_group_id": "select-calls:1:2",
22924                    "selection_group_base_sequence": 1,
22925                    "selection_group_size": 2,
22926                    "member_key": "votes",
22927                    "member_index": 1,
22928                    "member_base_sequence": 2,
22929                    "member_size": 1,
22930                    "operation_kind": "condition",
22931                    "operation_identity": original_identity,
22932                    "outcome": "completed",
22933                    "resolution_event_id": "latest-condition-resolution",
22934                    "resolution_event_type": terminal_type,
22935                }),
22936            ));
22937            if acknowledge_timeout {
22938                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
22939            }
22940            let ctx = workflow_context(history);
22941            let mut selected = Box::pin(ctx.select_keyed(vec![
22942                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22943                (
22944                    "votes",
22945                    ParallelOperation::condition(
22946                        if uses_timer {
22947                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22948                                .timeout(Duration::from_secs(3))
22949                        } else {
22950                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22951                        },
22952                        || Ok(true),
22953                    ),
22954                ),
22955            ]));
22956            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22957            match selected.as_mut().poll(&mut task_context) {
22958                Poll::Ready(Ok(result)) => {
22959                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
22960                    let expected = if terminal_type == "ConditionWaitSatisfied" {
22961                        ConditionWaitResult::Satisfied
22962                    } else {
22963                        ConditionWaitResult::TimedOut
22964                    };
22965                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
22966                }
22967                other => panic!("latest physical winner must replay: {other:?}"),
22968            }
22969            assert!(ctx.take_commands().unwrap().is_empty());
22970            ctx.ensure_history_consumed()
22971                .expect("winner history consumed");
22972        }
22973    }
22974
22975    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
22976        let fixture: Value = serde_json::from_str(include_str!(
22977            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
22978        ))
22979        .expect("grouped condition fixture");
22980        fixture["history"]
22981            .as_array()
22982            .unwrap()
22983            .iter()
22984            .map(|event| {
22985                let mut payload = event["payload"].clone();
22986                let index = payload["parallel_group_index"].as_u64().unwrap();
22987                payload["parallel_group_id"] = json!("select-calls:1:2");
22988                payload["parallel_group_mode"] = json!("select");
22989                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
22990                payload["selection_member_index"] = json!(index);
22991                payload["selection_member_base_sequence"] = json!(index + 1);
22992                payload["selection_member_size"] = json!(1);
22993                payload["selection_member_kind"] =
22994                    json!(if index == 0 { "timer" } else { "condition" });
22995                history_event(event["event_type"].as_str().unwrap(), payload)
22996            })
22997            .collect()
22998    }
22999
23000    #[test]
23001    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
23002        let fixture: Value = serde_json::from_str(include_str!(
23003            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
23004        ))
23005        .expect("grouped condition fixture");
23006        let original = fixture["history"].as_array().expect("fixture history");
23007        let decode = |events: &[Value]| {
23008            let history = events
23009                .iter()
23010                .map(|event| {
23011                    history_event(
23012                        event["event_type"].as_str().unwrap(),
23013                        event["payload"].clone(),
23014                    )
23015                })
23016                .collect::<Vec<_>>();
23017            recorded_commands(
23018                &history,
23019                DEFAULT_CODEC,
23020                WorkflowIdentity {
23021                    workflow_id: None,
23022                    run_id: None,
23023                },
23024            )
23025        };
23026        assert!(decode(original).is_ok());
23027        for field in [
23028            "condition_wait_occurrence_id",
23029            "condition_key",
23030            "condition_definition_fingerprint",
23031            "timeout_seconds",
23032            "parallel_group_id",
23033            "parallel_group_size",
23034            "parallel_group_index",
23035        ] {
23036            let mut changed = original.clone();
23037            changed[3]["payload"][field] = match field {
23038                "timeout_seconds" | "parallel_group_size" => json!(30),
23039                "parallel_group_index" => json!(0),
23040                _ => json!("changed"),
23041            };
23042            assert!(
23043                decode(&changed).is_err(),
23044                "reopen must reject changed {field}"
23045            );
23046        }
23047        let mut unsettled = original.clone();
23048        unsettled.remove(2);
23049        assert!(
23050            decode(&unsettled).is_err(),
23051            "physical predecessor must be resolved"
23052        );
23053        let mut timed_out = original.clone();
23054        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
23055        assert!(decode(&timed_out).is_err(), "timeout is terminal");
23056        let mut late_resolution = original.clone();
23057        late_resolution.swap(2, 3);
23058        assert!(
23059            decode(&late_resolution).is_err(),
23060            "later history cannot authorize a reopen"
23061        );
23062    }
23063
23064    #[test]
23065    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
23066        let history = vec![
23067            history_event(
23068                "ConditionWaitOpened",
23069                json!({
23070                    "sequence": 3,
23071                    "condition_wait_id": "condition:3",
23072                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23073                    "condition_key": "two-votes",
23074                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23075                }),
23076            ),
23077            history_event(
23078                "SignalReceived",
23079                json!({
23080                    "workflow_sequence": 3,
23081                    "signal_name": "vote",
23082                    "arguments": fixture_envelope(json!(["first"])),
23083                }),
23084            ),
23085            history_event(
23086                "ConditionWaitSatisfied",
23087                json!({
23088                    "sequence": 3,
23089                    "condition_wait_id": "condition:3",
23090                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23091                    "condition_key": "two-votes",
23092                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23093                }),
23094            ),
23095            history_event(
23096                "ConditionWaitOpened",
23097                json!({
23098                    "sequence": 5,
23099                    "condition_wait_id": "condition:5",
23100                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23101                    "condition_key": "two-votes",
23102                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23103                }),
23104            ),
23105            history_event(
23106                "SignalReceived",
23107                json!({
23108                    "workflow_sequence": 5,
23109                    "signal_name": "vote",
23110                    "arguments": fixture_envelope(json!(["second"])),
23111                }),
23112            ),
23113            history_event(
23114                "ConditionWaitSatisfied",
23115                json!({
23116                    "sequence": 5,
23117                    "condition_wait_id": "condition:5",
23118                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23119                    "condition_key": "two-votes",
23120                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23121                }),
23122            ),
23123        ];
23124        for _cold_worker_or_restart in 0..2 {
23125            let ctx = workflow_context(history.clone());
23126            let predicate_ctx = ctx.clone();
23127            let mut wait = Box::pin(ctx.wait_condition(
23128                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
23129                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23130            ));
23131            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23132
23133            assert!(matches!(
23134                wait.as_mut().poll(&mut task_context),
23135                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23136            ));
23137            assert!(ctx.take_commands().expect("commands").is_empty());
23138            ctx.ensure_history_consumed()
23139                .expect("every physical wait-open is consumed");
23140        }
23141    }
23142
23143    #[test]
23144    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
23145        let history = vec![
23146            history_event(
23147                "ConditionWaitOpened",
23148                json!({
23149                    "sequence": 3,
23150                    "condition_wait_id": "condition:3",
23151                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23152                    "condition_key": "approved",
23153                    "condition_definition_fingerprint": "sha256:approved-v1",
23154                }),
23155            ),
23156            history_event(
23157                "UpdateApplied",
23158                json!({
23159                    "sequence": 3,
23160                    "update_id": "update-1",
23161                    "update_name": "approve",
23162                    "arguments": fixture_envelope(json!([false])),
23163                }),
23164            ),
23165            history_event(
23166                "ConditionWaitOpened",
23167                json!({
23168                    "sequence": 5,
23169                    "condition_wait_id": "condition:5",
23170                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23171                    "condition_key": "approved",
23172                    "condition_definition_fingerprint": "sha256:approved-v1",
23173                }),
23174            ),
23175            history_event(
23176                "UpdateApplied",
23177                json!({
23178                    "sequence": 5,
23179                    "update_id": "update-2",
23180                    "update_name": "approve",
23181                    "arguments": fixture_envelope(json!([true])),
23182                }),
23183            ),
23184        ];
23185
23186        for _cold_worker_or_restart in 0..2 {
23187            let ctx = workflow_context(history.clone());
23188            let predicate_ctx = ctx.clone();
23189            let mut wait = Box::pin(ctx.wait_condition(
23190                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
23191                move || {
23192                    Ok(predicate_ctx
23193                        .updates("approve")?
23194                        .last()
23195                        .and_then(|arguments| arguments.first())
23196                        .and_then(Value::as_bool)
23197                        == Some(true))
23198                },
23199            ));
23200            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23201
23202            assert!(matches!(
23203                wait.as_mut().poll(&mut task_context),
23204                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23205            ));
23206            assert!(ctx.take_commands().expect("commands").is_empty());
23207            ctx.ensure_history_consumed()
23208                .expect("every update-driven reopen is consumed");
23209        }
23210    }
23211
23212    #[test]
23213    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
23214        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
23215            ("shared", "sha256:first", "shared", "sha256:second"),
23216            ("first", "sha256:shared", "second", "sha256:shared"),
23217            ("shared", "sha256:shared", "shared", "sha256:shared"),
23218            ("first", "sha256:first", "second", "sha256:second"),
23219        ] {
23220            let history = vec![
23221                history_event(
23222                    "ConditionWaitOpened",
23223                    json!({
23224                        "sequence": 3,
23225                        "condition_wait_id": "condition:3",
23226                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23227                        "condition_key": first_key,
23228                        "condition_definition_fingerprint": first_fingerprint,
23229                    }),
23230                ),
23231                history_event(
23232                    "ConditionWaitSatisfied",
23233                    json!({
23234                        "sequence": 3,
23235                        "condition_wait_id": "condition:3",
23236                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23237                        "condition_key": first_key,
23238                        "condition_definition_fingerprint": first_fingerprint,
23239                    }),
23240                ),
23241                history_event(
23242                    "ConditionWaitOpened",
23243                    json!({
23244                        "sequence": 4,
23245                        "condition_wait_id": "condition:4",
23246                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23247                        "condition_key": second_key,
23248                        "condition_definition_fingerprint": second_fingerprint,
23249                    }),
23250                ),
23251                history_event(
23252                    "ConditionWaitSatisfied",
23253                    json!({
23254                        "sequence": 4,
23255                        "condition_wait_id": "condition:4",
23256                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23257                        "condition_key": second_key,
23258                        "condition_definition_fingerprint": second_fingerprint,
23259                    }),
23260                ),
23261            ];
23262            for _cold_worker_or_restart in 0..2 {
23263                let ctx = workflow_context(history.clone());
23264                let mut task_context = TaskContext::from_waker(noop_waker_ref());
23265                let mut first = Box::pin(ctx.wait_condition(
23266                    ConditionWaitOptions::new(first_key, first_fingerprint),
23267                    || Ok(false),
23268                ));
23269                assert!(matches!(
23270                    first.as_mut().poll(&mut task_context),
23271                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23272                ));
23273
23274                let mut second = Box::pin(ctx.wait_condition(
23275                    ConditionWaitOptions::new(second_key, second_fingerprint),
23276                    || Ok(false),
23277                ));
23278                assert!(matches!(
23279                    second.as_mut().poll(&mut task_context),
23280                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23281                ));
23282                assert!(ctx.take_commands().expect("commands").is_empty());
23283                ctx.ensure_history_consumed()
23284                    .expect("each authored wait consumes one occurrence");
23285            }
23286        }
23287    }
23288
23289    #[test]
23290    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
23291        fn worker() -> Worker {
23292            let client = Client::new("http://127.0.0.1:8080").expect("client");
23293            let mut worker = Worker::new(client, "rust-workers");
23294            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
23295                let mut outcomes = Vec::new();
23296                for _ in 0..2 {
23297                    outcomes.push(
23298                        ctx.wait_condition(
23299                            ConditionWaitOptions::new("shared", "sha256:shared"),
23300                            || Ok(false),
23301                        )
23302                        .await?,
23303                    );
23304                }
23305                Ok(json!(outcomes))
23306            });
23307            worker
23308        }
23309
23310        let task = workflow_task(
23311            "rust.condition-loop",
23312            vec![
23313                history_event(
23314                    "ConditionWaitOpened",
23315                    json!({
23316                        "sequence": 1,
23317                        "condition_wait_id": "condition:1",
23318                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23319                        "condition_key": "shared",
23320                        "condition_definition_fingerprint": "sha256:shared",
23321                    }),
23322                ),
23323                history_event(
23324                    "ConditionWaitSatisfied",
23325                    json!({
23326                        "sequence": 1,
23327                        "condition_wait_id": "condition:1",
23328                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23329                        "condition_key": "shared",
23330                        "condition_definition_fingerprint": "sha256:shared",
23331                    }),
23332                ),
23333                history_event(
23334                    "ConditionWaitOpened",
23335                    json!({
23336                        "sequence": 2,
23337                        "condition_wait_id": "condition:2",
23338                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23339                        "condition_key": "shared",
23340                        "condition_definition_fingerprint": "sha256:shared",
23341                    }),
23342                ),
23343                history_event(
23344                    "ConditionWaitSatisfied",
23345                    json!({
23346                        "sequence": 2,
23347                        "condition_wait_id": "condition:2",
23348                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23349                        "condition_key": "shared",
23350                        "condition_definition_fingerprint": "sha256:shared",
23351                    }),
23352                ),
23353            ],
23354            DEFAULT_CODEC,
23355        );
23356
23357        for _cold_worker_or_restart in 0..2 {
23358            let commands = worker()
23359                .execute_workflow_task(task.clone())
23360                .expect("adjacent loop waits replay deterministically");
23361            assert_eq!(commands.len(), 1);
23362            assert_eq!(commands[0]["type"], "complete_workflow");
23363            assert_eq!(
23364                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23365                json!(["satisfied", "satisfied"])
23366            );
23367        }
23368    }
23369
23370    #[test]
23371    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
23372        let history = vec![history_event(
23373            "ConditionWaitOpened",
23374            json!({
23375                "sequence": 12,
23376                "condition_wait_id": "condition:12",
23377                "condition_wait_occurrence_id": "rust:condition-wait:0",
23378                "condition_key": "approval",
23379                "condition_definition_fingerprint": "sha256:approval-v1",
23380                "timeout_seconds": 30,
23381            }),
23382        )];
23383        for (options, expected_reason) in [
23384            (
23385                ConditionWaitOptions::new("changed", "sha256:approval-v1")
23386                    .timeout(Duration::from_secs(30)),
23387                "condition_wait_key_mismatch",
23388            ),
23389            (
23390                ConditionWaitOptions::new("approval", "sha256:approval-v2")
23391                    .timeout(Duration::from_secs(30)),
23392                "condition_wait_predicate_mismatch",
23393            ),
23394            (
23395                ConditionWaitOptions::new("approval", "sha256:approval-v1")
23396                    .timeout(Duration::from_secs(29)),
23397                "condition_wait_timeout_mismatch",
23398            ),
23399        ] {
23400            let ctx = workflow_context(history.clone());
23401            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
23402            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23403            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23404                wait.as_mut().poll(&mut task_context)
23405            else {
23406                panic!("changed condition definition must fail replay");
23407            };
23408            assert_eq!(failure.reason, expected_reason);
23409            assert_eq!(failure.sequence, Some(12));
23410        }
23411    }
23412
23413    #[test]
23414    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
23415        let error = WorkflowState::new(
23416            vec![history_event(
23417                "ConditionWaitOpened",
23418                json!({
23419                    "sequence": 12,
23420                    "condition_wait_id": "condition:12",
23421                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23422                    "condition_key": "approval",
23423                }),
23424            )],
23425            "rust-workers".to_string(),
23426            DEFAULT_CODEC.to_string(),
23427            None,
23428        )
23429        .expect_err("condition history without a predicate fingerprint must fail");
23430
23431        assert!(matches!(
23432            error,
23433            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23434                if reason == "condition_wait_predicate_fingerprint_missing"
23435        ));
23436    }
23437
23438    #[test]
23439    fn condition_wait_history_requires_authored_occurrence_identity() {
23440        let error = WorkflowState::new(
23441            vec![history_event(
23442                "ConditionWaitOpened",
23443                json!({
23444                    "sequence": 12,
23445                    "condition_wait_id": "condition:12",
23446                    "condition_key": "approval",
23447                    "condition_definition_fingerprint": "sha256:approval-v1",
23448                }),
23449            )],
23450            "rust-workers".to_string(),
23451            DEFAULT_CODEC.to_string(),
23452            None,
23453        )
23454        .expect_err("condition history without occurrence identity must fail");
23455
23456        assert!(matches!(
23457            error,
23458            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23459                if reason == "condition_wait_occurrence_id_missing"
23460        ));
23461    }
23462
23463    #[test]
23464    fn typed_search_attribute_updates_validate_emit_and_replay() {
23465        let update = SearchAttributeUpdate::new()
23466            .keyword("OrderStatus", " waiting ")
23467            .expect("keyword")
23468            .int("Attempt", 3)
23469            .expect("int")
23470            .bool("Escalated", false)
23471            .expect("bool")
23472            .keyword_list("Regions", ["us-east", "eu-west"])
23473            .expect("list")
23474            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
23475            .expect("datetime")
23476            .delete("LegacyStatus")
23477            .expect("delete");
23478        let ctx = workflow_context(Vec::new());
23479        ctx.upsert_search_attributes(update.clone())
23480            .expect("typed update");
23481        assert_eq!(
23482            ctx.take_commands().expect("search-attribute command"),
23483            vec![json!({
23484                "type": "upsert_search_attributes",
23485                "attributes": {
23486                    "Attempt": 3,
23487                    "Escalated": false,
23488                    "LegacyStatus": null,
23489                    "OrderStatus": "waiting",
23490                    "Regions": ["us-east", "eu-west"],
23491                    "UpdatedAt": "2026-08-22T04:00:00Z",
23492                },
23493                "attribute_types": {
23494                    "Attempt": "int",
23495                    "Escalated": "bool",
23496                    "OrderStatus": "keyword",
23497                    "Regions": "keyword_list",
23498                    "UpdatedAt": "datetime",
23499                },
23500            })]
23501        );
23502
23503        let replay = workflow_context(vec![history_event(
23504            "SearchAttributesUpserted",
23505            json!({
23506                "sequence": 6,
23507                "attributes": {
23508                    "Attempt": 3,
23509                    "Escalated": false,
23510                    "LegacyStatus": null,
23511                    "OrderStatus": "waiting",
23512                    "Regions": ["us-east", "eu-west"],
23513                    "UpdatedAt": "2026-08-22T04:00:00Z",
23514                },
23515                "attribute_types": {
23516                    "Attempt": "int",
23517                    "Escalated": "bool",
23518                    "OrderStatus": "keyword",
23519                    "Regions": "keyword_list",
23520                    "UpdatedAt": "datetime",
23521                },
23522                "merged": {},
23523            }),
23524        )]);
23525        replay
23526            .upsert_search_attributes(update)
23527            .expect("matching update replays");
23528        assert!(replay.take_commands().expect("commands").is_empty());
23529        replay.ensure_history_consumed().expect("history consumed");
23530
23531        let type_drift = workflow_context(vec![history_event(
23532            "SearchAttributesUpserted",
23533            json!({
23534                "sequence": 7,
23535                "attributes": {"OrderStatus": "waiting"},
23536                "attribute_types": {"OrderStatus": "keyword"},
23537                "merged": {"OrderStatus": "waiting"},
23538            }),
23539        )]);
23540        let error = type_drift
23541            .upsert_search_attributes(
23542                SearchAttributeUpdate::new()
23543                    .string("OrderStatus", "waiting")
23544                    .expect("string update"),
23545            )
23546            .expect_err("same JSON value with a changed type must fail replay");
23547        assert!(matches!(
23548            error,
23549            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23550                if reason == "search_attribute_type_mismatch"
23551        ));
23552
23553        let malformed_types = WorkflowState::new(
23554            vec![history_event(
23555                "SearchAttributesUpserted",
23556                json!({
23557                    "sequence": 8,
23558                    "attributes": {"OrderStatus": "waiting"},
23559                    "attribute_types": {"OrderStatus": "unsupported"},
23560                    "merged": {"OrderStatus": "waiting"},
23561                }),
23562            )],
23563            "rust-workers".to_string(),
23564            DEFAULT_CODEC.to_string(),
23565            None,
23566        )
23567        .expect_err("unsupported search-attribute type metadata must fail");
23568        assert!(matches!(
23569            malformed_types,
23570            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23571                if reason == "search_attribute_types_malformed"
23572        ));
23573
23574        assert!(matches!(
23575            SearchAttributeUpdate::new().keyword("bad key", "value"),
23576            Err(SearchAttributeUpdateError::InvalidKey(_))
23577        ));
23578        assert!(matches!(
23579            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
23580            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
23581        ));
23582        assert!(matches!(
23583            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
23584            Err(SearchAttributeUpdateError::ValueTooLong { .. })
23585        ));
23586        assert!(matches!(
23587            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
23588            Err(SearchAttributeUpdateError::InvalidDateTime(_))
23589        ));
23590        assert!(matches!(
23591            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
23592            Err(Error::InvalidSearchAttributeUpdate(
23593                SearchAttributeUpdateError::Empty
23594            ))
23595        ));
23596    }
23597
23598    #[test]
23599    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
23600        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
23601        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
23602
23603        assert!(SearchAttributeUpdate::new()
23604            .string("AsciiDescription", ascii)
23605            .is_ok());
23606        assert!(SearchAttributeUpdate::new()
23607            .string("Utf8Description", utf8)
23608            .is_ok());
23609        assert!(matches!(
23610            SearchAttributeUpdate::new().string(
23611                "TooLongDescription",
23612                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
23613            ),
23614            Err(SearchAttributeUpdateError::ValueTooLong {
23615                kind: "string",
23616                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
23617                ..
23618            })
23619        ));
23620    }
23621
23622    #[test]
23623    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
23624        let lone_fire = WorkflowState::new(
23625            vec![history_event(
23626                "TimerFired",
23627                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23628            )],
23629            "rust-workers".to_string(),
23630            DEFAULT_CODEC.to_string(),
23631            None,
23632        )
23633        .expect_err("TimerFired requires TimerScheduled");
23634        assert!(matches!(
23635            lone_fire,
23636            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23637                if reason == "timer_schedule_missing_or_duplicate"
23638        ));
23639
23640        let wrong_identity = WorkflowState::new(
23641            vec![
23642                history_event(
23643                    "TimerScheduled",
23644                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23645                ),
23646                history_event(
23647                    "TimerFired",
23648                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23649                ),
23650            ],
23651            "rust-workers".to_string(),
23652            DEFAULT_CODEC.to_string(),
23653            None,
23654        )
23655        .expect_err("fire must match scheduled timer identity");
23656        assert!(matches!(
23657            wrong_identity,
23658            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23659                if reason == "timer_identity_mismatch"
23660        ));
23661
23662        let duplicate_fire = WorkflowState::new(
23663            vec![
23664                history_event(
23665                    "TimerScheduled",
23666                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23667                ),
23668                history_event(
23669                    "TimerFired",
23670                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23671                ),
23672                history_event(
23673                    "TimerFired",
23674                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23675                ),
23676            ],
23677            "rust-workers".to_string(),
23678            DEFAULT_CODEC.to_string(),
23679            None,
23680        )
23681        .expect_err("a durable timer cannot fire twice");
23682        assert!(matches!(
23683            duplicate_fire,
23684            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23685                if reason == "duplicate_timer_fire"
23686        ));
23687
23688        let wrong_fired_delay = WorkflowState::new(
23689            vec![
23690                history_event(
23691                    "TimerScheduled",
23692                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23693                ),
23694                history_event(
23695                    "TimerFired",
23696                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
23697                ),
23698            ],
23699            "rust-workers".to_string(),
23700            DEFAULT_CODEC.to_string(),
23701            None,
23702        )
23703        .expect_err("timer schedule and fire delays must agree");
23704        assert!(matches!(
23705            wrong_fired_delay,
23706            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23707                if reason == "timer_history_delay_mismatch"
23708        ));
23709    }
23710
23711    #[test]
23712    fn replay_rejects_activity_moved_before_recorded_timer() {
23713        let ctx = workflow_context(vec![
23714            history_event(
23715                "TimerScheduled",
23716                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23717            ),
23718            history_event(
23719                "TimerFired",
23720                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23721            ),
23722            history_event(
23723                "ActivityCompleted",
23724                json!({
23725                    "sequence": 2,
23726                    "activity_type": "after-timer",
23727                    "payload_codec": DEFAULT_CODEC,
23728                    "result": fixture_envelope(json!("done")),
23729                }),
23730            ),
23731        ]);
23732        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
23733        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23734
23735        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23736            activity.as_mut().poll(&mut task_context)
23737        else {
23738            panic!("reordered durable command must be rejected");
23739        };
23740        assert_eq!(failure.reason, "recorded_command_mismatch");
23741        assert_eq!(failure.sequence, Some(1));
23742        assert_eq!(failure.expected.as_deref(), Some("timer"));
23743        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
23744    }
23745
23746    #[test]
23747    fn workflow_context_emits_a_typed_named_signal_wait() {
23748        let ctx = workflow_context(Vec::new());
23749        let mut signal = Box::pin(ctx.wait_signal("finish"));
23750        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23751
23752        assert!(matches!(
23753            signal.as_mut().poll(&mut task_context),
23754            Poll::Pending
23755        ));
23756        assert_eq!(
23757            ctx.take_commands().expect("signal-wait command"),
23758            vec![json!({
23759                "type": "open_signal_wait",
23760                "signal_name": "finish",
23761            })]
23762        );
23763    }
23764
23765    #[test]
23766    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
23767        let ctx = workflow_context(Vec::new());
23768        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
23769        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23770
23771        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
23772        else {
23773            panic!("runtime-reserved signal should be rejected");
23774        };
23775        assert!(message.contains("reserved by the workflow runtime"));
23776        assert!(ctx.take_commands().expect("commands").is_empty());
23777    }
23778
23779    #[tokio::test]
23780    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
23781        let client = Client::builder("http://127.0.0.1:9")
23782            .build()
23783            .expect("client");
23784        let error = client
23785            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
23786            .await
23787            .expect_err("runtime-reserved signal should be rejected before transport");
23788
23789        assert!(
23790            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
23791        );
23792    }
23793
23794    #[test]
23795    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
23796        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23797            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23798                value.to_string(),
23799            )]))
23800            .expect("message payload");
23801            json!({
23802                "schema": MESSAGE_STREAM_SCHEMA,
23803                "stream_name": "orders",
23804                "message_id": message_id,
23805                "position": position,
23806                "payload_envelope": payload,
23807            })
23808        }
23809
23810        fn opened(sequence: u64) -> HistoryEvent {
23811            history_event(
23812                "SignalWaitOpened",
23813                json!({
23814                    "sequence": sequence,
23815                    "signal_name": MESSAGE_STREAM_SIGNAL,
23816                }),
23817            )
23818        }
23819
23820        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23821            history_event(
23822                "SignalApplied",
23823                json!({
23824                    "sequence": sequence,
23825                    "signal_name": MESSAGE_STREAM_SIGNAL,
23826                    "value": fixture_envelope(json!([delivery])),
23827                }),
23828            )
23829        }
23830
23831        fn received(delivery: Value) -> HistoryEvent {
23832            history_event(
23833                "SignalReceived",
23834                json!({
23835                    "signal_name": MESSAGE_STREAM_SIGNAL,
23836                    "arguments": fixture_envelope(json!([delivery])),
23837                    "payload_codec": DEFAULT_CODEC,
23838                }),
23839            )
23840        }
23841
23842        let client = Client::new("http://127.0.0.1:8080").expect("client");
23843        let mut worker = Worker::new(client, "rust-workers");
23844        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
23845            let messages = ctx.message_stream("orders")?.receive(2).await?;
23846            Ok(json!(messages
23847                .into_iter()
23848                .map(|message| message.message_id)
23849                .collect::<Vec<_>>()))
23850        });
23851
23852        let first = delivery("message-1", 1, "one");
23853        let second = delivery("message-2", 2, "two");
23854        let batch = worker
23855            .execute_workflow_task_decision(workflow_task(
23856                "rust.message-stream-batch",
23857                vec![
23858                    opened(1),
23859                    received(first.clone()),
23860                    applied(1, first.clone()),
23861                    received(first.clone()),
23862                    received(second),
23863                ],
23864                DEFAULT_CODEC,
23865            ))
23866            .expect("worker task consumes the available batch");
23867
23868        assert_eq!(batch.commands.len(), 1);
23869        assert_eq!(batch.commands[0]["type"], "complete_workflow");
23870        assert_eq!(
23871            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
23872                .expect("workflow result"),
23873            json!(["message-1", "message-2"])
23874        );
23875        assert_eq!(
23876            batch.message_stream_cursors,
23877            vec![json!({"stream_name": "orders", "through_position": 2})]
23878        );
23879        assert!(batch.message_stream_waits.is_empty());
23880
23881        let partial = worker
23882            .execute_workflow_task_decision(workflow_task(
23883                "rust.message-stream-batch",
23884                vec![opened(1), received(first.clone()), applied(1, first)],
23885                DEFAULT_CODEC,
23886            ))
23887            .expect("worker task returns without waiting for a missing second item");
23888        assert_eq!(partial.commands.len(), 1);
23889        assert_eq!(partial.commands[0]["type"], "complete_workflow");
23890        assert_eq!(
23891            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
23892                .expect("workflow result"),
23893            json!(["message-1"])
23894        );
23895        assert_eq!(
23896            partial.message_stream_cursors,
23897            vec![json!({"stream_name": "orders", "through_position": 1})]
23898        );
23899        assert!(partial.message_stream_waits.is_empty());
23900    }
23901
23902    #[test]
23903    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
23904        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23905            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23906                value.to_string(),
23907            )]))
23908            .expect("message payload");
23909            json!({
23910                "schema": MESSAGE_STREAM_SCHEMA,
23911                "stream_name": "orders",
23912                "message_id": message_id,
23913                "position": position,
23914                "payload_envelope": payload,
23915            })
23916        }
23917
23918        fn opened(sequence: u64) -> HistoryEvent {
23919            history_event(
23920                "SignalWaitOpened",
23921                json!({
23922                    "sequence": sequence,
23923                    "signal_name": MESSAGE_STREAM_SIGNAL,
23924                }),
23925            )
23926        }
23927
23928        fn received(delivery: Value) -> HistoryEvent {
23929            history_event(
23930                "SignalReceived",
23931                json!({
23932                    "signal_name": MESSAGE_STREAM_SIGNAL,
23933                    "arguments": fixture_envelope(json!([delivery])),
23934                    "payload_codec": DEFAULT_CODEC,
23935                }),
23936            )
23937        }
23938
23939        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23940            history_event(
23941                "SignalApplied",
23942                json!({
23943                    "sequence": sequence,
23944                    "signal_name": MESSAGE_STREAM_SIGNAL,
23945                    "value": fixture_envelope(json!([delivery])),
23946                }),
23947            )
23948        }
23949
23950        let client = Client::new("http://127.0.0.1:8080").expect("client");
23951        let mut worker = Worker::new(client, "rust-workers");
23952        worker.register_workflow(
23953            "rust.message-stream-partial-batches",
23954            |ctx, _input| async move {
23955                let stream = ctx.message_stream("orders")?;
23956                let first = stream.receive(10).await?;
23957                let second = stream.receive(10).await?;
23958                Ok(json!([
23959                    first
23960                        .into_iter()
23961                        .map(|message| message.message_id)
23962                        .collect::<Vec<_>>(),
23963                    second
23964                        .into_iter()
23965                        .map(|message| message.message_id)
23966                        .collect::<Vec<_>>(),
23967                ]))
23968            },
23969        );
23970
23971        let first = delivery("message-1", 1, "one");
23972        let second = delivery("message-2", 2, "two");
23973        let decision = worker
23974            .execute_workflow_task_decision(workflow_task(
23975                "rust.message-stream-partial-batches",
23976                vec![
23977                    opened(1),
23978                    received(first.clone()),
23979                    applied(1, first),
23980                    opened(2),
23981                    received(second.clone()),
23982                    applied(2, second),
23983                ],
23984                DEFAULT_CODEC,
23985            ))
23986            .expect("cold replay preserves both authored receive boundaries");
23987
23988        assert_eq!(decision.commands.len(), 1);
23989        assert_eq!(decision.commands[0]["type"], "complete_workflow");
23990        assert_eq!(
23991            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
23992                .expect("workflow result"),
23993            json!([["message-1"], ["message-2"]])
23994        );
23995        assert_eq!(
23996            decision.message_stream_cursors,
23997            vec![json!({"stream_name": "orders", "through_position": 2})]
23998        );
23999        assert!(decision.message_stream_waits.is_empty());
24000    }
24001
24002    #[test]
24003    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
24004        let ctx = workflow_context(Vec::new());
24005        let stream = ctx.message_stream("orders").expect("message stream");
24006        let mut receive = Box::pin(stream.receive(10));
24007        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24008
24009        assert!(matches!(
24010            receive.as_mut().poll(&mut task_context),
24011            Poll::Pending
24012        ));
24013        assert_eq!(
24014            ctx.take_commands().expect("message-stream wait command"),
24015            vec![json!({
24016                "type": "open_signal_wait",
24017                "signal_name": MESSAGE_STREAM_SIGNAL,
24018            })]
24019        );
24020        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
24021        assert!(cursors.is_empty());
24022        assert_eq!(
24023            waits,
24024            vec![json!({"stream_name": "orders", "after_position": 0})]
24025        );
24026    }
24027
24028    #[test]
24029    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
24030        let ctx = workflow_context(vec![history_event(
24031            "SignalReceived",
24032            json!({
24033                "signal_name": MESSAGE_STREAM_SIGNAL,
24034                "arguments": fixture_envelope(json!([{
24035                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
24036                    "stream_name": "orders",
24037                    "through_position": 2,
24038                }])),
24039                "payload_codec": DEFAULT_CODEC,
24040            }),
24041        )]);
24042        let stream = ctx.message_stream("orders").expect("message stream");
24043        let mut receive = Box::pin(stream.receive(10));
24044        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24045
24046        assert!(matches!(
24047            receive.as_mut().poll(&mut task_context),
24048            Poll::Pending
24049        ));
24050        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
24051        assert_eq!(
24052            cursors,
24053            vec![json!({"stream_name": "orders", "through_position": 2})]
24054        );
24055        assert_eq!(
24056            waits,
24057            vec![json!({"stream_name": "orders", "after_position": 2})]
24058        );
24059    }
24060
24061    #[test]
24062    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
24063        let mut empty_map = BTreeMap::new();
24064        let mut nested = BTreeMap::new();
24065        nested.insert(
24066            "value".to_string(),
24067            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
24068        );
24069        let values = vec![
24070            AvroValue::Bytes(vec![0, 255]),
24071            AvroValue::Long(1),
24072            AvroValue::Double(1.0),
24073            AvroValue::Array(Vec::new()),
24074            AvroValue::Map(std::mem::take(&mut empty_map)),
24075            AvroValue::Map(nested),
24076        ];
24077        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
24078        let transport = vec![json!({
24079            "schema": MESSAGE_STREAM_SCHEMA,
24080            "stream_name": "orders",
24081            "message_id": "message-1",
24082            "position": 1,
24083            "payload_envelope": payload,
24084        })];
24085
24086        for _ in 0..2 {
24087            let Some(MessageStreamDelivery::Message(message)) =
24088                decode_message_stream_delivery(transport.clone()).expect("delivery")
24089            else {
24090                panic!("message delivery expected");
24091            };
24092            assert_eq!(message.arguments, values);
24093            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
24094            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
24095        }
24096    }
24097
24098    #[test]
24099    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
24100        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
24101            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
24102                value.to_string(),
24103            )]))
24104            .expect("message payload");
24105            json!({
24106                "schema": MESSAGE_STREAM_SCHEMA,
24107                "stream_name": "orders",
24108                "message_id": message_id,
24109                "position": position,
24110                "payload_envelope": payload,
24111            })
24112        }
24113
24114        fn opened(sequence: u64) -> HistoryEvent {
24115            history_event(
24116                "SignalWaitOpened",
24117                json!({
24118                    "sequence": sequence,
24119                    "signal_name": MESSAGE_STREAM_SIGNAL,
24120                }),
24121            )
24122        }
24123
24124        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
24125            history_event(
24126                "SignalApplied",
24127                json!({
24128                    "sequence": sequence,
24129                    "signal_name": MESSAGE_STREAM_SIGNAL,
24130                    "value": fixture_envelope(json!([delivery])),
24131                }),
24132            )
24133        }
24134
24135        fn worker() -> Worker {
24136            let client = Client::new("http://127.0.0.1:8080").expect("client");
24137            let mut worker = Worker::new(client, "rust-workers");
24138            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
24139                let stream = ctx.message_stream("orders")?;
24140                let first = stream.receive_one().await?;
24141                let second = stream.receive_one().await?;
24142                Ok(json!([first.message_id, second.message_id]))
24143            });
24144            worker
24145        }
24146
24147        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
24148            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
24149            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
24150            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
24151            task
24152        }
24153
24154        let waiting = worker()
24155            .execute_workflow_task_decision(workflow_task(
24156                "rust.message-stream",
24157                Vec::new(),
24158                DEFAULT_CODEC,
24159            ))
24160            .expect("first worker opens the stream wait");
24161        assert_eq!(
24162            waiting.commands,
24163            vec![json!({
24164                "type": "open_signal_wait",
24165                "signal_name": MESSAGE_STREAM_SIGNAL,
24166            })]
24167        );
24168        assert!(waiting.message_stream_cursors.is_empty());
24169        assert_eq!(
24170            waiting.message_stream_waits,
24171            vec![json!({"stream_name": "orders", "after_position": 0})]
24172        );
24173
24174        let first_delivery = delivery("message-1", 1, "one");
24175        let first_arrival = worker()
24176            .execute_workflow_task_decision(task_with_resume(
24177                vec![opened(1)],
24178                first_delivery.clone(),
24179            ))
24180            .expect("replacement worker consumes the first arrival");
24181        assert_eq!(
24182            first_arrival.commands,
24183            vec![json!({
24184                "type": "open_signal_wait",
24185                "signal_name": MESSAGE_STREAM_SIGNAL,
24186            })]
24187        );
24188        assert_eq!(
24189            first_arrival.message_stream_cursors,
24190            vec![json!({"stream_name": "orders", "through_position": 1})]
24191        );
24192        assert_eq!(
24193            first_arrival.message_stream_waits,
24194            vec![json!({"stream_name": "orders", "after_position": 1})]
24195        );
24196
24197        let second_delivery = delivery("message-2", 2, "two");
24198        let first_applied = applied(1, first_delivery);
24199        let completed = worker()
24200            .execute_workflow_task_decision(task_with_resume(
24201                vec![opened(1), first_applied.clone(), opened(2)],
24202                second_delivery.clone(),
24203            ))
24204            .expect("next replacement worker consumes the second arrival");
24205        assert_eq!(completed.commands.len(), 1);
24206        assert_eq!(completed.commands[0]["type"], "complete_workflow");
24207        assert_eq!(
24208            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
24209                .expect("workflow result"),
24210            json!(["message-1", "message-2"])
24211        );
24212        assert_eq!(
24213            completed.message_stream_cursors,
24214            vec![json!({"stream_name": "orders", "through_position": 2})]
24215        );
24216        assert!(completed.message_stream_waits.is_empty());
24217
24218        let replay_history = vec![
24219            opened(1),
24220            first_applied,
24221            opened(2),
24222            applied(2, second_delivery),
24223        ];
24224        for _cold_worker_or_restart in 0..2 {
24225            let replayed = worker()
24226                .execute_workflow_task_decision(workflow_task(
24227                    "rust.message-stream",
24228                    replay_history.clone(),
24229                    DEFAULT_CODEC,
24230                ))
24231                .expect("cold worker replays each logical message exactly once");
24232            assert_eq!(replayed.commands.len(), 1);
24233            assert_eq!(
24234                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
24235                    .expect("replayed workflow result"),
24236                json!(["message-1", "message-2"])
24237            );
24238            assert_eq!(
24239                replayed.message_stream_cursors,
24240                vec![json!({"stream_name": "orders", "through_position": 2})]
24241            );
24242            assert!(replayed.message_stream_waits.is_empty());
24243        }
24244    }
24245
24246    #[test]
24247    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
24248        assert!(!worker_protocol_supports_message_streams("1.14"));
24249        assert!(worker_protocol_supports_message_streams("1.15"));
24250        assert!(worker_protocol_supports_message_streams("1.16"));
24251        assert!(worker_protocol_supports_message_streams(
24252            WORKER_PROTOCOL_VERSION
24253        ));
24254        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
24255    }
24256
24257    #[test]
24258    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
24259        let ctx = workflow_context(vec![
24260            history_event(
24261                "ConditionWaitOpened",
24262                json!({
24263                    "sequence": 1,
24264                    "condition_wait_id": "condition:1",
24265                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24266                    "condition_key": "signal:finish",
24267                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24268                }),
24269            ),
24270            history_event(
24271                "ConditionWaitSatisfied",
24272                json!({
24273                    "sequence": 1,
24274                    "condition_wait_id": "condition:1",
24275                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24276                    "condition_key": "signal:finish",
24277                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24278                }),
24279            ),
24280            history_event(
24281                "SignalReceived",
24282                json!({"signal_name": "finish", "arguments": []}),
24283            ),
24284        ]);
24285        let mut signal = Box::pin(ctx.wait_signal("finish"));
24286        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24287
24288        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24289            signal.as_mut().poll(&mut task_context)
24290        else {
24291            panic!("condition history must not resolve as a typed signal wait");
24292        };
24293        assert_eq!(failure.reason, "recorded_command_mismatch");
24294        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
24295    }
24296
24297    #[test]
24298    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
24299        let signal_then_timer = vec![
24300            history_event(
24301                "SignalWaitOpened",
24302                json!({"sequence": 1, "signal_name": "go"}),
24303            ),
24304            history_event(
24305                "SignalApplied",
24306                json!({
24307                    "sequence": 1,
24308                    "signal_name": "go",
24309                    "value": fixture_envelope(json!(["now"])),
24310                }),
24311            ),
24312            history_event(
24313                "TimerScheduled",
24314                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24315            ),
24316            history_event(
24317                "TimerFired",
24318                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24319            ),
24320        ];
24321
24322        let ctx = workflow_context(signal_then_timer.clone());
24323        let mut signal = Box::pin(ctx.wait_signal("go"));
24324        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24325        assert!(matches!(
24326            signal.as_mut().poll(&mut task_context),
24327            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
24328        ));
24329        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
24330        assert!(matches!(
24331            timer.as_mut().poll(&mut task_context),
24332            Poll::Ready(Ok(()))
24333        ));
24334        ctx.ensure_history_consumed()
24335            .expect("signal and timer history consumed in order");
24336
24337        let reordered = workflow_context(signal_then_timer);
24338        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
24339        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24340            timer_first.as_mut().poll(&mut task_context)
24341        else {
24342            panic!("timer cannot consume signal-wait-first history");
24343        };
24344        assert_eq!(failure.reason, "recorded_command_mismatch");
24345        assert_eq!(failure.sequence, Some(1));
24346        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
24347
24348        let timer_then_signal = vec![
24349            history_event(
24350                "TimerScheduled",
24351                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24352            ),
24353            history_event(
24354                "TimerFired",
24355                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24356            ),
24357            history_event(
24358                "SignalWaitOpened",
24359                json!({"sequence": 2, "signal_name": "go"}),
24360            ),
24361            history_event(
24362                "SignalApplied",
24363                json!({
24364                    "sequence": 2,
24365                    "signal_name": "go",
24366                    "value": fixture_envelope(json!([])),
24367                }),
24368            ),
24369        ];
24370        let reordered = workflow_context(timer_then_signal);
24371        let mut signal_first = Box::pin(reordered.wait_signal("go"));
24372        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24373            signal_first.as_mut().poll(&mut task_context)
24374        else {
24375            panic!("signal wait cannot consume timer-first history");
24376        };
24377        assert_eq!(failure.reason, "recorded_command_mismatch");
24378        assert_eq!(failure.sequence, Some(1));
24379        assert_eq!(failure.expected.as_deref(), Some("timer"));
24380    }
24381
24382    #[test]
24383    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
24384        let duplicate_timer = WorkflowState::new(
24385            vec![
24386                history_event(
24387                    "TimerScheduled",
24388                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24389                ),
24390                history_event(
24391                    "TimerScheduled",
24392                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24393                ),
24394            ],
24395            "rust-workers".to_string(),
24396            DEFAULT_CODEC.to_string(),
24397            None,
24398        )
24399        .expect_err("one workflow sequence cannot schedule two timers");
24400        assert!(matches!(
24401            duplicate_timer,
24402            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24403                if reason == "timer_schedule_missing_or_duplicate"
24404        ));
24405
24406        let colliding_kinds = WorkflowState::new(
24407            vec![
24408                history_event(
24409                    "TimerScheduled",
24410                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24411                ),
24412                history_event(
24413                    "ActivityCompleted",
24414                    json!({"sequence": 1, "activity_type": "same-sequence"}),
24415                ),
24416            ],
24417            "rust-workers".to_string(),
24418            DEFAULT_CODEC.to_string(),
24419            None,
24420        )
24421        .expect_err("one workflow sequence cannot identify two command kinds");
24422        assert!(matches!(
24423            colliding_kinds,
24424            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24425                if reason == "durable_command_sequence_collision"
24426        ));
24427
24428        let duplicate_signal_wait = WorkflowState::new(
24429            vec![
24430                history_event(
24431                    "SignalWaitOpened",
24432                    json!({"sequence": 1, "signal_name": "go"}),
24433                ),
24434                history_event(
24435                    "SignalWaitOpened",
24436                    json!({"sequence": 1, "signal_name": "go"}),
24437                ),
24438            ],
24439            "rust-workers".to_string(),
24440            DEFAULT_CODEC.to_string(),
24441            None,
24442        )
24443        .expect_err("one workflow sequence cannot open two signal waits");
24444        assert!(matches!(
24445            duplicate_signal_wait,
24446            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24447                if reason == "signal_wait_open_missing_or_duplicate"
24448        ));
24449    }
24450
24451    #[test]
24452    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
24453        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
24454            .expect("side-effect result");
24455        let ctx = workflow_context(vec![history_event(
24456            "SideEffectRecorded",
24457            json!({"sequence": 99, "result": result}),
24458        )]);
24459
24460        let replayed: Value = ctx
24461            .side_effect(|| panic!("recorded side effect must not run"))
24462            .expect("positive global workflow sequence is valid");
24463        assert_eq!(replayed, json!({"captured": true}));
24464        ctx.ensure_history_consumed().expect("history consumed");
24465    }
24466
24467    #[test]
24468    fn workflow_history_rejects_zero_and_descending_command_sequences() {
24469        let result =
24470            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
24471        let zero = WorkflowState::new(
24472            vec![history_event(
24473                "SideEffectRecorded",
24474                json!({"sequence": 0, "result": result.clone()}),
24475            )],
24476            "rust-workers".to_string(),
24477            DEFAULT_CODEC.to_string(),
24478            None,
24479        )
24480        .expect_err("durable command sequences must be positive");
24481        assert!(matches!(
24482            zero,
24483            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24484                if reason == "durable_command_sequence_invalid"
24485        ));
24486
24487        let descending = WorkflowState::new(
24488            vec![
24489                history_event(
24490                    "SideEffectRecorded",
24491                    json!({"sequence": 3, "result": result}),
24492                ),
24493                history_event(
24494                    "VersionMarkerRecorded",
24495                    json!({
24496                        "sequence": 2,
24497                        "change_id": "descending-marker",
24498                        "version": 1,
24499                        "min_supported": 1,
24500                        "max_supported": 1,
24501                    }),
24502                ),
24503            ],
24504            "rust-workers".to_string(),
24505            DEFAULT_CODEC.to_string(),
24506            None,
24507        )
24508        .expect_err("new durable commands must remain strictly ordered");
24509        let Error::NonDeterministicReplay(failure) = descending else {
24510            panic!("expected typed replay failure");
24511        };
24512        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
24513        assert_eq!(failure.sequence, Some(2));
24514        assert_eq!(
24515            failure.expected.as_deref(),
24516            Some("workflow sequence greater than 3")
24517        );
24518        assert_eq!(failure.actual.as_deref(), Some("2"));
24519    }
24520
24521    #[test]
24522    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
24523        fn worker() -> Worker {
24524            let client = Client::new("http://127.0.0.1:8080").expect("client");
24525            let mut worker = Worker::new(client, "rust-workers");
24526            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
24527                ctx.wait_signal("finish").await?;
24528                let marker: String =
24529                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
24530                assert_eq!(marker, "after-finish");
24531                Ok(json!("finished"))
24532            });
24533            worker
24534        }
24535
24536        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
24537            .expect("side-effect result");
24538        let task = workflow_task(
24539            "rust.finish-after-gaps",
24540            vec![
24541                history_event(
24542                    "SignalWaitOpened",
24543                    json!({"sequence": 1, "signal_name": "finish"}),
24544                ),
24545                history_event(
24546                    "SignalReceived",
24547                    json!({
24548                        "signal_id": "increment-3",
24549                        "signal_name": "increment",
24550                        "workflow_sequence": 2,
24551                        "payload_codec": DEFAULT_CODEC,
24552                        "arguments": fixture_envelope(json!([3])),
24553                    }),
24554                ),
24555                history_event(
24556                    "SignalReceived",
24557                    json!({
24558                        "signal_id": "increment-5",
24559                        "signal_name": "increment",
24560                        "workflow_sequence": 3,
24561                        "payload_codec": DEFAULT_CODEC,
24562                        "arguments": fixture_envelope(json!([5])),
24563                    }),
24564                ),
24565                history_event(
24566                    "SignalReceived",
24567                    json!({
24568                        "signal_id": "finish",
24569                        "signal_name": "finish",
24570                        "workflow_sequence": 4,
24571                        "payload_codec": DEFAULT_CODEC,
24572                        "arguments": fixture_envelope(json!([])),
24573                    }),
24574                ),
24575                history_event(
24576                    "SignalApplied",
24577                    json!({
24578                        "sequence": 1,
24579                        "signal_id": "finish",
24580                        "signal_name": "finish",
24581                        "payload_codec": DEFAULT_CODEC,
24582                        "value": fixture_envelope(json!([])),
24583                    }),
24584                ),
24585                history_event(
24586                    "SideEffectRecorded",
24587                    json!({"sequence": 5, "result": marker}),
24588                ),
24589            ],
24590            DEFAULT_CODEC,
24591        );
24592
24593        for _original_or_cold_worker in 0..2 {
24594            let commands = worker()
24595                .execute_workflow_task(task.clone())
24596                .expect("signal gaps preserve deterministic replay");
24597            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
24598            assert_eq!(commands[0]["type"], "complete_workflow");
24599            assert_eq!(
24600                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24601                json!("finished")
24602            );
24603        }
24604    }
24605
24606    #[test]
24607    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
24608        let ctx = workflow_context(Vec::new());
24609        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
24610        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24611        assert!(matches!(
24612            sleep.as_mut().poll(&mut task_context),
24613            Poll::Ready(Err(Error::TimerDurationOverflow))
24614        ));
24615        assert!(ctx.take_commands().expect("commands").is_empty());
24616    }
24617
24618    #[test]
24619    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
24620        let entries = AvroValue::Map(BTreeMap::from([
24621            ("text".to_string(), AvroValue::String("same".to_string())),
24622            (
24623                "nested".to_string(),
24624                AvroValue::Map(BTreeMap::from([
24625                    ("beta".to_string(), AvroValue::Long(2)),
24626                    ("alpha".to_string(), AvroValue::Long(1)),
24627                ])),
24628            ),
24629            ("long".to_string(), AvroValue::Long(7)),
24630            ("double".to_string(), AvroValue::Double(7.0)),
24631            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
24632        ]));
24633        let ctx = workflow_context(Vec::new());
24634        ctx.upsert_memo(entries.clone()).expect("valid memo update");
24635        let commands = ctx.take_commands().expect("commands");
24636
24637        assert_eq!(commands.len(), 1);
24638        assert_eq!(commands[0]["type"], "upsert_memo");
24639        let server_entries = json!({
24640            "codec": "avro",
24641            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
24642        });
24643        assert_eq!(
24644            commands[0]["entries"]
24645                .as_object()
24646                .expect("entries envelope")
24647                .keys()
24648                .collect::<Vec<_>>(),
24649            vec!["blob", "codec"]
24650        );
24651        assert_eq!(commands[0]["entries"], server_entries);
24652        let wire_entries =
24653            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
24654        assert_eq!(wire_entries, entries);
24655
24656        let history = vec![history_event(
24657            "MemoUpserted",
24658            json!({
24659                "sequence": 1,
24660                "entries": server_entries.clone(),
24661                "merged": server_entries,
24662            }),
24663        )];
24664        let replay = workflow_context(history.clone());
24665        replay
24666            .upsert_memo(entries.clone())
24667            .expect("matching replay identity");
24668        assert!(replay.take_commands().expect("replay commands").is_empty());
24669
24670        let changed_types = AvroValue::Map(BTreeMap::from([
24671            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
24672            (
24673                "nested".to_string(),
24674                AvroValue::Map(BTreeMap::from([
24675                    ("alpha".to_string(), AvroValue::Long(1)),
24676                    ("beta".to_string(), AvroValue::Long(2)),
24677                ])),
24678            ),
24679            ("long".to_string(), AvroValue::Double(7.0)),
24680            ("double".to_string(), AvroValue::Long(7)),
24681            ("binary".to_string(), AvroValue::String("same".to_string())),
24682        ]));
24683        let error = workflow_context(history)
24684            .upsert_memo(changed_types)
24685            .expect_err("memo replay identity must preserve Avro value types");
24686        assert!(matches!(
24687            error,
24688            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24689        ));
24690    }
24691
24692    #[test]
24693    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
24694        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
24695            .expect("memo envelope");
24696        let replay = workflow_context(vec![history_event(
24697            "MemoUpserted",
24698            json!({
24699                "sequence": 1,
24700                "entries": original.clone(),
24701                "merged": original
24702            }),
24703        )]);
24704        let error = replay
24705            .upsert_memo(json!({"stage": "changed"}))
24706            .expect_err("changed memo update must fail replay");
24707        assert!(matches!(
24708            error,
24709            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24710        ));
24711
24712        let invalid = workflow_context(Vec::new())
24713            .upsert_memo(
24714                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
24715            )
24716            .expect_err("oversized key");
24717        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
24718    }
24719
24720    #[test]
24721    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
24722        let negative_zero = AvroValue::Map(BTreeMap::from([(
24723            "reading".to_string(),
24724            AvroValue::Double(-0.0),
24725        )]));
24726        let negative_zero_envelope =
24727            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
24728        let history = vec![history_event(
24729            "MemoUpserted",
24730            json!({
24731                "sequence": 1,
24732                "entries": negative_zero_envelope.clone(),
24733                "merged": negative_zero_envelope,
24734            }),
24735        )];
24736
24737        workflow_context(history.clone())
24738            .upsert_memo(negative_zero)
24739            .expect("matching negative-zero history identity");
24740
24741        let error = workflow_context(history)
24742            .upsert_memo(AvroValue::Map(BTreeMap::from([(
24743                "reading".to_string(),
24744                AvroValue::Double(0.0),
24745            )])))
24746            .expect_err("positive zero must not consume negative-zero memo history");
24747        assert!(matches!(
24748            error,
24749            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24750        ));
24751    }
24752
24753    #[test]
24754    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
24755        let supported = json!({
24756            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
24757            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
24758        });
24759        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
24760        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
24761            "workflow_memo_updates": {"supported": false},
24762            "supported_workflow_task_commands": ["upsert_memo"]
24763        }))));
24764        assert!(commands_use_workflow_memo_updates(&[json!({
24765            "type": "upsert_memo",
24766            "entries": {"stage": "processing"}
24767        })]));
24768    }
24769
24770    #[test]
24771    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
24772        let client = Client::new("http://127.0.0.1:8080").expect("client");
24773        let mut worker = Worker::new(client, "rust-workers");
24774        worker.register_workflow("rust.timer", |ctx, _input| async move {
24775            ctx.sleep(Duration::from_secs(5)).await?;
24776            ctx.activity("after-timer", json!([])).await
24777        });
24778
24779        let task = |history_events| WorkflowTask {
24780            task_id: "wft-rust-timer-1".to_string(),
24781            workflow_command_id: None,
24782            workflow_id: Some("wf-rust-timer".to_string()),
24783            run_id: Some("run-rust-timer".to_string()),
24784            workflow_type: "rust.timer".to_string(),
24785            cancel_requested: false,
24786            payload_codec: DEFAULT_CODEC.to_string(),
24787            arguments: Some(
24788                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24789            ),
24790            history_events,
24791            total_history_events: None,
24792            history_size_bytes: None,
24793            continue_as_new_recommended: None,
24794            history_budget_pressure: None,
24795            next_history_page_token: None,
24796            workflow_task_attempt: 1,
24797            workflow_signal_id: None,
24798            signal_name: None,
24799            signal_arguments: None,
24800            workflow_update_id: None,
24801            update_name: None,
24802            lease_owner: Some("rust-worker".to_string()),
24803        };
24804
24805        let initial = worker
24806            .execute_workflow_task(task(Vec::new()))
24807            .expect("initial timer task");
24808        assert_eq!(
24809            initial,
24810            vec![json!({"type": "start_timer", "delay_seconds": 5})]
24811        );
24812
24813        let activity_result =
24814            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
24815        let replayed = worker
24816            .execute_workflow_task(task(vec![
24817                history_event(
24818                    "TimerScheduled",
24819                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24820                ),
24821                history_event(
24822                    "TimerFired",
24823                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24824                ),
24825                history_event(
24826                    "ActivityCompleted",
24827                    json!({
24828                        "sequence": 2,
24829                        "activity_type": "after-timer",
24830                        "payload_codec": DEFAULT_CODEC,
24831                        "result": activity_result,
24832                    }),
24833                ),
24834            ]))
24835            .expect("replayed workflow task");
24836        assert_eq!(replayed.len(), 1);
24837        assert_eq!(replayed[0]["type"], "complete_workflow");
24838        assert_eq!(
24839            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
24840            json!("done")
24841        );
24842    }
24843
24844    #[test]
24845    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
24846        let client = Client::new("http://127.0.0.1:8080").expect("client");
24847        let mut worker = Worker::new(client, "rust-workers");
24848        worker.register_workflow("rust.continue", |ctx, _input| async move {
24849            ctx.continue_as_new_with_options(
24850                ContinueAsNewOptions::new()
24851                    .workflow_type("rust.next")
24852                    .task_queue("next-workers"),
24853                json!([2, {"cursor": "next"}]),
24854            )
24855        });
24856
24857        let commands = worker
24858            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
24859            .expect("continue-as-new command");
24860
24861        assert_eq!(commands.len(), 1);
24862        assert_eq!(commands[0]["type"], "continue_as_new");
24863        assert_eq!(commands[0]["workflow_type"], "rust.next");
24864        assert_eq!(commands[0]["queue"], "next-workers");
24865        assert_eq!(
24866            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
24867                .expect("continue-as-new arguments"),
24868            json!([2, {"cursor": "next"}])
24869        );
24870    }
24871
24872    #[test]
24873    fn continue_as_new_preserves_typed_arguments() {
24874        let client = Client::new("http://127.0.0.1:8080").expect("client");
24875        let mut worker = Worker::new(client, "rust-workers");
24876        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
24877            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
24878            unreachable!("continue-as-new returns a control-flow error")
24879        });
24880
24881        let commands = worker
24882            .execute_workflow_task(workflow_task(
24883                "rust.typed-continue",
24884                Vec::new(),
24885                DEFAULT_CODEC,
24886            ))
24887            .expect("typed continue-as-new command");
24888
24889        assert_eq!(commands[0]["type"], "continue_as_new");
24890        assert_eq!(
24891            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
24892                .expect("typed continue arguments"),
24893            AvroValue::Array(vec![typed_fidelity_probe()])
24894        );
24895    }
24896
24897    #[test]
24898    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
24899        let client = Client::new("http://127.0.0.1:8080").expect("client");
24900        let mut worker = Worker::new(client, "rust-workers");
24901        worker.register_workflow("rust.continue", |ctx, _input| async move {
24902            ctx.continue_as_new(json!([2]))
24903        });
24904        let task = workflow_task(
24905            "rust.continue",
24906            vec![history_event(
24907                "WorkflowContinuedAsNew",
24908                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
24909            )],
24910            DEFAULT_CODEC,
24911        );
24912
24913        for _worker_restart_or_redelivery in 0..2 {
24914            let commands = worker
24915                .execute_workflow_task(task.clone())
24916                .expect("recorded transition replays");
24917            assert!(
24918                commands.is_empty(),
24919                "replay must not emit another successor"
24920            );
24921        }
24922    }
24923
24924    #[test]
24925    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
24926        let ctx = workflow_context(Vec::new());
24927        let error = ctx
24928            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
24929            .expect_err("blank queue must be rejected");
24930
24931        let Error::InvalidContinueAsNewOptions(error) = error else {
24932            panic!("expected typed continue-as-new validation error");
24933        };
24934        assert_eq!(error.field, "task_queue");
24935        assert!(ctx.take_commands().expect("commands").is_empty());
24936    }
24937
24938    #[test]
24939    fn workflow_context_exposes_server_history_budget() {
24940        let client = Client::new("http://127.0.0.1:8080").expect("client");
24941        let mut worker = Worker::new(client, "rust-workers");
24942        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
24943            let budget = ctx.history_budget()?;
24944            Ok(json!({
24945                "events": budget.event_count,
24946                "bytes": budget.size_bytes,
24947                "recommended": budget.continue_as_new_recommended,
24948                "pressure": budget.pressure,
24949            }))
24950        });
24951        let task: WorkflowTask = serde_json::from_value(json!({
24952            "task_id": "task-history-budget",
24953            "workflow_type": "rust.history-budget",
24954            "payload_codec": DEFAULT_CODEC,
24955            "history_events": [],
24956            "total_history_events": 480,
24957            "history_size_bytes": 1_048_576,
24958            "continue_as_new_recommended": true,
24959            "history_budget_pressure": "continue_as_new_recommended",
24960        }))
24961        .expect("published workflow task");
24962
24963        let commands = worker
24964            .execute_workflow_task(task)
24965            .expect("history-budget workflow");
24966        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
24967        assert_eq!(result["events"], 480);
24968        assert_eq!(result["bytes"], 1_048_576);
24969        assert_eq!(result["recommended"], true);
24970        assert_eq!(result["pressure"], "continue_as_new_recommended");
24971    }
24972
24973    #[test]
24974    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
24975        let client = Client::new("http://127.0.0.1:8080").expect("client");
24976        let mut worker = Worker::new(client, "rust-workers");
24977        worker.register_workflow("rust.failing", |_ctx, _input| async move {
24978            Err(Error::Codec("rust_conformance_failure".to_string()))
24979        });
24980        let task = WorkflowTask {
24981            task_id: "wft-rust-failing-1".to_string(),
24982            workflow_command_id: None,
24983            workflow_id: Some("wf-rust-failing".to_string()),
24984            run_id: Some("run-rust-failing".to_string()),
24985            workflow_type: "rust.failing".to_string(),
24986            cancel_requested: false,
24987            payload_codec: DEFAULT_CODEC.to_string(),
24988            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24989            history_events: Vec::new(),
24990            total_history_events: Some(0),
24991            history_size_bytes: None,
24992            continue_as_new_recommended: None,
24993            history_budget_pressure: None,
24994            next_history_page_token: None,
24995            workflow_task_attempt: 1,
24996            workflow_signal_id: None,
24997            signal_name: None,
24998            signal_arguments: None,
24999            workflow_update_id: None,
25000            update_name: None,
25001            lease_owner: Some("rust-worker".to_string()),
25002        };
25003
25004        let commands = worker
25005            .execute_workflow_task(task)
25006            .expect("handler failure becomes a workflow command");
25007
25008        assert_eq!(commands.len(), 1);
25009        assert_eq!(commands[0]["type"], "fail_workflow");
25010        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
25011        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
25012        assert_eq!(commands[0]["non_retryable"], false);
25013        assert_eq!(
25014            commands[0]["message"],
25015            "codec error: rust_conformance_failure"
25016        );
25017        assert_eq!(
25018            commands[0]["exception"]["message"],
25019            "codec error: rust_conformance_failure"
25020        );
25021    }
25022
25023    #[test]
25024    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
25025        let client = Client::new("http://127.0.0.1:8080").expect("client");
25026        let mut worker = Worker::new(client, "rust-workers");
25027        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
25028            let _: String = ctx.side_effect(|| "captured".to_string())?;
25029            Err(Error::WorkerLoop("application failure".to_string()))
25030        });
25031
25032        let commands = worker
25033            .execute_workflow_task(workflow_task(
25034                "rust.failing-after-side-effect",
25035                Vec::new(),
25036                DEFAULT_CODEC,
25037            ))
25038            .expect("ordinary failure remains a workflow decision");
25039
25040        assert_eq!(commands.len(), 2);
25041        assert_eq!(commands[0]["type"], "record_side_effect");
25042        assert_eq!(commands[1]["type"], "fail_workflow");
25043    }
25044
25045    #[test]
25046    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
25047        let client = Client::new("http://127.0.0.1:8080").expect("client");
25048        let mut worker = Worker::new(client, "rust-workers");
25049        worker.register_workflow("rust.redrive", |ctx, _input| async move {
25050            ctx.activity("greet", json!([])).await?;
25051            Ok(Value::Null)
25052        });
25053        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
25054            match ctx.activity("greet", json!([])).await {
25055                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
25056                result => result,
25057            }
25058        });
25059
25060        let failed = history_event(
25061            "ActivityFailed",
25062            json!({
25063                "sequence": 1,
25064                "activity_type": "greet",
25065                "activity_execution_id": "activity-1",
25066                "message": "failed"
25067            }),
25068        );
25069        let commands = worker
25070            .execute_workflow_task(workflow_task(
25071                "rust.redrive",
25072                vec![failed.clone()],
25073                DEFAULT_CODEC,
25074            ))
25075            .expect("recorded failure becomes a workflow command");
25076        assert_eq!(commands[0]["type"], "fail_workflow");
25077        assert_eq!(commands[0]["failed_step_sequence"], 1);
25078        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
25079
25080        let translated = worker
25081            .execute_workflow_task(workflow_task(
25082                "rust.redrive-translated",
25083                vec![failed],
25084                DEFAULT_CODEC,
25085            ))
25086            .expect("translated failure becomes a workflow command");
25087        assert_eq!(translated[0]["type"], "fail_workflow");
25088        assert!(translated[0].get("failed_step_sequence").is_none());
25089        assert!(translated[0].get("failed_activity_execution_id").is_none());
25090
25091        let without_identity = worker
25092            .execute_workflow_task(workflow_task(
25093                "rust.redrive",
25094                vec![history_event(
25095                    "ActivityFailed",
25096                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
25097                )],
25098                DEFAULT_CODEC,
25099            ))
25100            .expect("incomplete identity still fails the workflow");
25101        assert!(without_identity[0].get("failed_step_sequence").is_none());
25102
25103        let timed_out = worker
25104            .execute_workflow_task(workflow_task(
25105                "rust.redrive",
25106                vec![history_event(
25107                    "ActivityTimedOut",
25108                    json!({
25109                        "sequence": 1,
25110                        "activity_type": "greet",
25111                        "activity_execution_id": "activity-timeout",
25112                    }),
25113                )],
25114                DEFAULT_CODEC,
25115            ))
25116            .expect("timeout still fails the workflow");
25117        assert!(timed_out[0].get("failed_step_sequence").is_none());
25118    }
25119
25120    #[test]
25121    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
25122        let client = Client::new("http://127.0.0.1:8080").expect("client");
25123        let mut worker = Worker::new(client, "rust-workers");
25124        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
25125            let first = ctx.activity("first", json!([])).await?;
25126            let second = ctx.activity("second", json!([first.clone()])).await?;
25127            Ok(json!({"first": first, "second": second}))
25128        });
25129        let first = history_event(
25130            "ActivityCompleted",
25131            json!({
25132                "sequence": 1,
25133                "activity_type": "first",
25134                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
25135                "payload_codec": DEFAULT_CODEC,
25136                "reused_from_run_id": "failed-run",
25137                "reused_activity_execution_id": "original-first",
25138            }),
25139        );
25140
25141        let retry = worker
25142            .execute_workflow_task(workflow_task(
25143                "rust.redrive-successor",
25144                vec![first.clone()],
25145                DEFAULT_CODEC,
25146            ))
25147            .expect("reused result replays before failed step");
25148        assert_eq!(retry.len(), 1);
25149        assert_eq!(retry[0]["type"], "schedule_activity");
25150        assert_eq!(retry[0]["activity_type"], "second");
25151        assert_eq!(
25152            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
25153            json!(["recorded"]),
25154        );
25155
25156        let second = history_event(
25157            "ActivityCompleted",
25158            json!({
25159                "sequence": 2,
25160                "activity_type": "second",
25161                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
25162                "payload_codec": DEFAULT_CODEC,
25163            }),
25164        );
25165        let completed = worker
25166            .execute_workflow_task(workflow_task(
25167                "rust.redrive-successor",
25168                vec![first, second],
25169                DEFAULT_CODEC,
25170            ))
25171            .expect("retried step completes the successor");
25172        assert_eq!(completed.len(), 1);
25173        assert_eq!(completed[0]["type"], "complete_workflow");
25174        assert_eq!(
25175            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
25176            json!({"first": "recorded", "second": "retried"}),
25177        );
25178    }
25179
25180    #[test]
25181    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
25182        let client = Client::new("http://127.0.0.1:8080").expect("client");
25183        let mut worker = Worker::new(client, "rust-workers");
25184        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
25185            Err(Error::WorkerLoop("application failure".to_string()))
25186        });
25187        let result =
25188            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
25189
25190        let error = worker
25191            .execute_workflow_task(workflow_task(
25192                "rust.removed-side-effect",
25193                vec![history_event(
25194                    "SideEffectRecorded",
25195                    json!({"sequence": 1, "result": result}),
25196                )],
25197                DEFAULT_CODEC,
25198            ))
25199            .expect_err("removed committed history must not become fail_workflow");
25200
25201        let Error::NonDeterministicReplay(failure) = error else {
25202            panic!("expected typed replay failure");
25203        };
25204        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25205        assert_eq!(failure.sequence, Some(1));
25206        assert_eq!(failure.expected.as_deref(), Some("side effect"));
25207    }
25208
25209    #[test]
25210    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
25211        let client = Client::new("http://127.0.0.1:8080").expect("client");
25212        let mut worker = Worker::new(client, "rust-workers");
25213        worker.register_workflow(
25214            "rust.side-effect-before-marker-error",
25215            |ctx, _input| async move {
25216                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
25217                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
25218                ctx.get_version("restart-safe", 2, 2)?;
25219                Ok(Value::Null)
25220            },
25221        );
25222
25223        let error = worker
25224            .execute_workflow_task(workflow_task(
25225                "rust.side-effect-before-marker-error",
25226                vec![history_event(
25227                    "VersionMarkerRecorded",
25228                    json!({
25229                        "sequence": 1,
25230                        "change_id": "restart-safe",
25231                        "version": 1,
25232                        "min_supported": 1,
25233                        "max_supported": 1,
25234                    }),
25235                )],
25236                DEFAULT_CODEC,
25237            ))
25238            .expect_err("replay error must return no queued workflow commands");
25239
25240        let Error::NonDeterministicReplay(failure) = error else {
25241            panic!("expected typed replay failure");
25242        };
25243        assert_eq!(failure.reason, "version_marker_incompatible_range");
25244        assert_eq!(failure.sequence, Some(1));
25245    }
25246
25247    #[test]
25248    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
25249        let client = Client::new("http://127.0.0.1:8080").expect("client");
25250        let mut worker = Worker::new(client, "rust-workers");
25251        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
25252            ctx.sleep(Duration::from_secs(5)).await?;
25253            Ok(json!({"status": "timer fired"}))
25254        });
25255
25256        let task = WorkflowTask {
25257            task_id: "wft-rust-timer-pending".to_string(),
25258            workflow_command_id: None,
25259            workflow_id: Some("wf-rust-timer".to_string()),
25260            run_id: Some("run-rust-timer".to_string()),
25261            workflow_type: "rust.timer.pending".to_string(),
25262            cancel_requested: false,
25263            payload_codec: DEFAULT_CODEC.to_string(),
25264            arguments: Some(
25265                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25266            ),
25267            history_events: vec![history_event(
25268                "TimerScheduled",
25269                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25270            )],
25271            total_history_events: Some(1),
25272            history_size_bytes: None,
25273            continue_as_new_recommended: None,
25274            history_budget_pressure: None,
25275            next_history_page_token: None,
25276            workflow_task_attempt: 1,
25277            workflow_signal_id: None,
25278            signal_name: None,
25279            signal_arguments: None,
25280            workflow_update_id: None,
25281            update_name: None,
25282            lease_owner: Some("rust-worker".to_string()),
25283        };
25284
25285        for _redelivery_or_restart in 0..2 {
25286            let commands = worker
25287                .execute_workflow_task(task.clone())
25288                .expect("recorded timer remains pending");
25289            assert!(
25290                commands.is_empty(),
25291                "recorded timer must not be rescheduled"
25292            );
25293        }
25294    }
25295
25296    #[test]
25297    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
25298        let client = Client::new("http://127.0.0.1:8080").expect("client");
25299        let mut worker = Worker::new(client, "rust-workers");
25300        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
25301            Ok(json!({"status": "completed"}))
25302        });
25303        let task = WorkflowTask {
25304            task_id: "wft-rust-timer-removed".to_string(),
25305            workflow_command_id: None,
25306            workflow_id: Some("wf-rust-timer".to_string()),
25307            run_id: Some("run-rust-timer".to_string()),
25308            workflow_type: "rust.timer.removed".to_string(),
25309            cancel_requested: false,
25310            payload_codec: DEFAULT_CODEC.to_string(),
25311            arguments: Some(
25312                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25313            ),
25314            history_events: vec![
25315                history_event(
25316                    "TimerScheduled",
25317                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25318                ),
25319                history_event(
25320                    "TimerFired",
25321                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25322                ),
25323            ],
25324            total_history_events: Some(2),
25325            history_size_bytes: None,
25326            continue_as_new_recommended: None,
25327            history_budget_pressure: None,
25328            next_history_page_token: None,
25329            workflow_task_attempt: 1,
25330            workflow_signal_id: None,
25331            signal_name: None,
25332            signal_arguments: None,
25333            workflow_update_id: None,
25334            update_name: None,
25335            lease_owner: Some("rust-worker".to_string()),
25336        };
25337
25338        let Error::NonDeterministicReplay(failure) = worker
25339            .execute_workflow_task(task)
25340            .expect_err("removed timer must fail replay")
25341        else {
25342            panic!("expected typed replay failure");
25343        };
25344        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25345        assert_eq!(failure.sequence, Some(1));
25346    }
25347
25348    #[test]
25349    fn workflow_context_emits_explicit_child_workflow_contract() {
25350        let ctx = WorkflowContext {
25351            cancellation_scope_id: "root".into(),
25352            state: Arc::new(Mutex::new(
25353                WorkflowState::new_with_identity(
25354                    Vec::new(),
25355                    Some("wf-parent".to_string()),
25356                    Some("run-parent".to_string()),
25357                    "parent-workers".to_string(),
25358                    DEFAULT_CODEC.to_string(),
25359                    None,
25360                )
25361                .expect("workflow state"),
25362            )),
25363        };
25364        let options = ChildWorkflowOptions::new("python-workers")
25365            .parent_close_policy(ParentClosePolicy::RequestCancel)
25366            .retry_policy(ChildWorkflowRetryPolicy {
25367                max_attempts: Some(3),
25368                backoff_seconds: vec![1, 5],
25369                non_retryable_error_types: vec!["ValidationError".to_string()],
25370            })
25371            .execution_timeout_seconds(600)
25372            .run_timeout_seconds(120);
25373        let mut call = Box::pin(ctx.start_child_workflow(
25374            "python.fulfil-order",
25375            options,
25376            json!([{"order_id": "order-42"}]),
25377        ));
25378        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25379
25380        assert!(matches!(
25381            call.as_mut().poll(&mut task_context),
25382            Poll::Pending
25383        ));
25384        let commands = ctx.take_commands().expect("commands");
25385        assert_eq!(commands.len(), 1);
25386        let command = &commands[0];
25387        assert_eq!(command["type"], "start_child_workflow");
25388        assert_eq!(command["workflow_type"], "python.fulfil-order");
25389        assert_eq!(command["queue"], "python-workers");
25390        assert_eq!(command["parent_close_policy"], "request_cancel");
25391        assert_eq!(command["retry_policy"]["max_attempts"], 3);
25392        assert_eq!(command["execution_timeout_seconds"], 600);
25393        assert_eq!(command["run_timeout_seconds"], 120);
25394        assert_eq!(
25395            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
25396            json!([{"order_id": "order-42"}])
25397        );
25398    }
25399
25400    fn child_parent_worker() -> Worker {
25401        let client = Client::new("http://127.0.0.1:8080").expect("client");
25402        let mut worker = Worker::new(client, "rust-parent-workers");
25403        worker.register_workflow("rust.parent", |ctx, _input| async move {
25404            let child = ctx
25405                .start_child_workflow(
25406                    "python.child",
25407                    ChildWorkflowOptions::new("python-child-workers")
25408                        .parent_close_policy(ParentClosePolicy::Terminate),
25409                    json!([{"codec_probe": [1, true, "rust"]}]),
25410                )
25411                .await?;
25412            Ok(json!({
25413                "parent_workflow_id": child.parent.workflow_id,
25414                "parent_run_id": child.parent.run_id,
25415                "child_workflow_id": child.child.workflow_id,
25416                "child_run_id": child.child.run_id,
25417                "child_workflow_type": child.child_workflow_type,
25418                "result": child.result,
25419            }))
25420        });
25421        worker
25422    }
25423
25424    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
25425        WorkflowTask {
25426            task_id: "wft-child-parent".to_string(),
25427            workflow_command_id: None,
25428            workflow_id: Some("wf-parent".to_string()),
25429            run_id: Some("run-parent".to_string()),
25430            workflow_type: "rust.parent".to_string(),
25431            cancel_requested: false,
25432            payload_codec: DEFAULT_CODEC.to_string(),
25433            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25434            history_events: vec![
25435                HistoryEvent {
25436                    event_type: "ChildWorkflowScheduled".to_string(),
25437                    payload: json!({
25438                        "sequence": 1,
25439                        "child_call_id": "call-child",
25440                        "child_workflow_instance_id": "wf-child",
25441                        "child_workflow_run_id": "run-child",
25442                        "child_workflow_type": "python.child",
25443                        "parent_close_policy": "terminate",
25444                    }),
25445                    raw: HashMap::new(),
25446                },
25447                HistoryEvent {
25448                    event_type: event_type.to_string(),
25449                    payload,
25450                    raw: HashMap::new(),
25451                },
25452            ],
25453            total_history_events: Some(2),
25454            history_size_bytes: None,
25455            continue_as_new_recommended: None,
25456            history_budget_pressure: None,
25457            next_history_page_token: None,
25458            workflow_task_attempt: 1,
25459            workflow_signal_id: None,
25460            signal_name: None,
25461            signal_arguments: None,
25462            workflow_update_id: None,
25463            update_name: None,
25464            lease_owner: Some("rust-worker".to_string()),
25465        }
25466    }
25467
25468    #[test]
25469    fn committed_child_result_replays_without_starting_a_duplicate() {
25470        let worker = child_parent_worker();
25471        let task = child_parent_task(
25472            "ChildRunCompleted",
25473            json!({
25474                "sequence": 1,
25475                "child_call_id": "call-child",
25476                "child_workflow_instance_id": "wf-child",
25477                "child_workflow_run_id": "run-child",
25478                "child_workflow_type": "python.child",
25479                "payload_codec": DEFAULT_CODEC,
25480                "result": fixture_envelope(json!({"from":"python","ok":true})),
25481            }),
25482        );
25483
25484        for _restart in 0..2 {
25485            let commands = worker
25486                .execute_workflow_task(task.clone())
25487                .expect("replayed parent task");
25488            assert_eq!(commands.len(), 1);
25489            assert_eq!(commands[0]["type"], "complete_workflow");
25490            assert!(!commands
25491                .iter()
25492                .any(|command| command["type"] == "start_child_workflow"));
25493            let output =
25494                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25495            assert_eq!(output["parent_workflow_id"], "wf-parent");
25496            assert_eq!(output["parent_run_id"], "run-parent");
25497            assert_eq!(output["child_workflow_id"], "wf-child");
25498            assert_eq!(output["child_run_id"], "run-child");
25499            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
25500        }
25501    }
25502
25503    #[test]
25504    fn typed_child_arguments_and_results_survive_replay() {
25505        let client = Client::new("http://127.0.0.1:8080").expect("client");
25506        let mut worker = Worker::new(client, "rust-parent-workers");
25507        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
25508            let child = ctx
25509                .start_child_workflow_avro_value(
25510                    "python.typed-child",
25511                    ChildWorkflowOptions::new("python-workers"),
25512                    AvroValue::Array(vec![typed_fidelity_probe()]),
25513                )
25514                .await?;
25515            Ok(child.result)
25516        });
25517
25518        let initial = worker
25519            .execute_workflow_task(workflow_task(
25520                "rust.typed-parent",
25521                Vec::new(),
25522                DEFAULT_CODEC,
25523            ))
25524            .expect("typed child start");
25525        assert_eq!(initial[0]["type"], "start_child_workflow");
25526        assert_eq!(
25527            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
25528                .expect("typed child arguments"),
25529            AvroValue::Array(vec![typed_fidelity_probe()])
25530        );
25531
25532        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
25533            .expect("typed child result");
25534        let task = workflow_task(
25535            "rust.typed-parent",
25536            vec![
25537                history_event(
25538                    "ChildWorkflowScheduled",
25539                    json!({
25540                        "sequence": 1,
25541                        "child_call_id": "call-typed",
25542                        "child_workflow_instance_id": "wf-child",
25543                        "child_workflow_run_id": "run-child",
25544                        "child_workflow_type": "python.typed-child",
25545                    }),
25546                ),
25547                history_event(
25548                    "ChildRunCompleted",
25549                    json!({
25550                        "sequence": 1,
25551                        "child_call_id": "call-typed",
25552                        "child_workflow_instance_id": "wf-child",
25553                        "child_workflow_run_id": "run-child",
25554                        "child_workflow_type": "python.typed-child",
25555                        "payload_codec": DEFAULT_CODEC,
25556                        "result": result,
25557                    }),
25558                ),
25559            ],
25560            DEFAULT_CODEC,
25561        );
25562
25563        let commands = worker
25564            .execute_workflow_task(task)
25565            .expect("typed child replay");
25566        assert_eq!(commands[0]["type"], "complete_workflow");
25567        assert_eq!(
25568            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
25569                .expect("typed parent result"),
25570            typed_fidelity_probe()
25571        );
25572    }
25573
25574    #[test]
25575    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
25576        let worker = child_parent_worker();
25577        let mut task = child_parent_task("unused", Value::Null);
25578        task.history_events.truncate(1);
25579        task.total_history_events = Some(1);
25580
25581        for _redelivery_or_restart in 0..2 {
25582            let commands = worker
25583                .execute_workflow_task(task.clone())
25584                .expect("recorded child remains pending");
25585            assert!(
25586                commands.is_empty(),
25587                "recorded pending child must not be started again"
25588            );
25589        }
25590    }
25591
25592    #[test]
25593    fn child_cancellation_becomes_stable_parent_failure_command() {
25594        let worker = child_parent_worker();
25595        let task = child_parent_task(
25596            "ChildRunCancelled",
25597            json!({
25598                "sequence": 1,
25599                "child_workflow_instance_id": "wf-child",
25600                "child_workflow_run_id": "run-child",
25601                "child_workflow_type": "python.child",
25602                "failure_id": "failure-child",
25603                "failure_category": "cancelled",
25604                "message": "cancelled by parent-close policy",
25605            }),
25606        );
25607
25608        let commands = worker
25609            .execute_workflow_task(task)
25610            .expect("parent settlement");
25611        assert_eq!(commands.len(), 1);
25612        assert_eq!(commands[0]["type"], "fail_workflow");
25613        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
25614        assert_eq!(
25615            commands[0]["exception"]["properties"]["reason"],
25616            "cancelled"
25617        );
25618        assert_eq!(
25619            commands[0]["exception"]["properties"]["child_workflow_run_id"],
25620            "run-child"
25621        );
25622    }
25623
25624    #[test]
25625    fn workflow_can_handle_typed_child_failure() {
25626        let client = Client::new("http://127.0.0.1:8080").expect("client");
25627        let mut worker = Worker::new(client, "rust-parent-workers");
25628        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
25629            match ctx
25630                .start_child_workflow(
25631                    "python.child",
25632                    ChildWorkflowOptions::new("python-child-workers"),
25633                    json!([]),
25634                )
25635                .await
25636            {
25637                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
25638                    "reason": failure.reason,
25639                    "failure_id": failure.failure_id,
25640                    "exception_class": failure.exception_class,
25641                    "child_run_id": failure.child_workflow_run_id,
25642                })),
25643                Err(error) => Err(error),
25644                Ok(_) => Err(Error::WorkerLoop(
25645                    "child unexpectedly succeeded".to_string(),
25646                )),
25647            }
25648        });
25649        let mut task = child_parent_task(
25650            "ChildRunFailed",
25651            json!({
25652                "sequence": 1,
25653                "child_workflow_instance_id": "wf-child",
25654                "child_workflow_run_id": "run-child",
25655                "child_workflow_type": "python.child",
25656                "failure_id": "failure-child",
25657                "failure_category": "child_workflow",
25658                "message": "payment rejected",
25659                "exception": {
25660                    "type": "PaymentRejected",
25661                    "class": "payments.PaymentRejected",
25662                    "message": "payment rejected"
25663                }
25664            }),
25665        );
25666        task.workflow_type = "rust.handled-parent".to_string();
25667        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
25668
25669        let commands = worker.execute_workflow_task(task).expect("handled failure");
25670        assert_eq!(commands[0]["type"], "complete_workflow");
25671        let output =
25672            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25673        assert_eq!(output["reason"], "child_workflow");
25674        assert_eq!(output["failure_id"], "failure-child");
25675        assert_eq!(output["exception_class"], "payments.PaymentRejected");
25676        assert_eq!(output["child_run_id"], "run-child");
25677    }
25678
25679    #[test]
25680    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
25681        let client = Client::new("http://127.0.0.1:8080").expect("client");
25682        let mut worker = Worker::new(client, "rust-workers");
25683
25684        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
25685            let signal = ctx.wait_signal("start").await?;
25686            let name = signal
25687                .first()
25688                .and_then(|value| value.as_str())
25689                .unwrap_or("world");
25690            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
25691            Ok(json!({
25692                "greeting": greeting,
25693                "language": "rust"
25694            }))
25695        });
25696
25697        let signal_arguments =
25698            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
25699        let task = WorkflowTask {
25700            task_id: "wft-rust-signal-1".to_string(),
25701            workflow_command_id: None,
25702            workflow_id: Some("wf-rust-hello".to_string()),
25703            run_id: Some("run-rust-hello".to_string()),
25704            workflow_type: "rust.hello_workflow".to_string(),
25705            cancel_requested: false,
25706            payload_codec: DEFAULT_CODEC.to_string(),
25707            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25708            history_events: vec![HistoryEvent {
25709                event_type: "SignalReceived".to_string(),
25710                payload: json!({
25711                    "signal_id": "sig-rust-1",
25712                    "signal_name": "start"
25713                }),
25714                raw: HashMap::new(),
25715            }],
25716            total_history_events: Some(1),
25717            history_size_bytes: None,
25718            continue_as_new_recommended: None,
25719            history_budget_pressure: None,
25720            next_history_page_token: None,
25721            workflow_task_attempt: 1,
25722            workflow_signal_id: Some("sig-rust-1".to_string()),
25723            signal_name: Some("start".to_string()),
25724            signal_arguments: Some(signal_arguments),
25725            workflow_update_id: None,
25726            update_name: None,
25727            lease_owner: Some("rust-worker".to_string()),
25728        };
25729
25730        let commands = worker.execute_workflow_task(task).expect("workflow task");
25731
25732        assert_eq!(commands.len(), 1);
25733        assert_eq!(commands[0]["type"], "schedule_activity");
25734        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
25735        assert_eq!(
25736            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
25737            json!(["Rust"])
25738        );
25739    }
25740
25741    #[test]
25742    fn workflow_task_appends_paginated_history_events() {
25743        let mut task = WorkflowTask {
25744            task_id: "wft-rust-pages-1".to_string(),
25745            workflow_command_id: None,
25746            workflow_id: Some("wf-rust-pages".to_string()),
25747            run_id: Some("run-rust-pages".to_string()),
25748            workflow_type: "rust.hello_workflow".to_string(),
25749            cancel_requested: false,
25750            payload_codec: DEFAULT_CODEC.to_string(),
25751            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25752            history_events: vec![HistoryEvent {
25753                event_type: "WorkflowStarted".to_string(),
25754                payload: json!({}),
25755                raw: HashMap::new(),
25756            }],
25757            total_history_events: Some(3),
25758            history_size_bytes: None,
25759            continue_as_new_recommended: None,
25760            history_budget_pressure: None,
25761            next_history_page_token: Some("MQ==".to_string()),
25762            workflow_task_attempt: 1,
25763            workflow_signal_id: None,
25764            signal_name: None,
25765            signal_arguments: None,
25766            workflow_update_id: None,
25767            update_name: None,
25768            lease_owner: Some("rust-worker".to_string()),
25769        };
25770
25771        task.append_history_page(WorkflowTaskHistoryPage {
25772            history_events: vec![
25773                HistoryEvent {
25774                    event_type: "SignalReceived".to_string(),
25775                    payload: json!({
25776                        "signal_id": "sig-rust-1",
25777                        "signal_name": "start",
25778                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
25779                            .expect("signal arguments")
25780                    }),
25781                    raw: HashMap::new(),
25782                },
25783                HistoryEvent {
25784                    event_type: "MarkerRecorded".to_string(),
25785                    payload: json!({"sequence": 3}),
25786                    raw: HashMap::new(),
25787                },
25788            ],
25789            total_history_events: Some(3),
25790            next_history_page_token: None,
25791        });
25792
25793        assert_eq!(task.history_events.len(), 3);
25794        assert_eq!(task.total_history_events, Some(3));
25795        assert_eq!(task.next_history_page_token, None);
25796
25797        let signal = task
25798            .history_events
25799            .iter()
25800            .find(|event| event.event_type == "SignalReceived")
25801            .expect("signal event");
25802        assert_eq!(
25803            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
25804            vec![AvroValue::String("Rust".to_string())]
25805        );
25806    }
25807
25808    #[tokio::test]
25809    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
25810        let client = Client::new("http://127.0.0.1:8080").expect("client");
25811        let mut worker = Worker::new(client, "rust-workers");
25812        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25813        worker.register_query("counter", "current", |ctx, _args| async move {
25814            let mut count = 0_i64;
25815            for signal in ctx.signal_events() {
25816                let value = signal
25817                    .arguments
25818                    .first()
25819                    .and_then(Value::as_i64)
25820                    .unwrap_or_default();
25821                match signal.name.as_str() {
25822                    "increment" => count += value,
25823                    "set" => count = value,
25824                    _ => {}
25825                }
25826            }
25827            Ok(json!(count))
25828        });
25829
25830        let task = QueryTask {
25831            query_task_id: "query-rust-counter".to_string(),
25832            query_task_attempt: 1,
25833            lease_owner: Some("rust-worker".to_string()),
25834            workflow_id: Some("counter-1".to_string()),
25835            run_id: Some("run-counter-1".to_string()),
25836            workflow_type: "counter".to_string(),
25837            query_name: "current".to_string(),
25838            payload_codec: DEFAULT_CODEC.to_string(),
25839            workflow_arguments: Some(
25840                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25841            ),
25842            query_arguments: Some(
25843                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
25844            ),
25845            history_events: vec![
25846                HistoryEvent {
25847                    event_type: "SignalReceived".to_string(),
25848                    payload: json!({
25849                        "signal_id": "php-signal-1",
25850                        "signal_name": "increment",
25851                        "workflow_sequence": 1,
25852                        "payload_codec": DEFAULT_CODEC,
25853                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
25854                    }),
25855                    raw: HashMap::new(),
25856                },
25857                HistoryEvent {
25858                    event_type: "SignalReceived".to_string(),
25859                    payload: json!({
25860                        "signal_id": "python-signal-2",
25861                        "signal_name": "increment",
25862                        "workflow_sequence": 2,
25863                        "payload_codec": DEFAULT_CODEC,
25864                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
25865                    }),
25866                    raw: HashMap::new(),
25867                },
25868                HistoryEvent {
25869                    event_type: "SignalReceived".to_string(),
25870                    payload: json!({
25871                        "signal_id": "rust-signal-3",
25872                        "signal_name": "set",
25873                        "workflow_sequence": 3,
25874                        "payload_codec": DEFAULT_CODEC,
25875                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
25876                    }),
25877                    raw: HashMap::new(),
25878                },
25879            ],
25880            history_export: None,
25881            run_status: Some("completed".to_string()),
25882        };
25883
25884        let result = worker.execute_query_task(task).await.expect("query result");
25885        assert_eq!(result.into_json().expect("query projection"), json!(0));
25886    }
25887
25888    #[tokio::test]
25889    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
25890        let worker = replay_counter_worker();
25891        let running_history = json!([
25892            {
25893                "type": "ActivityCompleted",
25894                "payload": {
25895                    "sequence": 1,
25896                    "activity_type": "load-counter",
25897                    "payload_codec": DEFAULT_CODEC,
25898                    "result": fixture_envelope(json!("loaded"))
25899                }
25900            },
25901            {
25902                "type": "SignalWaitOpened",
25903                "payload": {
25904                    "sequence": 3,
25905                    "signal_name": "increment"
25906                }
25907            },
25908            {
25909                "type": "SignalReceived",
25910                "payload": {
25911                    "signal_id": "signal-3",
25912                    "signal_name": "increment",
25913                    "workflow_sequence": 2,
25914                    "payload_codec": DEFAULT_CODEC,
25915                    "arguments": fixture_envelope(json!([3]))
25916                }
25917            },
25918            {
25919                "type": "SignalApplied",
25920                "payload": {
25921                    "sequence": 3,
25922                    "signal_id": "signal-3",
25923                    "signal_name": "increment",
25924                    "payload_codec": DEFAULT_CODEC,
25925                    "value": fixture_envelope(json!([3]))
25926                }
25927            }
25928        ]);
25929
25930        let running = worker
25931            .execute_query_task(replay_counter_query(
25932                "current",
25933                running_history.clone(),
25934                "running",
25935            ))
25936            .await
25937            .expect("running replay query");
25938        assert_eq!(
25939            running.clone().into_json().expect("query projection"),
25940            json!({"loaded": "loaded", "count": 3, "finished": false})
25941        );
25942
25943        let detached = worker
25944            .execute_query_task(replay_counter_query(
25945                "detached-mutation",
25946                running_history.clone(),
25947                "running",
25948            ))
25949            .await
25950            .expect("query mutates only its detached state clone");
25951        assert_eq!(detached.into_json().expect("query projection"), json!(999));
25952        let failed = worker
25953            .execute_query_task(replay_counter_query(
25954                "failed-mutation",
25955                running_history.clone(),
25956                "running",
25957            ))
25958            .await
25959            .expect_err("failed query");
25960        assert_eq!(failed.reason, "query_rejected");
25961        let unchanged = worker
25962            .execute_query_task(replay_counter_query("current", running_history, "running"))
25963            .await
25964            .expect("later query reconstructs unchanged state");
25965        assert_eq!(unchanged, running);
25966
25967        let restarted_worker = replay_counter_worker();
25968        let empty_arguments = fixture_envelope(json!([]));
25969        let loaded_result = fixture_envelope(json!("loaded"));
25970        let signal_three = fixture_blob(json!([3]));
25971        let signal_five = fixture_blob(json!([5]));
25972        let restarted_task: QueryTask = serde_json::from_value(json!({
25973            "query_task_id": "query-after-restart",
25974            "workflow_id": "counter-1",
25975            "run_id": "run-counter-1",
25976            "workflow_type": "replay-counter",
25977            "query_name": "current",
25978            "payload_codec": DEFAULT_CODEC,
25979            "workflow_arguments": empty_arguments.clone(),
25980            "query_arguments": empty_arguments,
25981            "history_events": [],
25982            "history_export": {
25983                "payloads": {"codec": DEFAULT_CODEC},
25984                "history_events": [
25985                    {
25986                        "type": "ActivityCompleted",
25987                        "payload": {
25988                            "sequence": 1,
25989                            "activity_type": "load-counter",
25990                            "payload_codec": DEFAULT_CODEC,
25991                            "result": null
25992                        }
25993                    },
25994                    {
25995                        "type": "SignalWaitOpened",
25996                        "payload": {
25997                            "sequence": 3,
25998                            "signal_name": "increment"
25999                        }
26000                    },
26001                    {
26002                        "type": "SignalReceived",
26003                        "payload": {
26004                            "signal_id": "signal-3",
26005                            "signal_name": "increment",
26006                            "workflow_sequence": 2
26007                        }
26008                    },
26009                    {
26010                        "type": "SignalApplied",
26011                        "payload": {
26012                            "sequence": 3,
26013                            "signal_id": "signal-3",
26014                            "signal_name": "increment"
26015                        }
26016                    },
26017                    {
26018                        "type": "SignalWaitOpened",
26019                        "payload": {
26020                            "sequence": 5,
26021                            "signal_name": "increment"
26022                        }
26023                    },
26024                    {
26025                        "type": "SignalReceived",
26026                        "payload": {
26027                            "signal_id": "signal-5",
26028                            "signal_name": "increment",
26029                            "workflow_sequence": 4
26030                        }
26031                    },
26032                    {
26033                        "type": "SignalApplied",
26034                        "payload": {
26035                            "sequence": 5,
26036                            "signal_id": "signal-5",
26037                            "signal_name": "increment"
26038                        }
26039                    }
26040                ],
26041                "activities": [{
26042                    "sequence": 1,
26043                    "activity_type": "load-counter",
26044                    "payload_codec": DEFAULT_CODEC,
26045                    "result": loaded_result
26046                }],
26047                "signals": [
26048                    {
26049                        "id": "signal-3",
26050                        "name": "increment",
26051                        "workflow_sequence": 2,
26052                        "payload_codec": DEFAULT_CODEC,
26053                        "arguments": signal_three
26054                    },
26055                    {
26056                        "id": "signal-5",
26057                        "name": "increment",
26058                        "workflow_sequence": 4,
26059                        "payload_codec": DEFAULT_CODEC,
26060                        "arguments": signal_five
26061                    }
26062                ]
26063            },
26064            "run_status": "completed"
26065        }))
26066        .expect("cold replay query task");
26067        let completed = restarted_worker
26068            .execute_query_task(restarted_task)
26069            .await
26070            .expect("completed cold replay query");
26071        assert_eq!(
26072            completed.into_json().expect("query projection"),
26073            json!({"loaded": "loaded", "count": 8, "finished": true})
26074        );
26075    }
26076
26077    #[tokio::test]
26078    async fn replayed_query_replay_failures_are_machine_readable() {
26079        let worker = replay_counter_worker();
26080        let task = replay_counter_query(
26081            "current",
26082            json!([{
26083                "type": "ActivityCompleted",
26084                "payload": {
26085                    "sequence": 1,
26086                    "payload_codec": DEFAULT_CODEC,
26087                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
26088                }
26089            }]),
26090            "running",
26091        );
26092        let failure = worker
26093            .execute_query_task(task)
26094            .await
26095            .expect_err("invalid replay history payload");
26096        assert_eq!(failure.reason, "query_payload_decode_failed");
26097        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
26098        assert!(failure.message.contains("invalid_payload_framing"));
26099    }
26100
26101    #[tokio::test]
26102    async fn query_task_restores_compact_history_from_export() {
26103        let client = Client::new("http://127.0.0.1:8080").expect("client");
26104        let mut worker = Worker::new(client, "rust-workers");
26105        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26106        worker.register_query("counter", "current", |ctx, _args| async move {
26107            Ok(json!(ctx.signals("increment")[0][0]))
26108        });
26109        let empty_arguments = fixture_envelope(json!([]));
26110        let exported_signal = fixture_blob(json!([9]));
26111        let task: QueryTask = serde_json::from_value(json!({
26112            "query_task_id": "query-export",
26113            "workflow_type": "counter",
26114            "query_name": "current",
26115            "payload_codec": DEFAULT_CODEC,
26116            "workflow_arguments": empty_arguments.clone(),
26117            "query_arguments": empty_arguments,
26118            "history_events": [],
26119            "history_export": {
26120                "payloads": {"codec": DEFAULT_CODEC},
26121                "history_events": [{
26122                    "type": "SignalReceived",
26123                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
26124                }],
26125                "signals": [{
26126                    "id": "signal-export",
26127                    "name": "increment",
26128                    "status": "applied",
26129                    "workflow_sequence": 1,
26130                    "payload_codec": DEFAULT_CODEC,
26131                    "arguments": exported_signal
26132                }]
26133            }
26134        }))
26135        .expect("query task");
26136
26137        let result = worker.execute_query_task(task).await.expect("query result");
26138        assert_eq!(result.into_json().expect("query projection"), json!(9));
26139    }
26140
26141    #[tokio::test]
26142    async fn query_task_failures_have_stable_reasons() {
26143        let client = Client::new("http://127.0.0.1:8080").expect("client");
26144        let mut worker = Worker::new(client, "rust-workers");
26145        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26146        worker.register_query(
26147            "counter",
26148            "current",
26149            |_ctx, _args| async move { Ok(json!(0)) },
26150        );
26151
26152        let base_task = QueryTask {
26153            query_task_id: "query-errors".to_string(),
26154            query_task_attempt: 1,
26155            lease_owner: None,
26156            workflow_id: Some("counter-errors".to_string()),
26157            run_id: Some("run-errors".to_string()),
26158            workflow_type: "counter".to_string(),
26159            query_name: "missing".to_string(),
26160            payload_codec: DEFAULT_CODEC.to_string(),
26161            workflow_arguments: Some(fixture_envelope(json!([]))),
26162            query_arguments: Some(fixture_envelope(json!([]))),
26163            history_events: Vec::new(),
26164            history_export: None,
26165            run_status: Some("running".to_string()),
26166        };
26167
26168        let unknown = worker
26169            .execute_query_task(base_task.clone())
26170            .await
26171            .expect_err("unknown query");
26172        assert_eq!(unknown.reason, "rejected_unknown_query");
26173
26174        let mut malformed = base_task;
26175        malformed.query_name = "current".to_string();
26176        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
26177        let malformed = worker
26178            .execute_query_task(malformed)
26179            .await
26180            .expect_err("malformed payload");
26181        assert_eq!(malformed.reason, "query_payload_decode_failed");
26182
26183        let client = Client::new("http://127.0.0.1:8080").expect("client");
26184        let mut unavailable_worker = Worker::new(client, "rust-workers");
26185        unavailable_worker
26186            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26187        let empty_arguments = fixture_envelope(json!([]));
26188        let unavailable_task: QueryTask = serde_json::from_value(json!({
26189            "query_task_id": "query-unavailable",
26190            "workflow_type": "counter",
26191            "query_name": "current",
26192            "payload_codec": DEFAULT_CODEC,
26193            "workflow_arguments": empty_arguments.clone(),
26194            "query_arguments": empty_arguments
26195        }))
26196        .expect("query task");
26197        let unavailable = unavailable_worker
26198            .execute_query_task(unavailable_task)
26199            .await
26200            .expect_err("query handler unavailable");
26201        assert_eq!(unavailable.reason, "query_handler_unavailable");
26202    }
26203
26204    #[tokio::test]
26205    async fn client_query_decodes_result_and_typed_failure() {
26206        let server = MockWorkerServer::start();
26207        let client = Client::builder(server.base_url())
26208            .timeout(Duration::from_secs(2))
26209            .build()
26210            .expect("client");
26211
26212        let result = client
26213            .query_workflow("counter-1", "current", json!([]))
26214            .await
26215            .expect("query result");
26216        assert_eq!(result, json!({"count": 8}));
26217
26218        let error = client
26219            .query_workflow("counter-1", "missing", json!([]))
26220            .await
26221            .expect_err("unknown query");
26222        let Error::QueryFailed(failure) = error else {
26223            panic!("expected typed query failure");
26224        };
26225        assert_eq!(failure.status, 404);
26226        assert_eq!(failure.reason, "rejected_unknown_query");
26227    }
26228
26229    #[tokio::test]
26230    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
26231        let server = MockWorkerServer::start();
26232        let client = Client::builder(server.base_url())
26233            .timeout(Duration::from_secs(2))
26234            .build()
26235            .expect("client");
26236        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
26237
26238        client
26239            .start_workflow(
26240                "typed.echo",
26241                "rust-workers",
26242                "typed-start",
26243                arguments.clone(),
26244            )
26245            .await
26246            .expect("typed workflow start");
26247        assert_eq!(
26248            decode_wire_avro_value(
26249                &server.request_body("/api/workflows")["input"],
26250                DEFAULT_CODEC,
26251            )
26252            .expect("typed start input"),
26253            arguments
26254        );
26255
26256        client
26257            .signal_workflow("typed-1", "changed", arguments.clone())
26258            .await
26259            .expect("typed signal");
26260        assert_eq!(
26261            decode_wire_avro_value(
26262                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
26263                DEFAULT_CODEC,
26264            )
26265            .expect("typed signal input"),
26266            arguments
26267        );
26268
26269        assert_eq!(
26270            client
26271                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
26272                .await
26273                .expect("typed query"),
26274            typed_fidelity_probe()
26275        );
26276        assert_eq!(
26277            decode_wire_avro_value(
26278                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
26279                DEFAULT_CODEC,
26280            )
26281            .expect("typed query input"),
26282            arguments
26283        );
26284
26285        assert_eq!(
26286            client
26287                .update_workflow_avro_value(
26288                    "typed-1",
26289                    "replace",
26290                    arguments.clone(),
26291                    Some("typed-request"),
26292                )
26293                .await
26294                .expect("typed update"),
26295            typed_fidelity_probe()
26296        );
26297        let update = server.request_body("/api/workflows/typed-1/update/replace");
26298        assert_eq!(update["request_id"], "typed-request");
26299        assert_eq!(
26300            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
26301            arguments
26302        );
26303
26304        let handle = WorkflowHandle {
26305            client: client.clone(),
26306            workflow_id: "typed-1".to_string(),
26307            run_id: Some("run-typed-1".to_string()),
26308            workflow_type: "typed.echo".to_string(),
26309        };
26310        assert_eq!(
26311            handle
26312                .result_avro_value(WorkflowResultOptions::default())
26313                .await
26314                .expect("typed workflow result"),
26315            typed_fidelity_probe()
26316        );
26317
26318        client
26319            .complete_activity_task(
26320                "activity-typed",
26321                "attempt-typed",
26322                "rust-worker",
26323                typed_fidelity_probe(),
26324                DEFAULT_CODEC,
26325            )
26326            .await
26327            .expect("typed activity completion");
26328        assert_eq!(
26329            decode_wire_avro_value(
26330                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
26331                    ["result"],
26332                DEFAULT_CODEC,
26333            )
26334            .expect("typed activity result"),
26335            typed_fidelity_probe()
26336        );
26337        client
26338            .fail_activity_task(
26339                "activity-typed",
26340                "attempt-typed",
26341                "rust-worker",
26342                "typed failure",
26343                true,
26344            )
26345            .await
26346            .expect("activity failure");
26347    }
26348
26349    #[tokio::test]
26350    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
26351        let server = MockWorkerServer::start();
26352        let client = Client::builder(server.base_url())
26353            .timeout(Duration::from_secs(2))
26354            .build()
26355            .expect("client");
26356
26357        let options = WorkflowCommandOptions::new()
26358            .reason("cleanup requested")
26359            .request_id("cancel-17");
26360        let cancelled = client
26361            .cancel_workflow("wf-lifecycle", options)
26362            .await
26363            .expect("instance cancellation");
26364        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
26365        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
26366        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
26367        assert_eq!(
26368            server.request_body("/api/workflows/wf-lifecycle/cancel"),
26369            json!({"reason":"cleanup requested","request_id":"cancel-17"})
26370        );
26371
26372        let terminated = client
26373            .terminate_workflow(
26374                "wf-lifecycle",
26375                WorkflowCommandOptions::new().reason("forced stop"),
26376            )
26377            .await
26378            .expect("instance termination");
26379        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
26380        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
26381
26382        client
26383            .cancel_workflow_run(
26384                "wf-lifecycle",
26385                "run-current",
26386                WorkflowCommandOptions::default(),
26387            )
26388            .await
26389            .expect("selected run cancellation");
26390        client
26391            .terminate_workflow_run(
26392                "wf-lifecycle",
26393                "run-current",
26394                WorkflowCommandOptions::default(),
26395            )
26396            .await
26397            .expect("selected run termination");
26398
26399        for (command, error) in [
26400            (
26401                WorkflowCommandKind::Cancel,
26402                client
26403                    .cancel_workflow_run(
26404                        "wf-lifecycle",
26405                        "run-stale",
26406                        WorkflowCommandOptions::default(),
26407                    )
26408                    .await
26409                    .expect_err("stale cancellation must be rejected"),
26410            ),
26411            (
26412                WorkflowCommandKind::Terminate,
26413                client
26414                    .terminate_workflow_run(
26415                        "wf-lifecycle",
26416                        "run-stale",
26417                        WorkflowCommandOptions::default(),
26418                    )
26419                    .await
26420                    .expect_err("stale termination must be rejected"),
26421            ),
26422        ] {
26423            let Error::WorkflowCommandRejected(rejection) = error else {
26424                panic!("expected typed command rejection");
26425            };
26426            assert_eq!(rejection.command, command);
26427            assert_eq!(rejection.status, 409);
26428            assert_eq!(rejection.reason, "historical_run_command_rejected");
26429            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
26430            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
26431        }
26432    }
26433
26434    #[tokio::test]
26435    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
26436        let server = MockWorkerServer::start();
26437        let client = Client::builder(server.base_url())
26438            .timeout(Duration::from_secs(2))
26439            .build()
26440            .expect("client");
26441
26442        let result = client
26443            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
26444            .await
26445            .expect("redrive accepted");
26446        assert_eq!(result.workflow_id, "wf-lifecycle");
26447        assert_eq!(result.source_run_id, "run-failed");
26448        assert_eq!(result.run_id, "run-successor");
26449        assert_eq!(result.resume_step_sequence, 2);
26450        assert_eq!(
26451            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
26452            json!({"request_id":"retry-1"})
26453        );
26454
26455        let repeated = client
26456            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
26457            .await
26458            .expect("idempotent redrive response accepted");
26459        assert_eq!(repeated.run_id, "run-successor");
26460
26461        let error = client
26462            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
26463            .await
26464            .expect_err("completed run must be rejected");
26465        let Error::Http { status, body } = error else {
26466            panic!("expected HTTP redrive rejection");
26467        };
26468        assert_eq!(status.as_u16(), 409);
26469        assert!(body.contains("run_not_failed"));
26470        assert_eq!(
26471            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
26472            json!({})
26473        );
26474
26475        let handle = WorkflowHandle {
26476            client: client.clone(),
26477            workflow_id: "wf-lifecycle".to_string(),
26478            run_id: Some("run-failed".to_string()),
26479            workflow_type: "test".to_string(),
26480        };
26481        assert_eq!(
26482            handle.redrive(None).await.expect("handle redrive").run_id,
26483            "run-successor"
26484        );
26485        let missing_run = WorkflowHandle {
26486            run_id: None,
26487            ..handle
26488        };
26489        assert!(matches!(
26490            missing_run.redrive(None).await,
26491            Err(Error::Codec(_))
26492        ));
26493    }
26494
26495    #[tokio::test]
26496    async fn workflow_start_options_send_server_enforced_deadlines() {
26497        let server = MockWorkerServer::start();
26498        let client = Client::builder(server.base_url())
26499            .timeout(Duration::from_secs(2))
26500            .build()
26501            .expect("client");
26502
26503        let handle = client
26504            .start_workflow_with_options(
26505                "rust.timeout",
26506                "rust-timeouts",
26507                "wf-start-options",
26508                WorkflowStartOptions::new()
26509                    .execution_timeout_seconds(30)
26510                    .run_timeout_seconds(1),
26511                json!([]),
26512            )
26513            .await
26514            .expect("workflow start");
26515
26516        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
26517        let body = server.request_body("/api/workflows");
26518        assert_eq!(body["execution_timeout_seconds"], 30);
26519        assert_eq!(body["run_timeout_seconds"], 1);
26520
26521        let invalid = client
26522            .start_workflow_with_options(
26523                "rust.timeout",
26524                "rust-timeouts",
26525                "wf-invalid-options",
26526                WorkflowStartOptions::new()
26527                    .execution_timeout_seconds(1)
26528                    .run_timeout_seconds(2),
26529                json!([]),
26530            )
26531            .await
26532            .expect_err("invalid deadline ordering");
26533        assert!(invalid
26534            .to_string()
26535            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
26536    }
26537
26538    #[tokio::test]
26539    async fn workflow_result_returns_each_typed_terminal_outcome() {
26540        let server = MockWorkerServer::start();
26541        let client = Client::builder(server.base_url())
26542            .timeout(Duration::from_secs(2))
26543            .build()
26544            .expect("client");
26545        let options = WorkflowResultOptions {
26546            poll_interval: Duration::ZERO,
26547            timeout: Duration::from_secs(1),
26548        };
26549
26550        let failed = WorkflowHandle {
26551            client: client.clone(),
26552            workflow_id: "wf-failed".to_string(),
26553            run_id: Some("run-failed".to_string()),
26554            workflow_type: "failure".to_string(),
26555        }
26556        .result(options)
26557        .await
26558        .expect_err("failed outcome");
26559        let Error::WorkflowFailed(failure) = failed else {
26560            panic!("expected WorkflowFailed");
26561        };
26562        assert_eq!(failure.workflow_id, "wf-failed");
26563        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
26564        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
26565        assert_eq!(failure.failure_category.as_deref(), Some("application"));
26566        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
26567        assert_eq!(
26568            failure.exception_class.as_deref(),
26569            Some("billing::PaymentError")
26570        );
26571        assert_eq!(failure.non_retryable, Some(true));
26572
26573        for (workflow_id, expected_kind, expected_reason) in [
26574            (
26575                "wf-cancelled",
26576                WorkflowTerminalKind::Cancelled,
26577                "cleanup requested",
26578            ),
26579            (
26580                "wf-terminated",
26581                WorkflowTerminalKind::Terminated,
26582                "forced stop",
26583            ),
26584            (
26585                "wf-timed-out",
26586                WorkflowTerminalKind::TimedOut,
26587                "run_timeout",
26588            ),
26589        ] {
26590            let error = WorkflowHandle {
26591                client: client.clone(),
26592                workflow_id: workflow_id.to_string(),
26593                run_id: None,
26594                workflow_type: "terminal".to_string(),
26595            }
26596            .result(options)
26597            .await
26598            .expect_err("typed terminal outcome");
26599            let outcome = match error {
26600                Error::WorkflowCancelled(outcome) => outcome,
26601                Error::WorkflowTerminated(outcome) => outcome,
26602                Error::WorkflowTimedOut(outcome) => outcome,
26603                other => panic!("unexpected terminal error: {other}"),
26604            };
26605            assert_eq!(outcome.kind, expected_kind);
26606            assert_eq!(outcome.workflow_id, workflow_id);
26607            assert_eq!(outcome.reason, expected_reason);
26608        }
26609
26610        let wait_timeout = WorkflowHandle {
26611            client,
26612            workflow_id: "wf-waiting".to_string(),
26613            run_id: Some("run-waiting".to_string()),
26614            workflow_type: "waiting".to_string(),
26615        }
26616        .result(WorkflowResultOptions {
26617            poll_interval: Duration::ZERO,
26618            timeout: Duration::ZERO,
26619        })
26620        .await
26621        .expect_err("client wait timeout");
26622        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
26623            panic!("expected typed client timeout");
26624        };
26625        assert_eq!(timeout.reason, "result_wait_timeout");
26626        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
26627        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
26628    }
26629
26630    #[tokio::test]
26631    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
26632        let server = MockWorkerServer::start();
26633        let client = Client::builder(server.base_url())
26634            .timeout(Duration::from_secs(2))
26635            .build()
26636            .expect("client");
26637
26638        let handle = WorkflowHandle {
26639            client,
26640            workflow_id: "wf-selected".to_string(),
26641            run_id: Some("run-selected".to_string()),
26642            workflow_type: "selected".to_string(),
26643        };
26644        let options = WorkflowResultOptions {
26645            poll_interval: Duration::ZERO,
26646            timeout: Duration::from_secs(1),
26647        };
26648
26649        let current = handle
26650            .result(options)
26651            .await
26652            .expect("instance result follows the current run");
26653        assert_eq!(current, json!("current run output"));
26654
26655        let error = handle
26656            .result_selected_run(options)
26657            .await
26658            .expect_err("the selected run is cancelled even though the current run completed");
26659
26660        let Error::WorkflowCancelled(outcome) = error else {
26661            panic!("expected selected run cancellation");
26662        };
26663        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
26664        assert_eq!(outcome.reason, "selected run cancelled");
26665        assert_eq!(
26666            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
26667            1
26668        );
26669        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
26670    }
26671
26672    #[tokio::test]
26673    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
26674        let server = MockWorkerServer::draining_polls();
26675        let client = Client::builder(server.base_url())
26676            .timeout(Duration::from_secs(2))
26677            .build()
26678            .expect("client");
26679
26680        let workflow = client
26681            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
26682            .await
26683            .expect("workflow drain response");
26684        let activity = client
26685            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
26686            .await
26687            .expect("activity drain response");
26688        let query = client
26689            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
26690            .await
26691            .expect("query drain response");
26692
26693        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
26694            assert_eq!(
26695                outcome,
26696                WorkerPollOutcome::Stop {
26697                    poll_status: Some("draining".to_string()),
26698                    reason: Some("worker_draining".to_string()),
26699                }
26700            );
26701        }
26702
26703        assert!(client
26704            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
26705            .await
26706            .expect("compatibility poll")
26707            .is_none());
26708    }
26709
26710    #[tokio::test]
26711    async fn managed_worker_honors_drain_stop_for_every_task_family() {
26712        let server = MockWorkerServer::draining_polls();
26713        let client = Client::builder(server.base_url())
26714            .timeout(Duration::from_secs(2))
26715            .build()
26716            .expect("client");
26717
26718        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
26719            .worker_id("draining-workflow-worker")
26720            .poll_timeout(Duration::ZERO);
26721        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
26722        workflow_worker
26723            .run()
26724            .await
26725            .expect("workflow drain is a clean stop");
26726
26727        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
26728            .worker_id("draining-activity-worker")
26729            .poll_timeout(Duration::ZERO);
26730        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
26731        activity_worker
26732            .run()
26733            .await
26734            .expect("activity drain is a clean stop");
26735
26736        let mut query_worker = Worker::new(client, "rust-workers")
26737            .worker_id("draining-query-worker")
26738            .poll_timeout(Duration::ZERO);
26739        query_worker.register_query("counter", "current", |_ctx, _args| async {
26740            Ok(Value::Null)
26741        });
26742        query_worker
26743            .run()
26744            .await
26745            .expect("query drain is a clean stop");
26746    }
26747
26748    #[tokio::test]
26749    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
26750        let server = MockWorkerServer::start();
26751        let client = Client::builder(server.base_url())
26752            .timeout(Duration::from_secs(2))
26753            .build()
26754            .expect("client");
26755
26756        let details: Value = serde_json::from_str(include_str!(
26757            "../tests/fixtures/activity-heartbeat-progress.json"
26758        ))
26759        .expect("heartbeat progress fixture");
26760        // Every individual field fits Server's progress contract, while the
26761        // obsolete encoded envelope exceeded its 191-character string limit.
26762        assert!(
26763            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
26764                .unwrap()["blob"]
26765                .as_str()
26766                .unwrap()
26767                .len()
26768                > 191
26769        );
26770        let heartbeat = client
26771            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
26772            .await
26773            .expect("cancellation heartbeat");
26774        assert!(heartbeat.cancel_requested);
26775        assert!(heartbeat.should_stop());
26776        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
26777        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
26778        let heartbeat_body =
26779            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
26780        assert_eq!(heartbeat_body["details"], details);
26781        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
26782        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
26783
26784        let error = client
26785            .complete_activity_task(
26786                "activity-cancel",
26787                "attempt-cancel",
26788                "rust-worker",
26789                json!({"late":true}),
26790                DEFAULT_CODEC,
26791            )
26792            .await
26793            .expect_err("late completion must be refused");
26794        assert!(activity_task_rejection_is_final(&error));
26795        let Error::ActivityTaskRejected(rejection) = error else {
26796            panic!("expected typed activity rejection");
26797        };
26798        assert_eq!(rejection.status, 409);
26799        assert_eq!(rejection.reason, "run_cancelled");
26800        assert!(rejection.cancel_requested);
26801        assert_eq!(rejection.can_continue, Some(false));
26802    }
26803
26804    #[tokio::test]
26805    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
26806        let server = MockWorkerServer::cancelled_activity();
26807        let client = Client::builder(server.base_url())
26808            .timeout(Duration::from_secs(2))
26809            .build()
26810            .expect("client");
26811        let cancellation_observed = Arc::new(AtomicBool::new(false));
26812        let observed = Arc::clone(&cancellation_observed);
26813        let mut worker = Worker::new(client.clone(), "rust-workers")
26814            .worker_id("rust-cancel-worker")
26815            .poll_timeout(Duration::from_millis(10));
26816        worker.register_activity("cancel-aware", move |ctx, _args| {
26817            let observed = Arc::clone(&observed);
26818            async move {
26819                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
26820                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
26821                Ok(json!({"late":"completion"}))
26822            }
26823        });
26824
26825        assert_eq!(
26826            worker.run_once().await.expect("cancelled attempt handled"),
26827            1
26828        );
26829        assert!(cancellation_observed.load(Ordering::SeqCst));
26830        assert_eq!(
26831            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
26832            1
26833        );
26834
26835        let mut restarted = Worker::new(client, "rust-workers")
26836            .worker_id("rust-cancel-worker-restarted")
26837            .poll_timeout(Duration::from_millis(10));
26838        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
26839        assert_eq!(
26840            restarted
26841                .run_once()
26842                .await
26843                .expect("replacement worker continues polling"),
26844            0
26845        );
26846    }
26847
26848    #[tokio::test]
26849    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
26850        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"}"#;
26851        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
26852        let client = Client::builder(server.base_url())
26853            .timeout(Duration::from_secs(2))
26854            .build()
26855            .expect("client");
26856
26857        let direct_error = client
26858            .complete_workflow_task(
26859                "workflow-timeout-task",
26860                "timeout-worker",
26861                3,
26862                vec![json!({
26863                    "type": "complete_workflow",
26864                    "result": fixture_envelope(Value::Null)
26865                })],
26866            )
26867            .await
26868            .expect_err("the low-level client preserves the completion rejection");
26869        let Error::Http { status, body } = direct_error else {
26870            panic!("expected the original HTTP completion rejection");
26871        };
26872        assert_eq!(status, reqwest::StatusCode::CONFLICT);
26873        assert_eq!(
26874            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
26875            "run_timed_out"
26876        );
26877
26878        let mut worker = Worker::new(client, "rust-workers")
26879            .worker_id("timeout-worker")
26880            .poll_timeout(Duration::from_millis(10));
26881        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26882            Ok(json!({"late": "result"}))
26883        });
26884
26885        assert_eq!(
26886            worker
26887                .run_once()
26888                .await
26889                .expect("authoritative selected-run timeout settles the tick"),
26890            1
26891        );
26892        assert_eq!(
26893            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
26894            2,
26895            "both the direct client proof and managed worker must see the rejection"
26896        );
26897    }
26898
26899    #[tokio::test]
26900    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
26901        for (name, status, response) in [
26902            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
26903            (
26904                "command was recorded",
26905                "409 Conflict",
26906                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26907            ),
26908            (
26909                "lease conflict",
26910                "409 Conflict",
26911                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
26912            ),
26913            (
26914                "nonterminal run",
26915                "409 Conflict",
26916                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
26917            ),
26918            (
26919                "different selected run",
26920                "409 Conflict",
26921                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"}"#,
26922            ),
26923            (
26924                "different task attempt",
26925                "409 Conflict",
26926                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26927            ),
26928            (
26929                "authentication failure",
26930                "401 Unauthorized",
26931                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26932            ),
26933            (
26934                "authorization failure",
26935                "403 Forbidden",
26936                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26937            ),
26938            (
26939                "protocol failure",
26940                "400 Bad Request",
26941                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
26942            ),
26943            (
26944                "malformed command",
26945                "422 Unprocessable Entity",
26946                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26947            ),
26948            (
26949                "transient server failure",
26950                "503 Service Unavailable",
26951                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26952            ),
26953        ] {
26954            let server = MockWorkerServer::workflow_completion(status, response);
26955            let client = Client::builder(server.base_url())
26956                .timeout(Duration::from_secs(2))
26957                .build()
26958                .expect("client");
26959            let mut worker = Worker::new(client, "rust-workers")
26960                .worker_id("timeout-worker")
26961                .poll_timeout(Duration::from_millis(10));
26962            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26963                Ok(json!({"late": "result"}))
26964            });
26965
26966            let error = worker
26967                .run_once()
26968                .await
26969                .expect_err(&format!("{name} must remain an error"));
26970            assert!(
26971                matches!(error, Error::Http { .. } | Error::Protocol(_)),
26972                "{name} returned an unexpected error variant: {error}"
26973            );
26974        }
26975    }
26976
26977    #[tokio::test]
26978    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
26979        let server = MockWorkerServer::start();
26980        let client = Client::builder(server.base_url())
26981            .worker_token(Some("worker-secret".to_string()))
26982            .namespace("orders")
26983            .timeout(Duration::from_secs(2))
26984            .build()
26985            .expect("client");
26986        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
26987
26988        let result = client
26989            .deregister_worker_registration("worker/α space")
26990            .await
26991            .expect("deregister worker registration");
26992
26993        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
26994        assert_eq!(
26995            server.worker_protocol_for(path).as_deref(),
26996            Some(WORKER_PROTOCOL_VERSION)
26997        );
26998        assert_eq!(server.control_protocol_for(path), None);
26999        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
27000        assert_eq!(
27001            server.authorization_for(path).as_deref(),
27002            Some("Bearer worker-secret")
27003        );
27004        assert_eq!(
27005            result,
27006            WorkerDeregistrationEnvelope {
27007                worker_id: "deregistered-worker".to_string(),
27008                outcome: "deregistered".to_string(),
27009                recovered_workflow_task_count: 2,
27010            }
27011        );
27012    }
27013
27014    #[tokio::test]
27015    async fn low_level_registration_rejects_update_validators_before_transport() {
27016        let server = MockWorkerServer::start();
27017        let client = Client::builder(server.base_url())
27018            .timeout(Duration::from_secs(2))
27019            .build()
27020            .expect("client");
27021
27022        for update_validators in [json!(["approve"]), json!("approve")] {
27023            let error = client
27024                .register_worker_with_command_contracts(
27025                    "validator-claiming-worker",
27026                    "rust-workers",
27027                    vec!["orders".to_string()],
27028                    vec![],
27029                    1,
27030                    1,
27031                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
27032                    json!({
27033                        "orders": {
27034                            "queries": ["current"],
27035                            "updates": ["approve"],
27036                            "update_validators": update_validators,
27037                        },
27038                    }),
27039                )
27040                .await
27041                .expect_err("unsupported validator claims must fail before registration");
27042
27043            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
27044                panic!("expected typed unsupported-validator failure");
27045            };
27046            assert_eq!(workflow_type, "orders");
27047        }
27048        assert_eq!(server.request_count("/api/worker/register"), 0);
27049    }
27050
27051    #[tokio::test]
27052    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
27053        let server = MockWorkerServer::start();
27054        let client = Client::builder(server.base_url())
27055            .timeout(Duration::from_secs(2))
27056            .build()
27057            .expect("client");
27058        let mut worker = Worker::new(client, "rust-workers");
27059        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
27060        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
27061        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
27062        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
27063        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
27064        worker
27065            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
27066            .expect("declare workflow signals");
27067
27068        worker.register().await.expect("register handler contracts");
27069
27070        let declaration =
27071            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
27072        let expected_contracts = json!([
27073            {
27074                "name": "a-avro",
27075                "parameters": [{
27076                    "name": "args", "position": 0, "required": false,
27077                    "variadic": true, "type": null, "allows_null": true,
27078                    "default_available": false, "default": null,
27079                }],
27080            },
27081            {
27082                "name": "z-json",
27083                "parameters": [{
27084                    "name": "args", "position": 0, "required": false,
27085                    "variadic": true, "type": null, "allows_null": true,
27086                    "default_available": false, "default": null,
27087                }],
27088            },
27089        ]);
27090        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
27091        assert_eq!(declaration["query_contracts"], expected_contracts);
27092        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
27093        assert_eq!(declaration["update_contracts"], expected_contracts);
27094        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
27095        assert_eq!(declaration["signal_contracts"], expected_contracts);
27096        assert_eq!(declaration["update_validators"], json!([]));
27097    }
27098
27099    #[tokio::test]
27100    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
27101        let server = MockWorkerServer::start();
27102        let client = Client::new(server.base_url()).expect("client");
27103        let mut worker = Worker::new(client, "rust-workers");
27104        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
27105        assert!(worker
27106            .declare_workflow_signals("missing", &["finish"])
27107            .is_err());
27108        worker
27109            .declare_workflow_signals("orders", &["finish"])
27110            .unwrap();
27111        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
27112            assert!(worker.declare_workflow_signals("orders", names).is_err());
27113        }
27114        worker.register().await.unwrap();
27115        assert_eq!(
27116            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
27117                ["signals"],
27118            json!(["finish"])
27119        );
27120        worker.declare_workflow_signals("orders", &[]).unwrap();
27121        worker.register().await.unwrap();
27122        let registrations = server.request_bodies("/api/worker/register");
27123        assert_eq!(
27124            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
27125            json!([])
27126        );
27127        assert_eq!(
27128            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
27129            json!([])
27130        );
27131    }
27132
27133    #[tokio::test]
27134    async fn low_level_registration_preserves_query_and_update_contracts() {
27135        let server = MockWorkerServer::start();
27136        let client = Client::builder(server.base_url())
27137            .timeout(Duration::from_secs(2))
27138            .build()
27139            .expect("client");
27140        let contracts = json!({
27141            "orders": {
27142                "queries": ["current"],
27143                "updates": ["approve"],
27144                "update_validators": [],
27145            },
27146            "payments": {
27147                "queries": ["status"],
27148                "updates": ["capture"],
27149            },
27150        });
27151
27152        client
27153            .register_worker_with_command_contracts(
27154                "command-worker",
27155                "rust-workers",
27156                vec!["orders".to_string(), "payments".to_string()],
27157                vec![],
27158                1,
27159                1,
27160                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
27161                contracts.clone(),
27162            )
27163            .await
27164            .expect("query and update contracts must remain supported");
27165
27166        assert_eq!(
27167            server.request_body("/api/worker/register")["workflow_command_contracts"],
27168            contracts
27169        );
27170        assert!(server
27171            .request_body("/api/worker/register")
27172            .get("workflow_definition_fingerprints")
27173            .is_none());
27174    }
27175
27176    #[tokio::test]
27177    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
27178        let server = MockWorkerServer::start();
27179        let client = Client::builder(server.base_url())
27180            .timeout(Duration::from_secs(2))
27181            .build()
27182            .expect("client");
27183        let mut worker = Worker::new(client.clone(), "rust-workers");
27184        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27185
27186        assert!(worker
27187            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
27188            .is_err());
27189        assert!(worker
27190            .set_workflow_definition_sources("orders", &[])
27191            .is_err());
27192        worker
27193            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
27194            .expect("embed workflow source");
27195        worker.register().await.expect("register worker");
27196        let first = server.request_bodies("/api/worker/register")[0]
27197            ["workflow_definition_fingerprints"]["orders"]
27198            .as_str()
27199            .expect("source-backed fingerprint")
27200            .to_string();
27201        assert!(first.starts_with("sha256:"));
27202
27203        worker
27204            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
27205            .expect("change embedded helper source");
27206        worker.register().await.expect("register changed source");
27207        let changed = server.request_bodies("/api/worker/register")[1]
27208            ["workflow_definition_fingerprints"]["orders"]
27209            .as_str()
27210            .expect("changed fingerprint")
27211            .to_string();
27212        assert_ne!(first, changed);
27213
27214        let mut replacement =
27215            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
27216        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27217        replacement
27218            .register()
27219            .await
27220            .expect("register replacement handler");
27221        assert_eq!(
27222            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
27223            json!({})
27224        );
27225    }
27226
27227    #[tokio::test]
27228    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
27229        let server = MockWorkerServer::start();
27230        let control_only = Client::builder(server.base_url())
27231            .control_token(Some("control-secret".to_string()))
27232            .build()
27233            .expect("control client");
27234
27235        let error = control_only
27236            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27237            .await
27238            .expect_err("control token must not authorize a worker request");
27239        assert!(matches!(
27240            error,
27241            Error::MissingRoleCredentials { role: "worker", .. }
27242        ));
27243        assert_eq!(server.request_count("/api/worker/register"), 0);
27244
27245        let worker_only = Client::builder(server.base_url())
27246            .worker_token(Some("worker-secret".to_string()))
27247            .build()
27248            .expect("worker client");
27249        let error = worker_only
27250            .health()
27251            .await
27252            .expect_err("worker token must not authorize a control request");
27253        assert!(matches!(
27254            error,
27255            Error::MissingRoleCredentials {
27256                role: "control",
27257                ..
27258            }
27259        ));
27260        assert_eq!(server.request_count("/api/health"), 0);
27261    }
27262
27263    #[tokio::test]
27264    async fn shared_token_supports_worker_and_control_planes() {
27265        let server = MockWorkerServer::start();
27266        let client = Client::builder(server.base_url())
27267            .token(Some("shared-secret".to_string()))
27268            .build()
27269            .expect("client");
27270
27271        client.health().await.expect("control request");
27272        client
27273            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27274            .await
27275            .expect("worker request");
27276
27277        assert_eq!(
27278            server.authorization_for("/api/health").as_deref(),
27279            Some("Bearer shared-secret")
27280        );
27281        assert_eq!(
27282            server.control_protocol_for("/api/health").as_deref(),
27283            Some(CONTROL_PLANE_VERSION)
27284        );
27285        assert_eq!(
27286            server.authorization_for("/api/worker/register").as_deref(),
27287            Some("Bearer shared-secret")
27288        );
27289        assert_eq!(
27290            server
27291                .worker_protocol_for("/api/worker/register")
27292                .as_deref(),
27293            Some(WORKER_PROTOCOL_VERSION)
27294        );
27295    }
27296
27297    #[tokio::test]
27298    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
27299        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
27300        let server = MockWorkerServer::start();
27301        let client = Client::builder(server.base_url())
27302            .timeout(Duration::from_secs(2))
27303            .build()
27304            .expect("client");
27305
27306        client
27307            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
27308            .await
27309            .expect("register");
27310        client
27311            .heartbeat_worker("capture-worker", 1, 1)
27312            .await
27313            .expect("heartbeat");
27314        client
27315            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27316            .await
27317            .expect("workflow poll");
27318        client
27319            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27320            .await
27321            .expect("activity poll");
27322
27323        for path in [
27324            "/api/worker/register",
27325            "/api/worker/heartbeat",
27326            "/api/worker/workflow-tasks/poll",
27327            "/api/worker/activity-tasks/poll",
27328        ] {
27329            assert_eq!(
27330                server.worker_protocol_for(path).as_deref(),
27331                Some(WORKER_PROTOCOL_VERSION),
27332                "unexpected protocol for {path}"
27333            );
27334        }
27335
27336        assert_eq!(
27337            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
27338            1
27339        );
27340        assert_eq!(
27341            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
27342            500
27343        );
27344        assert_eq!(
27345            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
27346            1
27347        );
27348        assert!(
27349            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
27350                .as_str()
27351                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
27352        );
27353        assert!(
27354            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
27355                .as_str()
27356                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
27357        );
27358        let registration = server.request_body("/api/worker/register");
27359        for optional in [
27360            "cooperative_cancellation",
27361            "local_activities",
27362            "worker_sessions",
27363            "sticky_execution",
27364        ] {
27365            assert!(!registration["capabilities"]
27366                .as_array()
27367                .is_some_and(|capabilities| capabilities
27368                    .iter()
27369                    .any(|capability| capability.as_str() == Some(optional))));
27370        }
27371    }
27372
27373    #[tokio::test]
27374    async fn explicit_previous_worker_protocol_preserves_headers() {
27375        let server = MockWorkerServer::start();
27376        let client = Client::builder(server.base_url())
27377            .worker_protocol_version(WorkerProtocolVersion::V119)
27378            .timeout(Duration::from_secs(2))
27379            .build()
27380            .expect("client");
27381        client
27382            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
27383            .await
27384            .expect("register");
27385        client
27386            .heartbeat_worker("legacy-worker", 1, 1)
27387            .await
27388            .expect("heartbeat");
27389        client
27390            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
27391            .await
27392            .expect("workflow poll");
27393        client
27394            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
27395            .await
27396            .expect("activity poll");
27397        client
27398            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
27399            .await
27400            .expect("query poll");
27401        client
27402            .deregister_worker_registration("legacy-worker")
27403            .await
27404            .expect("deregister");
27405        for path in [
27406            "/api/worker/register",
27407            "/api/worker/heartbeat",
27408            "/api/worker/workflow-tasks/poll",
27409            "/api/worker/activity-tasks/poll",
27410            "/api/worker/query-tasks/poll",
27411            "/api/worker/registrations/legacy-worker",
27412        ] {
27413            assert_eq!(
27414                server.worker_protocol_for(path).as_deref(),
27415                Some("1.19"),
27416                "{path}"
27417            );
27418            assert_eq!(server.control_protocol_for(path), None, "{path}");
27419        }
27420    }
27421
27422    #[tokio::test]
27423    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
27424        let server = MockWorkerServer::start();
27425        let client = Client::builder(server.base_url())
27426            .worker_protocol_version(WorkerProtocolVersion::V119)
27427            .timeout(Duration::from_secs(2))
27428            .build()
27429            .expect("client");
27430        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
27431        let error = worker
27432            .register()
27433            .await
27434            .expect_err("legacy cooperation must be refused");
27435        assert!(matches!(
27436            error,
27437            Error::CooperativeCancellationUnavailable(_)
27438        ));
27439        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
27440    }
27441
27442    #[tokio::test]
27443    async fn query_task_endpoints_send_the_selected_worker_protocol() {
27444        let server = MockWorkerServer::start();
27445        let client = Client::builder(server.base_url())
27446            .timeout(Duration::from_secs(2))
27447            .build()
27448            .expect("client");
27449
27450        client
27451            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27452            .await
27453            .expect("query poll");
27454        client
27455            .complete_query_task(
27456                "query-capture",
27457                "capture-worker",
27458                1,
27459                json!(8),
27460                DEFAULT_CODEC,
27461            )
27462            .await
27463            .expect("query complete");
27464        client
27465            .fail_query_task(
27466                "query-capture",
27467                "capture-worker",
27468                1,
27469                "failed",
27470                "query_rejected",
27471                "QueryFailed",
27472            )
27473            .await
27474            .expect("query fail");
27475
27476        for path in [
27477            "/api/worker/query-tasks/poll",
27478            "/api/worker/query-tasks/query-capture/complete",
27479            "/api/worker/query-tasks/query-capture/fail",
27480        ] {
27481            assert_eq!(
27482                server.worker_protocol_for(path).as_deref(),
27483                Some(WORKER_PROTOCOL_VERSION),
27484                "unexpected protocol for {path}"
27485            );
27486        }
27487
27488        assert_eq!(
27489            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
27490            1
27491        );
27492        assert!(
27493            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
27494                .as_str()
27495                .is_some_and(|id| id.starts_with("rust-query-poll-"))
27496        );
27497    }
27498
27499    #[tokio::test]
27500    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
27501        let server = MockWorkerServer::transient_worker_failures();
27502        let client = Client::builder(server.base_url())
27503            .timeout(Duration::from_secs(2))
27504            .build()
27505            .expect("client");
27506
27507        client
27508            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27509            .await
27510            .expect("workflow poll retry");
27511        client
27512            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27513            .await
27514            .expect("activity poll retry");
27515        client
27516            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27517            .await
27518            .expect("query poll retry");
27519
27520        for path in [
27521            "/api/worker/workflow-tasks/poll",
27522            "/api/worker/activity-tasks/poll",
27523            "/api/worker/query-tasks/poll",
27524        ] {
27525            let bodies = server.request_bodies(path);
27526            assert_eq!(bodies.len(), 2, "{path} must be retried once");
27527            assert_eq!(
27528                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
27529                "{path} must preserve the request binding across retry"
27530            );
27531        }
27532    }
27533
27534    #[tokio::test]
27535    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
27536        let server = MockWorkerServer::consecutive_poll_failures(2);
27537        let client = Client::builder(server.base_url())
27538            .timeout(Duration::from_secs(2))
27539            .build()
27540            .expect("client");
27541        let mut worker = Worker::new(client, "capture")
27542            .worker_id("capture-worker")
27543            .poll_timeout(Duration::from_millis(10))
27544            .retry_policy(WorkerRetryPolicy {
27545                max_retries: 2,
27546                initial_backoff: Duration::from_millis(1),
27547                max_backoff: Duration::from_millis(1),
27548            });
27549        worker.register_workflow(
27550            "capture.workflow",
27551            |_ctx, _input| async move { Ok(Value::Null) },
27552        );
27553        worker.register_activity(
27554            "capture.activity",
27555            |_ctx, _input| async move { Ok(Value::Null) },
27556        );
27557        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
27558            Ok(Value::Null)
27559        });
27560
27561        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
27562
27563        for path in [
27564            "/api/worker/workflow-tasks/poll",
27565            "/api/worker/activity-tasks/poll",
27566            "/api/worker/query-tasks/poll",
27567        ] {
27568            let bodies = server.request_bodies(path);
27569            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
27570            assert!(
27571                bodies
27572                    .iter()
27573                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
27574                "{path} must preserve one request binding across every retry"
27575            );
27576        }
27577    }
27578
27579    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
27580        let reason = if unavailable {
27581            "storage_admission_unavailable"
27582        } else {
27583            "storage_pressure"
27584        };
27585        let mut body = json!({
27586            "reason": reason,
27587            "storage_state": if unavailable { "fenced" } else { "draining" },
27588            "retryable": true,
27589            "retry_after_seconds": 1,
27590        });
27591        if !mid_poll {
27592            body["request_admitted"] = json!(false);
27593        }
27594        if let Some(id) = poll_id {
27595            body["task"] = Value::Null;
27596            body["poll_status"] = json!(reason);
27597            body["poll_request_id"] = json!(id);
27598            body["retry_same_poll_request_id"] = json!(true);
27599            body["claim_admitted"] = json!(false);
27600        }
27601        body
27602    }
27603
27604    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
27605        let operation = match path {
27606            "/api/worker/register" => "register_worker",
27607            "/api/worker/heartbeat" => "heartbeat_worker",
27608            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
27609            "/api/worker/activity-tasks/poll" => "poll_activity_task",
27610            "/api/worker/query-tasks/poll" => "poll_query_task",
27611            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
27612            _ => return None,
27613        };
27614        let request: Value = serde_json::from_str(request).ok()?;
27615        let mut response = json!({
27616            "reason": "backend_unavailable",
27617            "operation": operation,
27618            "outcome": "unknown",
27619            "retryable": true,
27620            "retry_after_seconds": 1,
27621            "worker_id": request["worker_id"],
27622            "task_queue": request.get("task_queue"),
27623        });
27624        if path.ends_with("/poll") {
27625            response["task"] = Value::Null;
27626            response["poll_status"] = json!("backend_unavailable");
27627            response["poll_request_id"] = request["poll_request_id"].clone();
27628            response["retry_same_poll_request_id"] = json!(true);
27629        }
27630        Some(response)
27631    }
27632
27633    fn backend_retry_override(
27634        path: &str,
27635        request: &str,
27636        number: usize,
27637    ) -> Option<(&'static str, String)> {
27638        if number > 8 {
27639            return None;
27640        }
27641        Some((
27642            "503 Service Unavailable",
27643            backend_refusal(path, request)?.to_string(),
27644        ))
27645    }
27646
27647    fn backend_unavailable_override(
27648        path: &str,
27649        request: &str,
27650        _number: usize,
27651    ) -> Option<(&'static str, String)> {
27652        Some((
27653            "503 Service Unavailable",
27654            backend_refusal(path, request)?.to_string(),
27655        ))
27656    }
27657
27658    fn storage_worker(server: &MockWorkerServer) -> Worker {
27659        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
27660            .worker_id("storage-worker")
27661            .retry_policy(WorkerRetryPolicy {
27662                max_retries: 1,
27663                initial_backoff: Duration::from_millis(1),
27664                max_backoff: Duration::from_millis(1),
27665            })
27666    }
27667
27668    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
27669        let requests = server.requests.lock().expect("requests");
27670        let bodies: Vec<_> = requests
27671            .iter()
27672            .filter(|request| request.path == path)
27673            .map(|request| &request.body)
27674            .collect();
27675        assert_eq!(bodies.len(), count, "{path}");
27676        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
27677    }
27678
27679    #[test]
27680    fn backend_recovery_requires_the_explicit_worker_contract() {
27681        for (path, operation) in [
27682            ("/worker/register", "register_worker"),
27683            ("/worker/heartbeat", "heartbeat_worker"),
27684            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
27685            ("/worker/activity-tasks/poll", "poll_activity_task"),
27686            ("/worker/query-tasks/poll", "poll_query_task"),
27687            (
27688                "/worker/update-validation-tasks/poll",
27689                "poll_update_validation_task",
27690            ),
27691        ] {
27692            let poll_id = path.ends_with("/poll").then_some("same-poll");
27693            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
27694            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
27695                .expect("worker operation");
27696            assert_eq!(body["operation"], operation);
27697            let error = Error::Http {
27698                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27699                body: body.to_string(),
27700            };
27701            assert_eq!(
27702                worker_backend_unavailable_retry_after(&error, path, poll_id),
27703                Some(Duration::from_secs(1))
27704            );
27705            assert!(!worker_operation_is_retryable(&error));
27706            for (field, value) in [
27707                ("operation", json!("wrong_operation")),
27708                ("outcome", json!("completed")),
27709                ("retryable", json!(false)),
27710                ("retry_after_seconds", json!(0)),
27711                ("worker_id", json!("")),
27712            ] {
27713                let mut invalid = body.clone();
27714                invalid[field] = value;
27715                let error = Error::Http {
27716                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27717                    body: invalid.to_string(),
27718                };
27719                assert!(
27720                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
27721                    "{path}: {field}"
27722                );
27723                assert!(!worker_operation_is_retryable(&error));
27724            }
27725            if let Some(poll_id) = poll_id {
27726                for (field, value) in [
27727                    ("poll_request_id", json!("wrong-poll")),
27728                    ("poll_status", json!("empty")),
27729                    ("task", json!({"task_id":"claimed"})),
27730                    ("retry_same_poll_request_id", json!(false)),
27731                ] {
27732                    let mut invalid = body.clone();
27733                    invalid[field] = value;
27734                    let error = Error::Http {
27735                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27736                        body: invalid.to_string(),
27737                    };
27738                    assert!(
27739                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
27740                            .is_none(),
27741                        "{path}: {field}"
27742                    );
27743                }
27744            }
27745            let error = Error::Http {
27746                status: reqwest::StatusCode::UNAUTHORIZED,
27747                body: body.to_string(),
27748            };
27749            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
27750            assert!(!worker_operation_is_retryable(&error));
27751        }
27752    }
27753
27754    #[tokio::test]
27755    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
27756        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27757            request_override: Some(backend_retry_override),
27758            ..MockWorkerBehavior::default()
27759        });
27760        let mut worker =
27761            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27762        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27763        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
27764        worker.register_query("backend.workflow", "state", |_, _| async {
27765            Ok(Value::Null)
27766        });
27767        worker.register().await.expect("registration recovery");
27768        worker
27769            .client
27770            .heartbeat_worker("storage-worker", 1, 1)
27771            .await
27772            .expect("heartbeat recovery");
27773        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
27774        for path in [
27775            "/api/worker/register",
27776            "/api/worker/heartbeat",
27777            "/api/worker/workflow-tasks/poll",
27778            "/api/worker/activity-tasks/poll",
27779            "/api/worker/query-tasks/poll",
27780        ] {
27781            assert_identical_requests(&server, path, 9);
27782        }
27783    }
27784
27785    #[tokio::test]
27786    async fn backend_recovery_wait_stops_with_worker() {
27787        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27788            request_override: Some(backend_unavailable_override),
27789            ..MockWorkerBehavior::default()
27790        });
27791        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
27792            max_retries: 1,
27793            initial_backoff: Duration::from_secs(2),
27794            max_backoff: Duration::from_secs(2),
27795        });
27796        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27797        let started = tokio::time::Instant::now();
27798        let _ = tokio::time::timeout(
27799            Duration::from_secs(1),
27800            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
27801        )
27802        .await
27803        .expect("shutdown interrupts backend wait");
27804        assert!(started.elapsed() < Duration::from_secs(1));
27805        assert!(server.request_count("/api/worker/register") >= 1);
27806    }
27807
27808    #[test]
27809    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
27810        for unavailable in [false, true] {
27811            for mid_poll in [false, true] {
27812                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
27813                let error = Error::Http {
27814                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27815                    body: body.to_string(),
27816                };
27817                assert_eq!(
27818                    worker_storage_admission_retry_after(&error, Some("same-poll")),
27819                    Some(Duration::from_secs(1))
27820                );
27821                assert!(
27822                    !worker_operation_is_retryable(&error),
27823                    "storage is not a bounded generic retry"
27824                );
27825                for (field, value) in [
27826                    ("poll_request_id", json!("wrong-poll")),
27827                    ("task", json!({"task_id":"claimed"})),
27828                    ("retryable", json!(false)),
27829                    ("retry_after_seconds", json!(0)),
27830                    ("retry_after_seconds", json!(true)),
27831                    ("retry_after_seconds", json!(1.0)),
27832                    ("storage_state", json!("normal")),
27833                    ("poll_status", json!("empty")),
27834                    ("claim_admitted", json!(true)),
27835                    ("retry_same_poll_request_id", json!(false)),
27836                    ("request_admitted", json!(true)),
27837                ] {
27838                    let mut invalid = body.clone();
27839                    invalid[field] = value;
27840                    let error = Error::Http {
27841                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27842                        body: invalid.to_string(),
27843                    };
27844                    assert!(
27845                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
27846                        "{field}"
27847                    );
27848                }
27849            }
27850        }
27851        let body = storage_refusal(None, false, false);
27852        let error = Error::Http {
27853            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27854            body: body.to_string(),
27855        };
27856        assert!(worker_storage_admission_retry_after(&error, None).is_some());
27857        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
27858        let error = Error::Http {
27859            status: reqwest::StatusCode::FORBIDDEN,
27860            body: body.to_string(),
27861        };
27862        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27863        let body = storage_refusal(None, false, true);
27864        let error = Error::Http {
27865            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27866            body: body.to_string(),
27867        };
27868        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27869    }
27870
27871    #[tokio::test]
27872    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
27873        for unavailable in [false, true] {
27874            for mid_poll in [false, true] {
27875                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27876                    poll_failures_per_path: 1,
27877                    storage_refusals: 7,
27878                    storage_path: Some("/poll"),
27879                    storage_unavailable: unavailable,
27880                    storage_mid_poll: mid_poll,
27881                    ..MockWorkerBehavior::default()
27882                });
27883                let mut worker = storage_worker(&server);
27884                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
27885                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
27886                for path in [
27887                    "/api/worker/workflow-tasks/poll",
27888                    "/api/worker/activity-tasks/poll",
27889                    "/api/worker/query-tasks/poll",
27890                ] {
27891                    assert_identical_requests(&server, path, 9);
27892                }
27893            }
27894        }
27895    }
27896
27897    #[tokio::test]
27898    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
27899        struct CountedBody(Arc<AtomicUsize>);
27900        impl Serialize for CountedBody {
27901            fn serialize<S: Serializer>(
27902                &self,
27903                serializer: S,
27904            ) -> std::result::Result<S::Ok, S::Error> {
27905                let count = self.0.fetch_add(1, Ordering::SeqCst);
27906                json!({"serialization":count,"lease_owner":"worker","attempt":7})
27907                    .serialize(serializer)
27908            }
27909        }
27910        for path in [
27911            "/api/worker/register",
27912            "/api/worker/heartbeat",
27913            "/api/worker/workflow-tasks/storage-task/complete",
27914            "/api/worker/workflow-tasks/storage-task/fail",
27915            "/api/worker/activity-tasks/storage-task/complete",
27916            "/api/worker/activity-tasks/storage-task/fail",
27917            "/api/worker/activity-tasks/storage-task/heartbeat",
27918            "/api/worker/query-tasks/storage-task/complete",
27919            "/api/worker/query-tasks/storage-task/fail",
27920        ] {
27921            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27922                storage_refusals: 7,
27923                storage_path: Some(path),
27924                ..MockWorkerBehavior::default()
27925            });
27926            let worker =
27927                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27928            let calls = Arc::new(AtomicUsize::new(0));
27929            let _: Value = worker
27930                .client
27931                .request_json(
27932                    reqwest::Method::POST,
27933                    &path[4..],
27934                    RequestProtocol::DefaultWorker,
27935                    Some(&CountedBody(Arc::clone(&calls))),
27936                )
27937                .await
27938                .expect("prepared request recovery");
27939            assert_eq!(calls.load(Ordering::SeqCst), 1);
27940            assert_identical_requests(&server, path, 8);
27941        }
27942        for worker_scope in [false, true] {
27943            let path = if worker_scope {
27944                "/api/health"
27945            } else {
27946                "/api/worker/register"
27947            };
27948            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27949                storage_refusals: usize::MAX,
27950                storage_path: Some(path),
27951                ..MockWorkerBehavior::default()
27952            });
27953            let worker = storage_worker(&server);
27954            let client = worker.client.clone();
27955            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
27956            let error = if worker_scope {
27957                worker
27958                    .client
27959                    .health()
27960                    .await
27961                    .expect_err("control plane is not retried")
27962            } else {
27963                client
27964                    .request_json::<Value, Value>(
27965                        reqwest::Method::POST,
27966                        "/worker/register",
27967                        RequestProtocol::DefaultWorker,
27968                        Some(&json!({})),
27969                    )
27970                    .await
27971                    .expect_err("direct client is not retried")
27972            };
27973            assert!(worker_storage_admission_body(&error).is_some());
27974            assert_eq!(server.request_count(path), 1);
27975        }
27976    }
27977
27978    #[tokio::test]
27979    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
27980        for fail in [false, true] {
27981            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27982                storage_activity: true,
27983                storage_refusals: 7,
27984                storage_path: Some("/storage-activity/"),
27985                ..MockWorkerBehavior::default()
27986            });
27987            let mut worker = storage_worker(&server);
27988            let calls = Arc::new(AtomicUsize::new(0));
27989            let observed = Arc::clone(&calls);
27990            worker.register_activity("storage.activity", move |ctx, _| {
27991                let calls = Arc::clone(&observed);
27992                async move {
27993                    calls.fetch_add(1, Ordering::SeqCst);
27994                    ctx.heartbeat(json!({"step":2})).await?;
27995                    if fail {
27996                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
27997                    } else {
27998                        Ok(json!({"receipt":true}))
27999                    }
28000                }
28001            });
28002            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
28003            assert_eq!(calls.load(Ordering::SeqCst), 1);
28004            assert_identical_requests(
28005                &server,
28006                "/api/worker/activity-tasks/storage-activity/heartbeat",
28007                8,
28008            );
28009            let suffix = if fail { "fail" } else { "complete" };
28010            assert_identical_requests(
28011                &server,
28012                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
28013                8,
28014            );
28015            let other = if fail { "complete" } else { "fail" };
28016            assert_eq!(
28017                server.request_count(&format!(
28018                    "/api/worker/activity-tasks/storage-activity/{other}"
28019                )),
28020                0
28021            );
28022        }
28023    }
28024
28025    #[tokio::test]
28026    async fn storage_waits_are_interruptible_without_false_activity_failure() {
28027        for path in [
28028            "/api/worker/register",
28029            "/api/worker/heartbeat",
28030            "/api/worker/activity-tasks/poll",
28031            "/api/worker/activity-tasks/storage-activity/heartbeat",
28032            "/api/worker/activity-tasks/storage-activity/complete",
28033        ] {
28034            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28035                storage_activity: true,
28036                storage_refusals: usize::MAX,
28037                storage_path: Some(path),
28038                ..MockWorkerBehavior::default()
28039            });
28040            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
28041            worker.register_activity("storage.activity", |ctx, _| async move {
28042                ctx.heartbeat(json!({"step":2})).await?;
28043                Ok(json!({"receipt":true}))
28044            });
28045            let shutdown = async {
28046                while server.request_count(path) == 0 {
28047                    tokio::time::sleep(Duration::from_millis(1)).await;
28048                }
28049            };
28050            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
28051                .await
28052                .expect("shutdown interrupts admission");
28053            assert!(
28054                result.is_err(),
28055                "a refused operation must not appear acknowledged: {path}, {result:?}"
28056            );
28057            assert_eq!(server.request_count(path), 1);
28058            assert_eq!(
28059                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
28060                0
28061            );
28062            assert_eq!(
28063                server.request_count("/api/worker/registrations/mock-worker"),
28064                usize::from(!path.ends_with("/register"))
28065            );
28066        }
28067    }
28068
28069    #[tokio::test]
28070    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
28071        for fail in [false, true] {
28072            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28073                storage_query: true,
28074                storage_refusals: 7,
28075                storage_path: Some("/storage-query/"),
28076                ..MockWorkerBehavior::default()
28077            });
28078            let mut worker = storage_worker(&server);
28079            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
28080            let calls = Arc::new(AtomicUsize::new(0));
28081            let observed = Arc::clone(&calls);
28082            worker.register_query("storage.workflow", "state", move |_, _| {
28083                let calls = Arc::clone(&observed);
28084                async move {
28085                    calls.fetch_add(1, Ordering::SeqCst);
28086                    if fail {
28087                        Err(Error::WorkerLoop("intentional query failure".to_string()))
28088                    } else {
28089                        Ok(json!({"state":"waiting"}))
28090                    }
28091                }
28092            });
28093            assert_eq!(worker.run_once().await.expect("query settled"), 1);
28094            assert_eq!(calls.load(Ordering::SeqCst), 1);
28095            let suffix = if fail { "fail" } else { "complete" };
28096            assert_identical_requests(
28097                &server,
28098                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
28099                8,
28100            );
28101            let other = if fail { "complete" } else { "fail" };
28102            assert_eq!(
28103                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
28104                0
28105            );
28106        }
28107    }
28108
28109    #[tokio::test]
28110    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
28111        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28112            storage_refusals: 7,
28113            storage_path: Some("/poll"),
28114            unauthorized_polls: true,
28115            ..MockWorkerBehavior::default()
28116        });
28117        let error = storage_worker(&server)
28118            .run_once()
28119            .await
28120            .expect_err("auth remains terminal");
28121        assert!(matches!(
28122            error,
28123            Error::Http {
28124                status: reqwest::StatusCode::UNAUTHORIZED,
28125                ..
28126            }
28127        ));
28128        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
28129
28130        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28131            storage_refusals: 7,
28132            storage_path: Some("/activity-cancel/complete"),
28133            ..MockWorkerBehavior::default()
28134        });
28135        let worker =
28136            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
28137        let error = worker
28138            .client
28139            .complete_activity_task(
28140                "activity-cancel",
28141                "attempt-cancel",
28142                "worker",
28143                json!({}),
28144                DEFAULT_CODEC,
28145            )
28146            .await
28147            .expect_err("cancellation remains terminal");
28148        assert!(activity_task_rejection_is_final(&error));
28149        assert_identical_requests(
28150            &server,
28151            "/api/worker/activity-tasks/activity-cancel/complete",
28152            8,
28153        );
28154
28155        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28156            storage_refusals: usize::MAX,
28157            storage_path: Some("/poll"),
28158            storage_wrong_poll_id: true,
28159            ..MockWorkerBehavior::default()
28160        });
28161        assert!(storage_worker(&server).run_once().await.is_err());
28162        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28163    }
28164
28165    #[tokio::test]
28166    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
28167        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28168            storage_refusals: usize::MAX,
28169            storage_path: Some("/poll"),
28170            ..MockWorkerBehavior::default()
28171        });
28172        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
28173        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
28174        let run = tokio::spawn(async move { worker.run().await });
28175        tokio::time::timeout(Duration::from_secs(2), async {
28176            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
28177                tokio::time::sleep(Duration::from_millis(1)).await;
28178            }
28179        })
28180        .await
28181        .expect("poll started");
28182        run.abort();
28183        assert!(run.await.expect_err("cancelled run").is_cancelled());
28184        tokio::time::sleep(Duration::from_millis(250)).await;
28185        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
28186    }
28187
28188    #[tokio::test]
28189    async fn query_protocol_rejection_from_older_server_is_typed() {
28190        let server = MockWorkerServer::reject_query_protocol();
28191        let client = Client::builder(server.base_url())
28192            .timeout(Duration::from_secs(2))
28193            .build()
28194            .expect("client");
28195
28196        let error = client
28197            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
28198            .await
28199            .expect_err("server below query protocol floor must reject");
28200        let Error::Protocol(failure) = error else {
28201            panic!("expected typed protocol failure");
28202        };
28203
28204        assert_eq!(failure.status, 400);
28205        assert_eq!(failure.reason, "unsupported_protocol_version");
28206        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
28207        assert_eq!(
28208            failure.requested_version.as_deref(),
28209            Some(WORKER_PROTOCOL_VERSION)
28210        );
28211        assert_eq!(
28212            server
28213                .worker_protocol_for("/api/worker/query-tasks/poll")
28214                .as_deref(),
28215            Some(WORKER_PROTOCOL_VERSION)
28216        );
28217    }
28218
28219    #[tokio::test]
28220    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
28221        let server = MockWorkerServer::reject_query_protocol();
28222        let client = Client::builder(server.base_url())
28223            .timeout(Duration::from_secs(2))
28224            .build()
28225            .expect("client");
28226        let mut worker = Worker::new(client, "rust-workers")
28227            .worker_id("baseline-worker")
28228            .poll_timeout(Duration::from_millis(10));
28229
28230        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
28231            Ok(Value::Null)
28232        });
28233
28234        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
28235        assert_eq!(
28236            server
28237                .worker_protocol_for("/api/worker/workflow-tasks/poll")
28238                .as_deref(),
28239            Some(WORKER_PROTOCOL_VERSION)
28240        );
28241        assert_eq!(
28242            server.worker_protocol_for("/api/worker/query-tasks/poll"),
28243            None,
28244            "a worker without query handlers must not use the query-task endpoint"
28245        );
28246    }
28247
28248    #[tokio::test]
28249    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
28250        let server = MockWorkerServer::reject_query_completion();
28251        let client = Client::builder(server.base_url())
28252            .timeout(Duration::from_secs(2))
28253            .build()
28254            .expect("client");
28255
28256        let error = client
28257            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
28258            .await
28259            .expect_err("expired completion must be rejected");
28260        let Error::QueryFailed(failure) = error else {
28261            panic!("expected typed query failure");
28262        };
28263        assert_eq!(failure.status, 409);
28264        assert_eq!(failure.reason, "query_task_timed_out");
28265
28266        let mut worker = Worker::new(client, "rust-workers")
28267            .worker_id("late-worker")
28268            .poll_timeout(Duration::from_millis(10));
28269        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28270        worker.register_query(
28271            "counter",
28272            "current",
28273            |_ctx, _args| async move { Ok(json!(8)) },
28274        );
28275
28276        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
28277        assert_eq!(
28278            worker
28279                .run_once()
28280                .await
28281                .expect("worker continues after late completion"),
28282            0
28283        );
28284        assert_eq!(
28285            server.request_count("/api/worker/query-tasks/query-late/complete"),
28286            2
28287        );
28288        assert_eq!(
28289            server.request_count("/api/worker/query-tasks/query-late/fail"),
28290            0,
28291            "a server completion rejection must not be reported as an encoding failure"
28292        );
28293    }
28294
28295    #[tokio::test]
28296    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
28297        let server = MockWorkerServer::start();
28298        let client = Client::builder(server.base_url())
28299            .timeout(Duration::from_secs(2))
28300            .build()
28301            .expect("client");
28302        let mut worker = Worker::new(client, "rust-workers")
28303            .worker_id("joined-worker")
28304            .poll_timeout(Duration::from_millis(10));
28305        worker.register_workflow(
28306            "joined.workflow",
28307            |_ctx, _input| async move { Ok(Value::Null) },
28308        );
28309        worker.register_activity(
28310            "joined.activity",
28311            |_ctx, _input| async move { Ok(Value::Null) },
28312        );
28313        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
28314            Ok(Value::Null)
28315        });
28316
28317        worker
28318            .run_until(tokio::time::sleep(Duration::from_millis(20)))
28319            .await
28320            .expect("normal shutdown");
28321
28322        let deregistration_path = "/api/worker/registrations/mock-worker";
28323        assert_eq!(server.request_count(deregistration_path), 1);
28324        for poll_path in [
28325            "/api/worker/workflow-tasks/poll",
28326            "/api/worker/activity-tasks/poll",
28327            "/api/worker/query-tasks/poll",
28328        ] {
28329            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
28330        }
28331        assert_eq!(
28332            server.captured_paths().last().map(String::as_str),
28333            Some(deregistration_path),
28334            "deregistration must start only after every poller has joined"
28335        );
28336    }
28337
28338    #[tokio::test]
28339    async fn registration_failure_does_not_deregister() {
28340        let server = MockWorkerServer::rejected_registration();
28341        let client = Client::builder(server.base_url())
28342            .timeout(Duration::from_secs(2))
28343            .build()
28344            .expect("client");
28345        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
28346
28347        let error = worker
28348            .run_until(async {})
28349            .await
28350            .expect_err("registration must fail");
28351        assert!(matches!(
28352            error,
28353            Error::Http {
28354                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28355                ..
28356            }
28357        ));
28358        assert!(server
28359            .captured_paths()
28360            .iter()
28361            .all(|path| !path.starts_with("/api/worker/registrations/")));
28362    }
28363
28364    #[tokio::test]
28365    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
28366        let server = MockWorkerServer::rejected_registration_protocol();
28367        let client = Client::builder(server.base_url())
28368            .timeout(Duration::from_secs(2))
28369            .build()
28370            .expect("client");
28371        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
28372
28373        let error = worker
28374            .run_until(async {})
28375            .await
28376            .expect_err("a protocol 1.16 server must reject this worker");
28377        let Error::Protocol(failure) = error else {
28378            panic!("expected typed protocol rejection");
28379        };
28380        assert_eq!(failure.reason, "unsupported_protocol_version");
28381        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
28382        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
28383        assert_eq!(
28384            server
28385                .worker_protocol_for("/api/worker/register")
28386                .as_deref(),
28387            Some(WORKER_PROTOCOL_VERSION)
28388        );
28389    }
28390
28391    #[tokio::test]
28392    async fn declined_registration_does_not_deregister() {
28393        let server = MockWorkerServer::declined_registration();
28394        let client = Client::builder(server.base_url())
28395            .timeout(Duration::from_secs(2))
28396            .build()
28397            .expect("client");
28398        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
28399
28400        let error = worker
28401            .run_until(async {})
28402            .await
28403            .expect_err("declined registration must fail");
28404        assert!(matches!(error, Error::WorkerLoop(_)));
28405        assert!(error.to_string().contains("was not accepted"));
28406        assert!(server
28407            .captured_paths()
28408            .iter()
28409            .all(|path| !path.starts_with("/api/worker/registrations/")));
28410    }
28411
28412    #[tokio::test]
28413    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
28414        let server = MockWorkerServer::rejected_deregistration();
28415        let client = Client::builder(server.base_url())
28416            .timeout(Duration::from_secs(2))
28417            .build()
28418            .expect("client");
28419        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
28420
28421        let error = worker
28422            .run_until(async {})
28423            .await
28424            .expect_err("deregistration must fail");
28425        assert!(matches!(
28426            error,
28427            Error::Http {
28428                status: reqwest::StatusCode::FORBIDDEN,
28429                ..
28430            }
28431        ));
28432        assert_eq!(
28433            server.request_count("/api/worker/registrations/mock-worker"),
28434            1
28435        );
28436    }
28437
28438    #[tokio::test]
28439    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
28440        let server = MockWorkerServer::rejected_deregistration_protocol();
28441        let client = Client::builder(server.base_url())
28442            .timeout(Duration::from_secs(2))
28443            .build()
28444            .expect("client");
28445        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
28446
28447        let error = worker
28448            .run_until(async {})
28449            .await
28450            .expect_err("protocol rejection must fail shutdown");
28451        let Error::Protocol(failure) = error else {
28452            panic!("expected typed protocol failure");
28453        };
28454        assert_eq!(failure.reason, "unsupported_protocol_version");
28455        assert_eq!(
28456            failure.requested_version.as_deref(),
28457            Some(WORKER_PROTOCOL_VERSION)
28458        );
28459        assert_eq!(
28460            server.request_count("/api/worker/registrations/mock-worker"),
28461            1
28462        );
28463    }
28464
28465    #[tokio::test]
28466    async fn primary_poller_error_retains_deregistration_failure_context() {
28467        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
28468        let client = Client::builder(server.base_url())
28469            .timeout(Duration::from_secs(2))
28470            .build()
28471            .expect("client");
28472        let mut worker = Worker::new(client, "rust-workers")
28473            .worker_id("combined-failure")
28474            .poll_timeout(Duration::from_millis(10));
28475        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
28476            Ok(Value::Null)
28477        });
28478
28479        let error = worker
28480            .run()
28481            .await
28482            .expect_err("worker and cleanup must fail");
28483        let summary = error.to_string();
28484        assert!(summary.contains("authentication_failed"));
28485        assert!(summary.contains("worker cannot deregister"));
28486        let Error::WorkerShutdown {
28487            primary,
28488            deregistration,
28489        } = error
28490        else {
28491            panic!("expected combined worker shutdown error");
28492        };
28493        assert!(matches!(
28494            *primary,
28495            Error::Http {
28496                status: reqwest::StatusCode::UNAUTHORIZED,
28497                ..
28498            }
28499        ));
28500        assert!(matches!(
28501            *deregistration,
28502            Error::Http {
28503                status: reqwest::StatusCode::FORBIDDEN,
28504                ..
28505            }
28506        ));
28507        assert_eq!(
28508            server.request_count("/api/worker/registrations/mock-worker"),
28509            1
28510        );
28511    }
28512
28513    #[tokio::test]
28514    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
28515        let server = MockWorkerServer::start();
28516        let client = Client::builder(server.base_url())
28517            .timeout(Duration::from_secs(2))
28518            .build()
28519            .expect("client");
28520        let mut worker = Worker::new(client, "rust-workers")
28521            .worker_id("activity-only-worker")
28522            .poll_timeout(Duration::from_millis(10));
28523
28524        worker.register_activity(
28525            "activity.only",
28526            |_ctx, _args| async move { Ok(Value::Null) },
28527        );
28528
28529        worker.run_until(async {}).await.expect("run worker");
28530    }
28531
28532    #[tokio::test]
28533    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
28534        let server = MockWorkerServer::start();
28535        let client = Client::builder(server.base_url())
28536            .timeout(Duration::from_secs(2))
28537            .build()
28538            .expect("client");
28539        let mut worker = Worker::new(client, "rust-workers")
28540            .worker_id("workflow-only-worker")
28541            .poll_timeout(Duration::from_millis(10));
28542
28543        worker.register_workflow(
28544            "workflow.only",
28545            |_ctx, _input| async move { Ok(Value::Null) },
28546        );
28547
28548        worker.run_until(async {}).await.expect("run worker");
28549    }
28550
28551    #[tokio::test]
28552    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
28553        let server = MockWorkerServer::start();
28554        let client = Client::builder(server.base_url())
28555            .timeout(Duration::from_secs(2))
28556            .build()
28557            .expect("client");
28558        let observations = Arc::new(Mutex::new(Vec::new()));
28559        let observed = Arc::clone(&observations);
28560        let mut worker = Worker::new(client, "rust-workers")
28561            .worker_id("observed-heartbeat-worker")
28562            .poll_timeout(Duration::from_millis(10))
28563            .on_worker_heartbeat(move |observation| {
28564                observed
28565                    .lock()
28566                    .expect("heartbeat observations")
28567                    .push(observation.clone());
28568            });
28569
28570        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
28571            Ok(Value::Null)
28572        });
28573        let acknowledged = Arc::clone(&observations);
28574        worker
28575            .run_until(async move {
28576                tokio::time::timeout(Duration::from_secs(2), async move {
28577                    loop {
28578                        if !acknowledged
28579                            .lock()
28580                            .expect("heartbeat observations")
28581                            .is_empty()
28582                        {
28583                            break;
28584                        }
28585                        tokio::time::sleep(Duration::from_millis(1)).await;
28586                    }
28587                })
28588                .await
28589                .expect("heartbeat acknowledgement within timeout");
28590            })
28591            .await
28592            .expect("run worker");
28593
28594        let observations = observations.lock().expect("heartbeat observations");
28595        let first = observations.first().expect("heartbeat acknowledgement");
28596        assert_eq!(first.worker_id, "observed-heartbeat-worker");
28597        assert_eq!(first.task_queue, "rust-workers");
28598        assert!(first.acknowledged_at_unix_millis > 0);
28599        assert_eq!(first.acknowledgement, json!({}));
28600    }
28601
28602    #[tokio::test]
28603    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
28604        let server = MockWorkerServer::delayed_heartbeat_worker();
28605        let client = Client::builder(server.base_url())
28606            .timeout(Duration::from_secs(3))
28607            .build()
28608            .expect("client");
28609        let observations = Arc::new(Mutex::new(Vec::new()));
28610        let observed = Arc::clone(&observations);
28611        let mut worker = Worker::new(client, "rust-snapshot-workers")
28612            .worker_id("rust-snapshot-worker")
28613            .poll_timeout(Duration::from_millis(10))
28614            .on_worker_heartbeat(move |observation| {
28615                observed
28616                    .lock()
28617                    .expect("heartbeat observations")
28618                    .push(observation.clone());
28619            });
28620
28621        worker.register_workflow("snapshot", |ctx, _input| async move {
28622            ctx.wait_signal("finish").await?;
28623            Ok(json!({"status": "finished"}))
28624        });
28625        worker.register_query("snapshot", "current", |ctx, _args| async move {
28626            Ok(json!(ctx
28627                .signals("increment")
28628                .iter()
28629                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28630                .sum::<i64>()))
28631        });
28632        worker.register_activity("cancel-aware", |_ctx, _args| async move {
28633            Ok(json!({"late": "completion"}))
28634        });
28635
28636        worker
28637            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
28638            .await
28639            .expect("delayed heartbeat must allow a clean worker shutdown");
28640
28641        let observations = observations.lock().expect("heartbeat observations");
28642        assert!(
28643            observations.len() >= 3,
28644            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
28645        );
28646        assert!(
28647            observations.windows(2).all(|pair| {
28648                pair[1].acknowledged_at_unix_millis
28649                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28650                    >= 850
28651            }),
28652            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
28653        );
28654        drop(observations);
28655
28656        let heartbeat_times = server.request_times("/api/worker/heartbeat");
28657        let delayed_request_at = *heartbeat_times
28658            .get(1)
28659            .expect("intentionally delayed heartbeat request");
28660        let delay_window_start = delayed_request_at + Duration::from_millis(100);
28661        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
28662        for path in [
28663            "/api/worker/workflow-tasks/poll",
28664            "/api/worker/activity-tasks/poll",
28665            "/api/worker/query-tasks/poll",
28666        ] {
28667            assert!(
28668                server
28669                    .request_times(path)
28670                    .iter()
28671                    .any(|received_at| *received_at >= delay_window_start
28672                        && *received_at <= delay_window_end),
28673                "{path} must keep polling while a heartbeat acknowledgement is delayed"
28674            );
28675        }
28676        assert!(
28677            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
28678            "workflow work must be settled"
28679        );
28680        assert!(
28681            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
28682            "activity work must be settled"
28683        );
28684        assert!(
28685            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
28686            "query work must be settled"
28687        );
28688    }
28689
28690    #[tokio::test]
28691    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
28692        let server = MockWorkerServer::heartbeat_retry_worker();
28693        let client = Client::builder(server.base_url())
28694            .timeout(Duration::from_secs(2))
28695            .build()
28696            .expect("client");
28697        let observations = Arc::new(Mutex::new(Vec::new()));
28698        let observed = Arc::clone(&observations);
28699        let worker = Worker::new(client, "rust-workers")
28700            .worker_id("heartbeat-retry-worker")
28701            .retry_policy(WorkerRetryPolicy {
28702                max_retries: 1,
28703                initial_backoff: Duration::from_millis(300),
28704                max_backoff: Duration::from_millis(300),
28705            })
28706            .on_worker_heartbeat(move |observation| {
28707                observed
28708                    .lock()
28709                    .expect("heartbeat observations")
28710                    .push(observation.clone());
28711            });
28712
28713        worker
28714            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
28715            .await
28716            .expect("retryable heartbeat failure must remain bounded and recover");
28717
28718        let observations = observations.lock().expect("heartbeat observations");
28719        assert!(observations.len() >= 3, "heartbeat retry must recover");
28720        assert!(
28721            observations.windows(2).all(|pair| {
28722                pair[1]
28723                    .acknowledged_at_unix_millis
28724                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28725                    >= 850
28726            }),
28727            "a successful retry must start a fresh advertised cadence: {observations:?}"
28728        );
28729        assert_eq!(
28730            server.request_count("/api/worker/heartbeat"),
28731            observations.len() + 1,
28732            "one retryable failure must add exactly one bounded request"
28733        );
28734    }
28735
28736    #[tokio::test]
28737    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
28738        let server = MockWorkerServer::waiting_query_worker();
28739        let client = Client::builder(server.base_url())
28740            .timeout(Duration::from_secs(2))
28741            .build()
28742            .expect("client");
28743        let observations = Arc::new(Mutex::new(Vec::new()));
28744        let observed = Arc::clone(&observations);
28745        let mut worker = Worker::new(client, "rust-snapshot-workers")
28746            .worker_id("rust-snapshot-worker")
28747            .poll_timeout(Duration::from_millis(10))
28748            .on_worker_heartbeat(move |observation| {
28749                observed
28750                    .lock()
28751                    .expect("heartbeat observations")
28752                    .push(observation.clone());
28753            });
28754
28755        worker.register_workflow("snapshot", |ctx, _input| async move {
28756            ctx.wait_signal("finish").await?;
28757            Ok(json!({"status": "finished"}))
28758        });
28759        worker.register_query("snapshot", "current", |ctx, _args| async move {
28760            let current = ctx
28761                .signals("increment")
28762                .iter()
28763                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28764                .sum::<i64>();
28765            Ok(json!(current))
28766        });
28767        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
28768        worker
28769            .declare_workflow_signals("snapshot", &["finish"])
28770            .expect("declare finish signal");
28771
28772        worker
28773            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
28774            .await
28775            .expect("pending workflow and query poller must remain live until shutdown");
28776
28777        assert!(
28778            observations.lock().expect("heartbeat observations").len() >= 4,
28779            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
28780        );
28781        assert!(
28782            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
28783            "workflow polling must continue after empty replay acknowledgements"
28784        );
28785        assert!(
28786            server.request_count("/api/worker/query-tasks/poll") >= 2,
28787            "query polling must continue after serving the current query"
28788        );
28789        assert_eq!(
28790            server.request_body("/api/worker/register")["capabilities"],
28791            json!([
28792                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
28793                DURABLE_SELECTION_CAPABILITY,
28794                MEMO_UPSERTS_CAPABILITY,
28795                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
28796                QUERY_TASKS_CAPABILITY,
28797                WORKFLOW_UPDATES_CAPABILITY,
28798                MESSAGE_STREAMS_CAPABILITY
28799            ])
28800        );
28801        assert_eq!(
28802            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
28803            json!({
28804                "queries": ["current"],
28805                "query_contracts": [{
28806                    "name": "current",
28807                    "parameters": [{
28808                        "name": "args", "position": 0, "required": false,
28809                        "variadic": true, "type": null, "allows_null": true,
28810                        "default_available": false, "default": null,
28811                    }],
28812                }],
28813                "signals": ["finish"],
28814                "signal_contracts": [{
28815                    "name": "finish",
28816                    "parameters": [{
28817                        "name": "args", "position": 0, "required": false,
28818                        "variadic": true, "type": null, "allows_null": true,
28819                        "default_available": false, "default": null,
28820                    }],
28821                }],
28822                "updates": ["replace"],
28823                "update_contracts": [{
28824                    "name": "replace",
28825                    "parameters": [{
28826                        "name": "args", "position": 0, "required": false,
28827                        "variadic": true, "type": null, "allows_null": true,
28828                        "default_available": false, "default": null,
28829                    }],
28830                }],
28831                "update_validators": [],
28832            })
28833        );
28834
28835        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
28836        assert_eq!(
28837            opened["commands"],
28838            json!([{
28839                "type": "open_signal_wait",
28840                "signal_name": "finish",
28841            }])
28842        );
28843
28844        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
28845            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
28846            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
28847            let failure = server.request_body(&fail_path);
28848            assert_eq!(
28849                failure["failure"]["type"],
28850                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
28851            );
28852            assert_eq!(server.request_count(&completion_path), 0);
28853        }
28854
28855        let query_completion =
28856            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
28857        assert_eq!(query_completion["result"], json!(8));
28858
28859        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
28860        assert_eq!(
28861            server.request_count(terminal_path),
28862            1,
28863            "the matching signal must settle the workflow exactly once"
28864        );
28865        let terminal = server.request_body(terminal_path);
28866        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
28867        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
28868        assert_eq!(
28869            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
28870                .expect("terminal workflow result"),
28871            json!({"status": "finished"})
28872        );
28873    }
28874
28875    #[tokio::test]
28876    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
28877        let server = MockWorkerServer::transient_worker_failures();
28878        let client = Client::builder(server.base_url())
28879            .timeout(Duration::from_secs(2))
28880            .build()
28881            .expect("client");
28882        let mut worker = Worker::new(client, "rust-workers")
28883            .worker_id("retry-worker")
28884            .poll_timeout(Duration::from_millis(10))
28885            .retry_policy(WorkerRetryPolicy {
28886                max_retries: 2,
28887                initial_backoff: Duration::from_millis(1),
28888                max_backoff: Duration::from_millis(1),
28889            });
28890        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28891        worker.register_activity(
28892            "counter.activity",
28893            |_ctx, _input| async move { Ok(Value::Null) },
28894        );
28895        worker.register_query(
28896            "counter",
28897            "current",
28898            |_ctx, _args| async move { Ok(json!(8)) },
28899        );
28900
28901        worker
28902            .run_until(tokio::time::sleep(Duration::from_millis(75)))
28903            .await
28904            .expect("transient failures must not stop the worker");
28905
28906        for path in [
28907            "/api/worker/heartbeat",
28908            "/api/worker/workflow-tasks/poll",
28909            "/api/worker/activity-tasks/poll",
28910            "/api/worker/query-tasks/poll",
28911        ] {
28912            assert!(
28913                server.request_count(path) >= 2,
28914                "{path} must continue after its transient failure"
28915            );
28916        }
28917    }
28918
28919    #[tokio::test]
28920    async fn worker_continues_after_long_poll_capacity_backpressure() {
28921        let server = MockWorkerServer::capacity_limited_activity_poll();
28922        let client = Client::builder(server.base_url())
28923            .timeout(Duration::from_secs(2))
28924            .build()
28925            .expect("client");
28926        let mut worker = Worker::new(client, "rust-workers")
28927            .worker_id("capacity-worker")
28928            .poll_timeout(Duration::from_millis(10))
28929            .retry_policy(WorkerRetryPolicy {
28930                max_retries: 0,
28931                initial_backoff: Duration::from_millis(1),
28932                max_backoff: Duration::from_millis(1),
28933            });
28934        worker.register_activity("capacity.activity", |_ctx, _input| async move {
28935            Ok(json!({"handled": true}))
28936        });
28937
28938        worker
28939            .run_until(tokio::time::sleep(Duration::from_millis(50)))
28940            .await
28941            .expect("capacity backpressure must not stop the worker");
28942
28943        assert!(
28944            server.request_count("/api/worker/activity-tasks/poll") >= 2,
28945            "the activity poller must continue after capacity backpressure"
28946        );
28947        assert_eq!(
28948            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
28949            1,
28950            "the worker must complete work returned after capacity recovers"
28951        );
28952    }
28953
28954    #[test]
28955    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
28956        let capacity = Error::Http {
28957            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28958            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
28959        };
28960        assert_eq!(
28961            worker_poll_capacity_retry_after(&capacity),
28962            Some(Duration::from_secs(3))
28963        );
28964
28965        let rejected_capacity = Error::Http {
28966            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28967            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
28968        };
28969        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
28970        assert!(!worker_operation_is_retryable(&rejected_capacity));
28971
28972        let ordinary_rate_limit = Error::Http {
28973            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28974            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
28975                .to_string(),
28976        };
28977        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
28978        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
28979    }
28980
28981    #[tokio::test]
28982    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
28983        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28984            poll_failures_per_path: 8,
28985            heartbeat_failures: 8,
28986            ..MockWorkerBehavior::default()
28987        });
28988        let client = Client::builder(server.base_url())
28989            .timeout(Duration::from_secs(2))
28990            .build()
28991            .expect("client");
28992        let acknowledgements = Arc::new(AtomicUsize::new(0));
28993        let observed = Arc::clone(&acknowledgements);
28994        let mut worker = Worker::new(client, "rust-workers")
28995            .recover_transient_outages(true)
28996            .poll_timeout(Duration::from_millis(10))
28997            .retry_policy(WorkerRetryPolicy {
28998                max_retries: 2,
28999                initial_backoff: Duration::from_millis(2),
29000                max_backoff: Duration::from_millis(5),
29001            })
29002            .on_worker_heartbeat(move |_| {
29003                observed.fetch_add(1, Ordering::SeqCst);
29004            });
29005        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29006        worker.register_activity(
29007            "counter.activity",
29008            |_ctx, _input| async move { Ok(Value::Null) },
29009        );
29010        worker.register_query("counter", "current", |_ctx, _args| async move {
29011            Ok(Value::Null)
29012        });
29013
29014        worker
29015            .run_until(tokio::time::sleep(Duration::from_millis(500)))
29016            .await
29017            .expect("a recoverable outage must not stop the service worker");
29018
29019        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
29020        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
29021        for path in [
29022            "/api/worker/workflow-tasks/poll",
29023            "/api/worker/activity-tasks/poll",
29024            "/api/worker/query-tasks/poll",
29025        ] {
29026            let bodies = server.request_bodies(path);
29027            assert!(bodies.len() >= 10, "{path} must resume after recovery");
29028            let first = &bodies[0]["poll_request_id"];
29029            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
29030            for body in &bodies[..9] {
29031                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
29032            }
29033            assert_ne!(&bodies[9]["poll_request_id"], first);
29034            let times = server.request_times(path);
29035            for pair in times[..9].windows(2) {
29036                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
29037            }
29038        }
29039    }
29040
29041    #[tokio::test]
29042    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
29043        for heartbeat_outage in [false, true] {
29044            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29045                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
29046                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
29047                ..MockWorkerBehavior::default()
29048            });
29049            let client = Client::builder(server.base_url()).build().expect("client");
29050            let mut worker = Worker::new(client, "rust-workers")
29051                .recover_transient_outages(true)
29052                .retry_policy(WorkerRetryPolicy {
29053                    max_retries: 1,
29054                    initial_backoff: Duration::from_secs(5),
29055                    max_backoff: Duration::from_secs(5),
29056                });
29057            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29058            let started = Instant::now();
29059            worker
29060                .run_until(tokio::time::sleep(Duration::from_millis(200)))
29061                .await
29062                .expect("shutdown during an outage is a normal stop");
29063            assert!(started.elapsed() < Duration::from_secs(1));
29064            let path = if heartbeat_outage {
29065                "/api/worker/heartbeat"
29066            } else {
29067                "/api/worker/workflow-tasks/poll"
29068            };
29069            assert_eq!(server.request_count(path), 1);
29070            assert_eq!(
29071                server.request_count("/api/worker/registrations/mock-worker"),
29072                1
29073            );
29074        }
29075    }
29076
29077    #[tokio::test]
29078    async fn worker_outage_recovery_keeps_run_once_bounded() {
29079        let server = MockWorkerServer::unavailable_polls();
29080        let client = Client::builder(server.base_url()).build().expect("client");
29081        let mut worker = Worker::new(client, "rust-workers")
29082            .recover_transient_outages(true)
29083            .retry_policy(WorkerRetryPolicy {
29084                max_retries: 2,
29085                initial_backoff: Duration::from_millis(1),
29086                max_backoff: Duration::from_millis(1),
29087            });
29088        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29089        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
29090        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
29091    }
29092
29093    #[tokio::test]
29094    async fn worker_outage_recovery_respects_disabled_retries() {
29095        let server = MockWorkerServer::unavailable_polls();
29096        let client = Client::builder(server.base_url()).build().expect("client");
29097        let mut worker = Worker::new(client, "rust-workers")
29098            .recover_transient_outages(true)
29099            .retry_policy(WorkerRetryPolicy {
29100                max_retries: 0,
29101                ..WorkerRetryPolicy::default()
29102            });
29103        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29104        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
29105        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29106    }
29107
29108    #[tokio::test]
29109    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
29110        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29111            heartbeat_failures: usize::MAX,
29112            unauthorized_polls: true,
29113            ..MockWorkerBehavior::default()
29114        });
29115        let client = Client::builder(server.base_url()).build().expect("client");
29116        let mut worker = Worker::new(client, "rust-workers")
29117            .recover_transient_outages(true)
29118            .retry_policy(WorkerRetryPolicy {
29119                max_retries: 1,
29120                initial_backoff: Duration::from_secs(5),
29121                max_backoff: Duration::from_secs(5),
29122            });
29123        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29124        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
29125            .await
29126            .expect("fatal poll errors must interrupt heartbeat recovery")
29127            .expect_err("authentication failure is terminal");
29128        assert!(
29129            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
29130        );
29131        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
29132    }
29133
29134    #[tokio::test]
29135    async fn worker_bounds_transport_retries() {
29136        let server = MockWorkerServer::unavailable_polls();
29137        let client = Client::builder(server.base_url())
29138            .timeout(Duration::from_secs(2))
29139            .build()
29140            .expect("client");
29141        let mut worker = Worker::new(client, "rust-workers")
29142            .worker_id("bounded-retry-worker")
29143            .poll_timeout(Duration::from_millis(10))
29144            .retry_policy(WorkerRetryPolicy {
29145                max_retries: 2,
29146                initial_backoff: Duration::from_millis(1),
29147                max_backoff: Duration::from_millis(1),
29148            });
29149        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29150
29151        let error = worker.run().await.expect_err("retry bound must terminate");
29152        assert!(matches!(error, Error::Transport(_)));
29153        assert_eq!(
29154            server.request_count("/api/worker/workflow-tasks/poll"),
29155            3,
29156            "one initial request plus exactly two retries"
29157        );
29158    }
29159
29160    #[tokio::test]
29161    async fn worker_retry_policy_can_disable_poll_retries() {
29162        let server = MockWorkerServer::unavailable_polls();
29163        let client = Client::builder(server.base_url())
29164            .timeout(Duration::from_secs(2))
29165            .build()
29166            .expect("client");
29167        let mut worker = Worker::new(client, "rust-workers")
29168            .worker_id("no-retry-worker")
29169            .poll_timeout(Duration::from_millis(10))
29170            .retry_policy(WorkerRetryPolicy {
29171                max_retries: 0,
29172                initial_backoff: Duration::from_millis(1),
29173                max_backoff: Duration::from_millis(1),
29174            });
29175        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29176
29177        let error = worker
29178            .run_once()
29179            .await
29180            .expect_err("disabled retries must return the first transport failure");
29181        assert!(matches!(error, Error::Transport(_)));
29182        assert_eq!(
29183            server.request_count("/api/worker/workflow-tasks/poll"),
29184            1,
29185            "max_retries=0 must send only the initial request"
29186        );
29187    }
29188
29189    #[tokio::test]
29190    async fn worker_does_not_retry_authentication_failures() {
29191        let server = MockWorkerServer::unauthorized_polls();
29192        let client = Client::builder(server.base_url())
29193            .timeout(Duration::from_secs(2))
29194            .build()
29195            .expect("client");
29196        let mut worker = Worker::new(client, "rust-workers")
29197            .worker_id("unauthorized-worker")
29198            .recover_transient_outages(true)
29199            .poll_timeout(Duration::from_millis(10));
29200        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29201
29202        let error = worker
29203            .run()
29204            .await
29205            .expect_err("authentication must terminate");
29206        let Error::Http { status, body } = error else {
29207            panic!("expected stable HTTP authentication error");
29208        };
29209        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
29210        assert!(body.contains("authentication_failed"));
29211        assert_eq!(
29212            server.request_count("/api/worker/workflow-tasks/poll"),
29213            1,
29214            "authentication failures must not be retried"
29215        );
29216    }
29217
29218    #[test]
29219    fn duplicate_registration_keeps_the_original_workflow() {
29220        let client = Client::new("http://127.0.0.1:9").expect("client");
29221        let mut worker = Worker::new(client, "registration-tests");
29222        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29223        let original = Arc::clone(&worker.workflows["same"].execute);
29224        worker
29225            .set_workflow_definition_sources("same", &["first workflow source"])
29226            .expect("source identity");
29227        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
29228        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
29229        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
29230        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
29231    }
29232
29233    #[test]
29234    fn duplicate_registration_keeps_the_original_activity() {
29235        let client = Client::new("http://127.0.0.1:9").expect("client");
29236        let mut worker = Worker::new(client, "registration-tests");
29237        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
29238        let original = Arc::clone(&worker.activities["same"]);
29239        worker.register_activity_avro_value("same", |_ctx, _input| async {
29240            Ok(AvroValue::String("second".into()))
29241        });
29242        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
29243    }
29244
29245    #[test]
29246    fn duplicate_registration_keeps_original_query_and_update_handlers() {
29247        let client = Client::new("http://127.0.0.1:9").expect("client");
29248        let mut worker = Worker::new(client, "registration-tests");
29249        worker.register_query("orders", "same", |_ctx, _input| async {
29250            Ok(json!("first"))
29251        });
29252        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
29253            panic!("snapshot query");
29254        };
29255        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
29256            Ok(json!("second"))
29257        });
29258        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
29259            panic!("duplicate replaced the query adapter");
29260        };
29261        assert!(Arc::ptr_eq(&original, retained));
29262        worker.register_update("orders", "same", |_ctx, _input| async {
29263            Ok(json!("first"))
29264        });
29265        let original = Arc::clone(&worker.updates["orders"]["same"]);
29266        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
29267            Ok(AvroValue::Null)
29268        });
29269        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
29270    }
29271
29272    #[tokio::test]
29273    async fn duplicate_registration_fails_before_server_contact() {
29274        let server = MockWorkerServer::start();
29275        let client = Client::builder(server.base_url()).build().expect("client");
29276        let mut worker =
29277            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
29278        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29279        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
29280        let error = worker
29281            .run_once()
29282            .await
29283            .expect_err("ambiguous worker must not poll");
29284        assert!(
29285            error.to_string().contains("duplicate_registration"),
29286            "{error}"
29287        );
29288        assert!(server.requests.lock().expect("requests").is_empty());
29289    }
29290
29291    #[derive(Clone, Debug)]
29292    struct CapturedRequest {
29293        headers: String,
29294        method: String,
29295        path: String,
29296        authorization: Option<String>,
29297        namespace: Option<String>,
29298        worker_protocol: Option<String>,
29299        control_protocol: Option<String>,
29300        body: String,
29301        received_at: Instant,
29302    }
29303
29304    struct MockWorkerServer {
29305        addr: SocketAddr,
29306        stop: Arc<AtomicBool>,
29307        requests: Arc<Mutex<Vec<CapturedRequest>>>,
29308        thread: Option<thread::JoinHandle<()>>,
29309    }
29310
29311    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
29312
29313    #[derive(Clone, Copy, Default)]
29314    struct MockWorkerBehavior {
29315        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
29316        request_override: Option<RequestOverride>,
29317        storage_refusals: usize,
29318        storage_path: Option<&'static str>,
29319        storage_unavailable: bool,
29320        storage_mid_poll: bool,
29321        storage_activity: bool,
29322        storage_query: bool,
29323        storage_wrong_poll_id: bool,
29324        reject_query_protocol: bool,
29325        reject_query_completion: bool,
29326        waiting_query_worker: bool,
29327        decline_registration: bool,
29328        complete_named_signal: bool,
29329        poll_failures_per_path: usize,
29330        long_poll_capacity_responses_per_path: usize,
29331        heartbeat_failures: usize,
29332        heartbeat_failure_request: Option<usize>,
29333        delayed_heartbeat_request: Option<usize>,
29334        heartbeat_response_delay: Duration,
29335        concurrent_requests: bool,
29336        unauthorized_polls: bool,
29337        reject_registration: bool,
29338        reject_registration_protocol: bool,
29339        reject_deregistration: bool,
29340        reject_deregistration_protocol: bool,
29341        cancelled_activity: bool,
29342        draining_polls: bool,
29343        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
29344        workflow_completion_status: Option<&'static str>,
29345        workflow_completion_body: Option<&'static str>,
29346    }
29347
29348    impl MockWorkerServer {
29349        fn start() -> Self {
29350            Self::start_with_behavior(MockWorkerBehavior::default())
29351        }
29352
29353        fn reject_query_protocol() -> Self {
29354            Self::start_with_behavior(MockWorkerBehavior {
29355                reject_query_protocol: true,
29356                ..MockWorkerBehavior::default()
29357            })
29358        }
29359
29360        fn reject_query_completion() -> Self {
29361            Self::start_with_behavior(MockWorkerBehavior {
29362                reject_query_completion: true,
29363                ..MockWorkerBehavior::default()
29364            })
29365        }
29366
29367        fn waiting_query_worker() -> Self {
29368            Self::start_with_behavior(MockWorkerBehavior {
29369                waiting_query_worker: true,
29370                complete_named_signal: true,
29371                ..MockWorkerBehavior::default()
29372            })
29373        }
29374
29375        fn transient_worker_failures() -> Self {
29376            Self::start_with_behavior(MockWorkerBehavior {
29377                poll_failures_per_path: 1,
29378                heartbeat_failures: 1,
29379                ..MockWorkerBehavior::default()
29380            })
29381        }
29382
29383        fn consecutive_poll_failures(count: usize) -> Self {
29384            Self::start_with_behavior(MockWorkerBehavior {
29385                poll_failures_per_path: count,
29386                ..MockWorkerBehavior::default()
29387            })
29388        }
29389
29390        fn capacity_limited_activity_poll() -> Self {
29391            Self::start_with_behavior(MockWorkerBehavior {
29392                long_poll_capacity_responses_per_path: 1,
29393                ..MockWorkerBehavior::default()
29394            })
29395        }
29396
29397        fn delayed_heartbeat_worker() -> Self {
29398            Self::start_with_behavior(MockWorkerBehavior {
29399                waiting_query_worker: true,
29400                delayed_heartbeat_request: Some(2),
29401                heartbeat_response_delay: Duration::from_millis(1_500),
29402                concurrent_requests: true,
29403                cancelled_activity: true,
29404                ..MockWorkerBehavior::default()
29405            })
29406        }
29407
29408        fn heartbeat_retry_worker() -> Self {
29409            Self::start_with_behavior(MockWorkerBehavior {
29410                waiting_query_worker: true,
29411                heartbeat_failure_request: Some(2),
29412                concurrent_requests: true,
29413                ..MockWorkerBehavior::default()
29414            })
29415        }
29416
29417        fn unavailable_polls() -> Self {
29418            Self::start_with_behavior(MockWorkerBehavior {
29419                poll_failures_per_path: usize::MAX,
29420                ..MockWorkerBehavior::default()
29421            })
29422        }
29423
29424        fn unauthorized_polls() -> Self {
29425            Self::start_with_behavior(MockWorkerBehavior {
29426                unauthorized_polls: true,
29427                ..MockWorkerBehavior::default()
29428            })
29429        }
29430
29431        fn rejected_registration() -> Self {
29432            Self::start_with_behavior(MockWorkerBehavior {
29433                reject_registration: true,
29434                ..MockWorkerBehavior::default()
29435            })
29436        }
29437
29438        fn rejected_registration_protocol() -> Self {
29439            Self::start_with_behavior(MockWorkerBehavior {
29440                reject_registration_protocol: true,
29441                ..MockWorkerBehavior::default()
29442            })
29443        }
29444
29445        fn declined_registration() -> Self {
29446            Self::start_with_behavior(MockWorkerBehavior {
29447                decline_registration: true,
29448                ..MockWorkerBehavior::default()
29449            })
29450        }
29451
29452        fn rejected_deregistration() -> Self {
29453            Self::start_with_behavior(MockWorkerBehavior {
29454                reject_deregistration: true,
29455                ..MockWorkerBehavior::default()
29456            })
29457        }
29458
29459        fn rejected_deregistration_protocol() -> Self {
29460            Self::start_with_behavior(MockWorkerBehavior {
29461                reject_deregistration_protocol: true,
29462                ..MockWorkerBehavior::default()
29463            })
29464        }
29465
29466        fn unauthorized_polls_and_rejected_deregistration() -> Self {
29467            Self::start_with_behavior(MockWorkerBehavior {
29468                unauthorized_polls: true,
29469                reject_deregistration: true,
29470                ..MockWorkerBehavior::default()
29471            })
29472        }
29473
29474        fn cancelled_activity() -> Self {
29475            Self::start_with_behavior(MockWorkerBehavior {
29476                cancelled_activity: true,
29477                ..MockWorkerBehavior::default()
29478            })
29479        }
29480
29481        fn draining_polls() -> Self {
29482            Self::start_with_behavior(MockWorkerBehavior {
29483                draining_polls: true,
29484                ..MockWorkerBehavior::default()
29485            })
29486        }
29487
29488        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
29489            Self::start_with_behavior(MockWorkerBehavior {
29490                invalid_task_payload_codec: Some(codec),
29491                ..MockWorkerBehavior::default()
29492            })
29493        }
29494
29495        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
29496            Self::start_with_behavior(MockWorkerBehavior {
29497                workflow_completion_status: Some(status),
29498                workflow_completion_body: Some(body),
29499                ..MockWorkerBehavior::default()
29500            })
29501        }
29502
29503        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
29504            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
29505            listener
29506                .set_nonblocking(true)
29507                .expect("configure mock listener");
29508            let addr = listener.local_addr().expect("mock server address");
29509            let stop = Arc::new(AtomicBool::new(false));
29510            let server_stop = Arc::clone(&stop);
29511            let requests = Arc::new(Mutex::new(Vec::new()));
29512            let server_requests = Arc::clone(&requests);
29513            let thread = thread::spawn(move || {
29514                let mut request_threads = Vec::new();
29515                while !server_stop.load(Ordering::SeqCst) {
29516                    match listener.accept() {
29517                        Ok((mut stream, _)) => {
29518                            if behavior.concurrent_requests {
29519                                let requests = Arc::clone(&server_requests);
29520                                request_threads.push(thread::spawn(move || {
29521                                    handle_mock_worker_request(&mut stream, &requests, behavior)
29522                                }));
29523                            } else {
29524                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
29525                            }
29526                        }
29527                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
29528                            let mut index = 0;
29529                            while index < request_threads.len() {
29530                                if request_threads[index].is_finished() {
29531                                    request_threads
29532                                        .swap_remove(index)
29533                                        .join()
29534                                        .expect("join mock request");
29535                                } else {
29536                                    index += 1;
29537                                }
29538                            }
29539                            thread::sleep(Duration::from_millis(5));
29540                        }
29541                        Err(_) => break,
29542                    }
29543                }
29544                for request_thread in request_threads {
29545                    request_thread.join().expect("join mock request");
29546                }
29547            });
29548
29549            Self {
29550                addr,
29551                stop,
29552                requests,
29553                thread: Some(thread),
29554            }
29555        }
29556
29557        fn base_url(&self) -> String {
29558            format!("http://{}", self.addr)
29559        }
29560
29561        fn worker_protocol_for(&self, path: &str) -> Option<String> {
29562            self.requests
29563                .lock()
29564                .expect("captured requests")
29565                .iter()
29566                .find(|request| request.path == path)
29567                .and_then(|request| request.worker_protocol.clone())
29568        }
29569
29570        fn control_protocol_for(&self, path: &str) -> Option<String> {
29571            self.requests
29572                .lock()
29573                .expect("captured requests")
29574                .iter()
29575                .find(|request| request.path == path)
29576                .and_then(|request| request.control_protocol.clone())
29577        }
29578
29579        fn method_for(&self, path: &str) -> Option<String> {
29580            self.requests
29581                .lock()
29582                .expect("captured requests")
29583                .iter()
29584                .find(|request| request.path == path)
29585                .map(|request| request.method.clone())
29586        }
29587
29588        fn authorization_for(&self, path: &str) -> Option<String> {
29589            self.requests
29590                .lock()
29591                .expect("captured requests")
29592                .iter()
29593                .find(|request| request.path == path)
29594                .and_then(|request| request.authorization.clone())
29595        }
29596
29597        fn namespace_for(&self, path: &str) -> Option<String> {
29598            self.requests
29599                .lock()
29600                .expect("captured requests")
29601                .iter()
29602                .find(|request| request.path == path)
29603                .and_then(|request| request.namespace.clone())
29604        }
29605
29606        fn request_count(&self, path: &str) -> usize {
29607            self.requests
29608                .lock()
29609                .expect("captured requests")
29610                .iter()
29611                .filter(|request| request.path == path)
29612                .count()
29613        }
29614
29615        fn captured_paths(&self) -> Vec<String> {
29616            self.requests
29617                .lock()
29618                .expect("captured requests")
29619                .iter()
29620                .map(|request| request.path.clone())
29621                .collect()
29622        }
29623
29624        fn request_times(&self, path: &str) -> Vec<Instant> {
29625            self.requests
29626                .lock()
29627                .expect("captured requests")
29628                .iter()
29629                .filter(|request| request.path == path)
29630                .map(|request| request.received_at)
29631                .collect()
29632        }
29633
29634        fn request_body(&self, path: &str) -> Value {
29635            let requests = self.requests.lock().expect("captured requests");
29636            let body = &requests
29637                .iter()
29638                .find(|request| request.path == path)
29639                .unwrap_or_else(|| panic!("missing request for {path}"))
29640                .body;
29641            serde_json::from_str(body).unwrap_or_else(|error| {
29642                panic!("invalid JSON request body for {path}: {error}: {body:?}")
29643            })
29644        }
29645
29646        fn request_bodies(&self, path: &str) -> Vec<Value> {
29647            self.requests
29648                .lock()
29649                .expect("captured requests")
29650                .iter()
29651                .filter(|request| request.path == path)
29652                .map(|request| {
29653                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
29654                        panic!(
29655                            "invalid JSON request body for {path}: {error}: {:?}",
29656                            request.body
29657                        )
29658                    })
29659                })
29660                .collect()
29661        }
29662    }
29663
29664    impl Drop for MockWorkerServer {
29665        fn drop(&mut self) {
29666            self.stop.store(true, Ordering::SeqCst);
29667            let _ = TcpStream::connect(self.addr);
29668
29669            if let Some(thread) = self.thread.take() {
29670                thread.join().expect("join mock server");
29671            }
29672        }
29673    }
29674
29675    fn handle_mock_worker_request(
29676        stream: &mut TcpStream,
29677        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
29678        behavior: MockWorkerBehavior,
29679    ) {
29680        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
29681        let mut buffer = [0_u8; 8192];
29682        let mut request = Vec::new();
29683
29684        loop {
29685            match stream.read(&mut buffer) {
29686                Ok(0) => break,
29687                Ok(read) => {
29688                    request.extend_from_slice(&buffer[..read]);
29689                    if mock_request_is_complete(&request) {
29690                        break;
29691                    }
29692                }
29693                Err(error)
29694                    if matches!(
29695                        error.kind(),
29696                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
29697                    ) =>
29698                {
29699                    break;
29700                }
29701                Err(_) => return,
29702            }
29703        }
29704
29705        let request = String::from_utf8_lossy(&request);
29706        let body = request
29707            .split_once("\r\n\r\n")
29708            .map(|(_, body)| body)
29709            .unwrap_or_default();
29710        let path = request
29711            .lines()
29712            .next()
29713            .and_then(|line| line.split_whitespace().nth(1))
29714            .unwrap_or_default();
29715        let method = request
29716            .lines()
29717            .next()
29718            .and_then(|line| line.split_whitespace().next())
29719            .unwrap_or_default();
29720        let authorization = request.lines().find_map(|line| {
29721            let (name, value) = line.split_once(':')?;
29722            name.eq_ignore_ascii_case("Authorization")
29723                .then(|| value.trim().to_string())
29724        });
29725        let namespace = request.lines().find_map(|line| {
29726            let (name, value) = line.split_once(':')?;
29727            name.eq_ignore_ascii_case("X-Namespace")
29728                .then(|| value.trim().to_string())
29729        });
29730        let worker_protocol = request.lines().find_map(|line| {
29731            let (name, value) = line.split_once(':')?;
29732            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
29733                .then(|| value.trim().to_string())
29734        });
29735        let control_protocol = request.lines().find_map(|line| {
29736            let (name, value) = line.split_once(':')?;
29737            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
29738                .then(|| value.trim().to_string())
29739        });
29740        let request_number = {
29741            let mut requests = requests.lock().expect("captured requests");
29742            requests.push(CapturedRequest {
29743                headers: request
29744                    .split_once("\r\n\r\n")
29745                    .map_or("", |(headers, _)| headers)
29746                    .to_owned(),
29747                method: method.to_string(),
29748                path: path.to_string(),
29749                authorization,
29750                namespace,
29751                worker_protocol: worker_protocol.clone(),
29752                control_protocol,
29753                body: body.to_string(),
29754                received_at: Instant::now(),
29755            });
29756            requests
29757                .iter()
29758                .filter(|request| request.path == path)
29759                .count()
29760        };
29761
29762        if let Some(response) = behavior
29763            .request_override
29764            .and_then(|handler| handler(path, body, request_number))
29765        {
29766            write_mock_response(stream, response.0, &response.1);
29767            return;
29768        }
29769        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
29770            write_mock_response(stream, response.0, &response.1);
29771            return;
29772        }
29773        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
29774            return;
29775        }
29776        let pressure_path = behavior
29777            .storage_path
29778            .is_some_and(|part| path.contains(part));
29779        let prior_failures = if path.ends_with("/poll") {
29780            behavior.poll_failures_per_path
29781        } else {
29782            0
29783        };
29784        if pressure_path
29785            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
29786        {
29787            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
29788            let poll_id = path
29789                .ends_with("/poll")
29790                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
29791            let mut refusal = storage_refusal(
29792                poll_id,
29793                behavior.storage_unavailable,
29794                behavior.storage_mid_poll,
29795            );
29796            if behavior.storage_wrong_poll_id {
29797                refusal["poll_request_id"] = json!("wrong-poll");
29798            }
29799            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
29800            return;
29801        }
29802        if path.contains("/storage-task/")
29803            || path.contains("/storage-activity/")
29804            || path.contains("/storage-query/")
29805        {
29806            write_mock_response(stream, "200 OK", "{}");
29807            return;
29808        }
29809        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
29810            write_mock_response(stream, "200 OK", &json!({"task":{
29811                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
29812                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
29813                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29814                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29815                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
29816            }}).to_string());
29817            return;
29818        }
29819        if behavior.storage_activity
29820            && path == "/api/worker/activity-tasks/poll"
29821            && request_number == 1
29822        {
29823            write_mock_response(stream, "200 OK", &json!({"task":{
29824                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
29825                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29826                "attempt_number":7, "lease_owner":"storage-worker"
29827            }}).to_string());
29828            return;
29829        }
29830
29831        if path == "/api/worker/register" {
29832            if behavior.reject_registration_protocol {
29833                write_mock_response(
29834                    stream,
29835                    "400 Bad Request",
29836                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
29837                );
29838                return;
29839            }
29840            if behavior.reject_registration {
29841                write_mock_response(
29842                    stream,
29843                    "503 Service Unavailable",
29844                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
29845                );
29846                return;
29847            }
29848        }
29849
29850        if path.starts_with("/api/worker/registrations/") {
29851            if behavior.reject_deregistration_protocol {
29852                write_mock_response(
29853                    stream,
29854                    "400 Bad Request",
29855                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
29856                );
29857            } else if behavior.reject_deregistration {
29858                write_mock_response(
29859                    stream,
29860                    "403 Forbidden",
29861                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
29862                );
29863            } else {
29864                write_mock_response(
29865                    stream,
29866                    "200 OK",
29867                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
29868                );
29869            }
29870            return;
29871        }
29872
29873        let is_poll = matches!(
29874            path,
29875            "/api/worker/workflow-tasks/poll"
29876                | "/api/worker/activity-tasks/poll"
29877                | "/api/worker/query-tasks/poll"
29878        );
29879        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
29880            write_mock_response(
29881                stream,
29882                "429 Too Many Requests",
29883                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
29884            );
29885            return;
29886        }
29887        if is_poll && request_number <= behavior.poll_failures_per_path {
29888            return;
29889        }
29890        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
29891            return;
29892        }
29893        if path == "/api/worker/heartbeat"
29894            && behavior.heartbeat_failure_request == Some(request_number)
29895        {
29896            return;
29897        }
29898        if path == "/api/worker/heartbeat"
29899            && behavior.delayed_heartbeat_request == Some(request_number)
29900        {
29901            thread::sleep(behavior.heartbeat_response_delay);
29902        }
29903        if behavior.unauthorized_polls && is_poll {
29904            write_mock_response(
29905                stream,
29906                "401 Unauthorized",
29907                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
29908            );
29909            return;
29910        }
29911        if behavior.draining_polls && is_poll {
29912            write_mock_response(
29913                stream,
29914                "409 Conflict",
29915                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
29916            );
29917            return;
29918        }
29919
29920        if let Some(codec_case) = behavior.invalid_task_payload_codec {
29921            if is_poll && request_number == 1 {
29922                let mut task = match path {
29923                    "/api/worker/workflow-tasks/poll" => json!({
29924                        "task_id": "codec-workflow",
29925                        "workflow_type": "codec.workflow",
29926                        "payload_codec": DEFAULT_CODEC,
29927                        "workflow_task_attempt": 1,
29928                        "lease_owner": "codec-worker"
29929                    }),
29930                    "/api/worker/activity-tasks/poll" => json!({
29931                        "task_id": "codec-activity",
29932                        "activity_attempt_id": "codec-activity-attempt",
29933                        "activity_type": "codec.activity",
29934                        "payload_codec": DEFAULT_CODEC,
29935                        "attempt_number": 1,
29936                        "lease_owner": "codec-worker"
29937                    }),
29938                    "/api/worker/query-tasks/poll" => json!({
29939                        "query_task_id": "codec-query",
29940                        "query_task_attempt": 1,
29941                        "workflow_type": "codec.workflow",
29942                        "query_name": "known",
29943                        "payload_codec": DEFAULT_CODEC,
29944                        "lease_owner": "codec-worker"
29945                    }),
29946                    _ => unreachable!("is_poll limits task codec probe paths"),
29947                };
29948                codec_case.apply(&mut task);
29949                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
29950                return;
29951            }
29952
29953            if matches!(
29954                path,
29955                "/api/worker/workflow-tasks/codec-workflow/fail"
29956                    | "/api/worker/activity-tasks/codec-activity/fail"
29957                    | "/api/worker/query-tasks/codec-query/fail"
29958            ) {
29959                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
29960                return;
29961            }
29962        }
29963
29964        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
29965            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
29966            let body = format!(
29967                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
29968            );
29969            write_mock_response(stream, "400 Bad Request", &body);
29970            return;
29971        }
29972
29973        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
29974        {
29975            write_mock_response(
29976                stream,
29977                "409 Conflict",
29978                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
29979            );
29980            return;
29981        }
29982
29983        if behavior.workflow_completion_status.is_some()
29984            && path == "/api/worker/workflow-tasks/poll"
29985            && request_number == 1
29986        {
29987            write_mock_response(
29988                stream,
29989                "200 OK",
29990                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"}}"#,
29991            );
29992            return;
29993        }
29994
29995        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
29996            if let (Some(status), Some(body)) = (
29997                behavior.workflow_completion_status,
29998                behavior.workflow_completion_body,
29999            ) {
30000                write_mock_response(stream, status, body);
30001                return;
30002            }
30003        }
30004
30005        if behavior.waiting_query_worker {
30006            if behavior.complete_named_signal
30007                && path == "/api/worker/workflow-tasks/poll"
30008                && request_number == 1
30009            {
30010                let body = json!({
30011                    "task": {
30012                        "task_id": "snapshot-open",
30013                        "workflow_id": "snapshot-1",
30014                        "run_id": "snapshot-run-1",
30015                        "workflow_type": "snapshot",
30016                        "payload_codec": DEFAULT_CODEC,
30017                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30018                            .expect("Avro workflow arguments"),
30019                        "history_events": [],
30020                        "workflow_task_attempt": 1,
30021                        "lease_owner": "rust-snapshot-worker"
30022                    }
30023                })
30024                .to_string();
30025                write_mock_response(stream, "200 OK", &body);
30026                return;
30027            }
30028
30029            let signal_request = request_number - usize::from(behavior.complete_named_signal);
30030            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
30031            if path == "/api/worker/workflow-tasks/poll"
30032                && signal_request >= 1
30033                && signal_request <= signal_request_limit
30034            {
30035                let finish = behavior.complete_named_signal && signal_request == 3;
30036                let amounts = if signal_request == 1 {
30037                    vec![3]
30038                } else {
30039                    vec![3, 5]
30040                };
30041                let task_id = if signal_request == 1 {
30042                    "snapshot-wait-3"
30043                } else if finish {
30044                    "snapshot-finish"
30045                } else {
30046                    "snapshot-wait-5"
30047                };
30048                let mut history_events = std::iter::once(json!({
30049                    "event_type": "SignalWaitOpened",
30050                    "payload": {"sequence": 1, "signal_name": "finish"}
30051                }))
30052                .chain(amounts.iter().enumerate().map(|(index, amount)| {
30053                    json!({
30054                        "event_type": "SignalReceived",
30055                        "payload": {
30056                            "signal_id": format!("increment-{amount}"),
30057                            "signal_name": "increment",
30058                            "workflow_sequence": index + 2,
30059                            "payload_codec": DEFAULT_CODEC,
30060                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30061                                .expect("Avro signal envelope")
30062                        }
30063                    })
30064                }))
30065                .collect::<Vec<_>>();
30066                let (resume_id, resume_name, resume_arguments) = if finish {
30067                    history_events.push(json!({
30068                        "event_type": "SignalReceived",
30069                        "payload": {
30070                            "signal_id": "finish",
30071                            "signal_name": "finish",
30072                            "workflow_sequence": 4,
30073                            "payload_codec": DEFAULT_CODEC,
30074                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30075                                .expect("Avro finish signal envelope")
30076                        }
30077                    }));
30078                    (
30079                        "finish".to_string(),
30080                        "finish".to_string(),
30081                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
30082                            .expect("Avro finish resume signal"),
30083                    )
30084                } else {
30085                    let amount = amounts.last().expect("amount");
30086                    (
30087                        format!("increment-{amount}"),
30088                        "increment".to_string(),
30089                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30090                            .expect("Avro increment resume signal"),
30091                    )
30092                };
30093                let body = json!({
30094                    "task": {
30095                        "task_id": task_id,
30096                        "workflow_id": "snapshot-1",
30097                        "run_id": "snapshot-run-1",
30098                        "workflow_type": "snapshot",
30099                        "payload_codec": DEFAULT_CODEC,
30100                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30101                            .expect("Avro workflow arguments"),
30102                        "history_events": history_events,
30103                        "workflow_task_attempt": 1,
30104                        "workflow_signal_id": resume_id,
30105                        "signal_name": resume_name,
30106                        "signal_arguments": resume_arguments,
30107                        "lease_owner": "rust-snapshot-worker"
30108                    }
30109                })
30110                .to_string();
30111                write_mock_response(stream, "200 OK", &body);
30112                return;
30113            }
30114
30115            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
30116                let history_events = [3, 5]
30117                    .into_iter()
30118                    .enumerate()
30119                    .map(|(index, amount)| {
30120                        json!({
30121                            "event_type": "SignalReceived",
30122                            "payload": {
30123                                "signal_id": format!("increment-{amount}"),
30124                                "signal_name": "increment",
30125                                "workflow_sequence": index + 2,
30126                                "payload_codec": DEFAULT_CODEC,
30127                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
30128                                    .expect("Avro query signal envelope")
30129                            }
30130                        })
30131                    })
30132                    .collect::<Vec<_>>();
30133                let body = json!({
30134                    "task": {
30135                        "query_task_id": "snapshot-current",
30136                        "query_task_attempt": 1,
30137                        "lease_owner": "rust-snapshot-worker",
30138                        "workflow_id": "snapshot-1",
30139                        "run_id": "snapshot-run-1",
30140                        "workflow_type": "snapshot",
30141                        "query_name": "current",
30142                        "payload_codec": DEFAULT_CODEC,
30143                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30144                            .expect("Avro workflow arguments"),
30145                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
30146                            .expect("Avro query arguments"),
30147                        "history_events": history_events,
30148                        "run_status": "waiting"
30149                    }
30150                })
30151                .to_string();
30152                write_mock_response(stream, "200 OK", &body);
30153                return;
30154            }
30155
30156            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
30157                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
30158            {
30159                write_mock_response(
30160                    stream,
30161                    "200 OK",
30162                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
30163                );
30164                return;
30165            }
30166
30167            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
30168                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
30169                return;
30170            }
30171
30172            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
30173                write_mock_response(
30174                    stream,
30175                    "200 OK",
30176                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
30177                );
30178                return;
30179            }
30180
30181            if path == "/api/worker/query-tasks/snapshot-current/complete" {
30182                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
30183                return;
30184            }
30185        }
30186
30187        if matches!(
30188            path,
30189            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
30190        ) {
30191            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30192                .expect("typed mock result");
30193            let body = json!({
30194                "result": typed_fidelity_probe().into_json().expect("result projection"),
30195                "result_envelope": result,
30196            })
30197            .to_string();
30198            write_mock_response(stream, "200 OK", &body);
30199            return;
30200        }
30201
30202        if path == "/api/workflows/typed-1" {
30203            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30204                .expect("typed mock result");
30205            let body = json!({
30206                "workflow_id": "typed-1",
30207                "run_id": "run-typed-1",
30208                "workflow_type": "typed.echo",
30209                "status": "completed",
30210                "output": typed_fidelity_probe().into_json().expect("output projection"),
30211                "output_envelope": result,
30212            })
30213            .to_string();
30214            write_mock_response(stream, "200 OK", &body);
30215            return;
30216        }
30217
30218        let (status, body) = match path {
30219            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
30220            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
30221            "/api/workflows" => (
30222                "201 Created",
30223                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
30224            ),
30225            "/api/worker/register" if behavior.decline_registration => (
30226                "200 OK",
30227                r#"{"worker_id":"declined-worker","registered":false}"#,
30228            ),
30229            "/api/worker/register" if behavior.waiting_query_worker => (
30230                "200 OK",
30231                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
30232            ),
30233            "/api/worker/register" => (
30234                "200 OK",
30235                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
30236            ),
30237            "/api/worker/heartbeat" => ("200 OK", "{}"),
30238            "/api/worker/activity-tasks/poll"
30239                if behavior.cancelled_activity && request_number == 1 =>
30240            {
30241                (
30242                    "200 OK",
30243                    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"}}"#,
30244                )
30245            }
30246            "/api/worker/activity-tasks/poll"
30247                if behavior.long_poll_capacity_responses_per_path > 0
30248                    && request_number
30249                        == behavior
30250                            .long_poll_capacity_responses_per_path
30251                            .saturating_add(1) =>
30252            {
30253                (
30254                    "200 OK",
30255                    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"}}"#,
30256                )
30257            }
30258            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
30259                ("200 OK", r#"{"task":null}"#)
30260            }
30261            "/api/worker/query-tasks/poll"
30262                if behavior.reject_query_completion && request_number == 1 =>
30263            {
30264                (
30265                    "200 OK",
30266                    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"}}"#,
30267                )
30268            }
30269            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
30270            "/api/worker/query-tasks/query-capture/complete"
30271            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
30272            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
30273                "200 OK",
30274                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
30275            ),
30276            "/api/worker/activity-tasks/activity-cancel/complete" => (
30277                "409 Conflict",
30278                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
30279            ),
30280            "/api/worker/activity-tasks/activity-typed/complete"
30281            | "/api/worker/activity-tasks/activity-typed/fail"
30282            | "/api/worker/activity-tasks/capacity-activity/complete"
30283            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
30284            "/api/workflows/counter-1/query/current" => (
30285                "200 OK",
30286                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
30287            ),
30288            "/api/workflows/counter-1/query/missing" => (
30289                "404 Not Found",
30290                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
30291            ),
30292            "/api/workflows/wf-lifecycle/cancel" => (
30293                "200 OK",
30294                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
30295            ),
30296            "/api/workflows/wf-lifecycle/terminate" => (
30297                "200 OK",
30298                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
30299            ),
30300            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
30301                "200 OK",
30302                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
30303            ),
30304            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
30305                "200 OK",
30306                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
30307            ),
30308            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
30309                "202 Accepted",
30310                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
30311            ),
30312            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
30313                "200 OK",
30314                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}"#,
30315            ),
30316            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
30317                "409 Conflict",
30318                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
30319            ),
30320            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
30321            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
30322                "409 Conflict",
30323                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
30324            ),
30325            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
30326                "200 OK",
30327                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"}]}}"#,
30328            ),
30329            "/api/workflows/wf-cancelled" => (
30330                "200 OK",
30331                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
30332            ),
30333            "/api/workflows/wf-terminated" => (
30334                "200 OK",
30335                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
30336            ),
30337            "/api/workflows/wf-timed-out" => (
30338                "200 OK",
30339                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
30340            ),
30341            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
30342                "200 OK",
30343                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
30344            ),
30345            "/api/workflows/wf-selected" => (
30346                "200 OK",
30347                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
30348            ),
30349            "/api/workflows/wf-selected/runs/run-selected" => (
30350                "200 OK",
30351                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
30352            ),
30353            _ => ("404 Not Found", r#"{"message":"not found"}"#),
30354        };
30355        write_mock_response(stream, status, body);
30356    }
30357
30358    fn mock_request_is_complete(request: &[u8]) -> bool {
30359        let Some(header_end) = request
30360            .windows(4)
30361            .position(|window| window == b"\r\n\r\n")
30362            .map(|position| position + 4)
30363        else {
30364            return false;
30365        };
30366        let headers = String::from_utf8_lossy(&request[..header_end]);
30367        let content_length = headers.lines().find_map(|line| {
30368            let (name, value) = line.split_once(':')?;
30369            name.eq_ignore_ascii_case("content-length")
30370                .then(|| value.trim().parse::<usize>().ok())
30371                .flatten()
30372        });
30373
30374        request.len() >= header_end + content_length.unwrap_or(0)
30375    }
30376
30377    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
30378        let response = format!(
30379            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
30380            body.len()
30381        );
30382
30383        let _ = stream.write_all(response.as_bytes());
30384        let _ = stream.flush();
30385    }
30386
30387    fn activity_completion_backend_recovery(
30388        path: &str,
30389        _body: &str,
30390        request_number: usize,
30391    ) -> Option<(&'static str, String)> {
30392        match path {
30393            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
30394                "200 OK",
30395                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(),
30396            )),
30397            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
30398                "503 Service Unavailable",
30399                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(),
30400            )),
30401            "/api/worker/activity-tasks/recover-activity/complete" => Some((
30402                "200 OK",
30403                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30404            )),
30405            _ => None,
30406        }
30407    }
30408
30409    fn workflow_completion_backend_recovery(
30410        path: &str,
30411        _body: &str,
30412        request_number: usize,
30413    ) -> Option<(&'static str, String)> {
30414        match path {
30415            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
30416                "200 OK",
30417                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
30418            )),
30419            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
30420                "503 Service Unavailable",
30421                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(),
30422            )),
30423            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
30424                "200 OK",
30425                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30426            )),
30427            _ => None,
30428        }
30429    }
30430
30431    fn workflow_completion_lock_pressure(
30432        path: &str,
30433        body: &str,
30434        request_number: usize,
30435    ) -> Option<(&'static str, String)> {
30436        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
30437            return Some((
30438                "503 Service Unavailable",
30439                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
30440                    "outcome":"deferred", "recorded":false, "retryable":true,
30441                    "retry_after_seconds":1, "task_id":"recover-workflow",
30442                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
30443                    "backend":{"driver":"sqlite", "lock_pressure":true}})
30444                .to_string(),
30445            ));
30446        }
30447        workflow_completion_backend_recovery(path, body, request_number)
30448    }
30449
30450    fn workflow_completion_lock_pressure_forever(
30451        path: &str,
30452        body: &str,
30453        request_number: usize,
30454    ) -> Option<(&'static str, String)> {
30455        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
30456            return workflow_completion_lock_pressure(path, body, 1);
30457        }
30458        workflow_completion_lock_pressure(path, body, request_number)
30459    }
30460
30461    fn workflow_completion_lock_pressure_then_expired(
30462        path: &str,
30463        body: &str,
30464        request_number: usize,
30465    ) -> Option<(&'static str, String)> {
30466        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
30467            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
30468                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
30469        }
30470        workflow_completion_lock_pressure(path, body, request_number)
30471    }
30472
30473    fn workflow_completion_lock_pressure_then_slow(
30474        path: &str,
30475        body: &str,
30476        request_number: usize,
30477    ) -> Option<(&'static str, String)> {
30478        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
30479            thread::sleep(Duration::from_secs(2));
30480        }
30481        workflow_completion_lock_pressure(path, body, request_number)
30482    }
30483
30484    fn workflow_completion_pressure_then_backend_loss(
30485        path: &str,
30486        body: &str,
30487        request_number: usize,
30488    ) -> Option<(&'static str, String)> {
30489        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
30490            return Some((
30491                "503 Service Unavailable",
30492                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
30493                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
30494                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
30495                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
30496                .to_string(),
30497            ));
30498        }
30499        workflow_completion_lock_pressure(path, body, request_number)
30500    }
30501
30502    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
30503        let client = Client::builder(server.base_url())
30504            .timeout(Duration::from_secs(4))
30505            .build()
30506            .unwrap();
30507        let mut worker = Worker::new(client, "recover-queue")
30508            .worker_id("recover-worker")
30509            .poll_timeout(Duration::from_millis(10));
30510        worker.register_workflow("recover.workflow", move |_ctx, _args| {
30511            let calls = Arc::clone(&calls);
30512            async move {
30513                calls.fetch_add(1, Ordering::SeqCst);
30514                Ok(json!("done"))
30515            }
30516        });
30517        worker
30518    }
30519
30520    #[tokio::test]
30521    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
30522        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30523            request_override: Some(workflow_completion_lock_pressure_forever),
30524            ..MockWorkerBehavior::default()
30525        });
30526        let calls = Arc::new(AtomicUsize::new(0));
30527        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
30528            .with_storage_admission(Arc::new(AtomicBool::new(false)));
30529        worker
30530            .client
30531            .worker_storage_admission
30532            .as_mut()
30533            .unwrap()
30534            .workflow_completion_retry_deadline =
30535            Some(tokio::time::Instant::now() + Duration::from_millis(250));
30536        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
30537            .await
30538            .unwrap();
30539        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
30540        assert_eq!(calls.load(Ordering::SeqCst), 1);
30541        assert_eq!(
30542            server
30543                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
30544                .len(),
30545            1
30546        );
30547    }
30548
30549    #[tokio::test]
30550    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
30551        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30552            request_override: Some(workflow_completion_lock_pressure_then_slow),
30553            ..MockWorkerBehavior::default()
30554        });
30555        let calls = Arc::new(AtomicUsize::new(0));
30556        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
30557            .with_storage_admission(Arc::new(AtomicBool::new(false)));
30558        let start = tokio::time::Instant::now();
30559        worker
30560            .client
30561            .worker_storage_admission
30562            .as_mut()
30563            .unwrap()
30564            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
30565        assert!(matches!(
30566            worker.poll_workflow_once().await,
30567            Err(Error::Timeout)
30568        ));
30569        assert!(start.elapsed() < Duration::from_secs(2));
30570        assert_eq!(calls.load(Ordering::SeqCst), 1);
30571        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30572        assert_eq!(bodies.len(), 2);
30573        assert_eq!(bodies[0], bodies[1]);
30574    }
30575
30576    #[tokio::test]
30577    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
30578        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30579            request_override: Some(workflow_completion_pressure_then_backend_loss),
30580            ..MockWorkerBehavior::default()
30581        });
30582        let calls = Arc::new(AtomicUsize::new(0));
30583        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
30584            .with_storage_admission(Arc::new(AtomicBool::new(false)));
30585        let start = tokio::time::Instant::now();
30586        worker
30587            .client
30588            .worker_storage_admission
30589            .as_mut()
30590            .unwrap()
30591            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
30592        let result = worker.poll_workflow_once().await;
30593        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
30594        assert!(start.elapsed() < Duration::from_secs(2));
30595        assert_eq!(calls.load(Ordering::SeqCst), 1);
30596        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30597        assert_eq!(bodies.len(), 2);
30598        assert_eq!(bodies[0], bodies[1]);
30599    }
30600
30601    #[tokio::test]
30602    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
30603        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30604            request_override: Some(workflow_completion_lock_pressure_forever),
30605            ..MockWorkerBehavior::default()
30606        });
30607        let calls = Arc::new(AtomicUsize::new(0));
30608        let stop = Arc::new(AtomicBool::new(false));
30609        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
30610            .with_storage_admission(Arc::clone(&stop));
30611        let shutdown = async {
30612            while server
30613                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
30614                .is_empty()
30615            {
30616                tokio::time::sleep(Duration::from_millis(10)).await;
30617            }
30618            stop.store(true, Ordering::SeqCst);
30619        };
30620        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
30621            tokio::join!(worker.poll_workflow_once(), shutdown)
30622        })
30623        .await
30624        .unwrap();
30625        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
30626        assert_eq!(calls.load(Ordering::SeqCst), 1);
30627        assert_eq!(
30628            server
30629                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
30630                .len(),
30631            1
30632        );
30633    }
30634
30635    #[tokio::test]
30636    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
30637        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30638            request_override: Some(workflow_completion_lock_pressure_then_expired),
30639            ..MockWorkerBehavior::default()
30640        });
30641        let calls = Arc::new(AtomicUsize::new(0));
30642        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
30643        let result = worker.run_once().await;
30644        assert!(
30645            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
30646        );
30647        assert_eq!(calls.load(Ordering::SeqCst), 1);
30648        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30649        assert_eq!(bodies.len(), 2);
30650        assert_eq!(bodies[0], bodies[1]);
30651        assert!(server
30652            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
30653            .is_empty());
30654    }
30655
30656    #[tokio::test]
30657    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
30658        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30659            request_override: Some(workflow_completion_lock_pressure),
30660            ..MockWorkerBehavior::default()
30661        });
30662        let client = Client::builder(server.base_url())
30663            .timeout(Duration::from_secs(2))
30664            .build()
30665            .unwrap();
30666        let calls = Arc::new(AtomicUsize::new(0));
30667        let mut worker = Worker::new(client, "recover-queue")
30668            .worker_id("recover-worker")
30669            .recover_transient_outages(true)
30670            .poll_timeout(Duration::from_millis(10))
30671            .retry_policy(WorkerRetryPolicy {
30672                max_retries: 1,
30673                initial_backoff: Duration::from_millis(10),
30674                max_backoff: Duration::from_millis(10),
30675            });
30676        worker.register_workflow("recover.workflow", {
30677            let calls = Arc::clone(&calls);
30678            move |_ctx, _args| {
30679                let calls = Arc::clone(&calls);
30680                async move {
30681                    calls.fetch_add(1, Ordering::SeqCst);
30682                    Ok(json!("done"))
30683                }
30684            }
30685        });
30686        let start = tokio::time::Instant::now();
30687        assert_eq!(worker.run_once().await.unwrap(), 1);
30688        assert!(start.elapsed() >= Duration::from_secs(1));
30689        assert_eq!(calls.load(Ordering::SeqCst), 1);
30690        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30691        assert_eq!(bodies.len(), 2);
30692        assert_eq!(bodies[0], bodies[1]);
30693    }
30694
30695    #[test]
30696    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
30697        let path = "/worker/workflow-tasks/recover-workflow/complete";
30698        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
30699        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
30700            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
30701            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
30702            "backend":{"driver":"sqlite", "lock_pressure":true}});
30703        let error = |body: Value| Error::Http {
30704            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30705            body: body.to_string(),
30706        };
30707        assert_eq!(
30708            worker_deferred_workflow_completion_retry_after(
30709                &error(response.clone()),
30710                path,
30711                Some(&request)
30712            ),
30713            Some(Duration::from_secs(1))
30714        );
30715        for (field, value) in [
30716            ("reason", json!("backend_unavailable")),
30717            ("operation", json!("complete_activity_task")),
30718            ("task_id", json!("other-task")),
30719            ("lease_owner", json!("other-owner")),
30720            ("workflow_task_attempt", json!(4)),
30721            ("recorded", json!(true)),
30722            ("recorded", Value::Null),
30723            ("recorded", json!("false")),
30724            ("retryable", json!(false)),
30725            ("retry_after_seconds", json!(0)),
30726            ("retry_after_seconds", json!(-1)),
30727            ("retry_after_seconds", json!(1.0)),
30728            ("retry_after_seconds", json!("1")),
30729            ("retry_after_seconds", json!(6)),
30730            ("backend", json!({"lock_pressure":false})),
30731        ] {
30732            let mut invalid = response.clone();
30733            invalid[field] = value;
30734            assert_eq!(
30735                worker_deferred_workflow_completion_retry_after(
30736                    &error(invalid),
30737                    path,
30738                    Some(&request)
30739                ),
30740                None,
30741                "invalid {field}"
30742            );
30743        }
30744        for field in [
30745            "reason",
30746            "operation",
30747            "task_id",
30748            "lease_owner",
30749            "workflow_task_attempt",
30750            "recorded",
30751            "retryable",
30752            "retry_after_seconds",
30753            "backend",
30754        ] {
30755            let mut missing = response.clone();
30756            missing.as_object_mut().unwrap().remove(field);
30757            assert_eq!(
30758                worker_deferred_workflow_completion_retry_after(
30759                    &error(missing),
30760                    path,
30761                    Some(&request)
30762                ),
30763                None,
30764                "missing {field}"
30765            );
30766        }
30767        assert_eq!(
30768            worker_deferred_workflow_completion_retry_after(
30769                &error(response.clone()),
30770                "/worker/activity-tasks/recover-workflow/complete",
30771                Some(&request)
30772            ),
30773            None
30774        );
30775        assert_eq!(
30776            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
30777            None
30778        );
30779        let wrong_status = Error::Http {
30780            status: reqwest::StatusCode::CONFLICT,
30781            body: response.to_string(),
30782        };
30783        assert_eq!(
30784            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
30785            None
30786        );
30787    }
30788
30789    fn activity_completion_stale_after_backend_recovery(
30790        path: &str,
30791        body: &str,
30792        request_number: usize,
30793    ) -> Option<(&'static str, String)> {
30794        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
30795            return Some((
30796                "409 Conflict",
30797                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(),
30798            ));
30799        }
30800        activity_completion_backend_recovery(path, body, request_number)
30801    }
30802
30803    fn activity_completion_remains_unavailable(
30804        path: &str,
30805        body: &str,
30806        request_number: usize,
30807    ) -> Option<(&'static str, String)> {
30808        if path == "/api/worker/activity-tasks/recover-activity/complete" {
30809            return activity_completion_backend_recovery(path, body, 1);
30810        }
30811        activity_completion_backend_recovery(path, body, request_number)
30812    }
30813
30814    #[tokio::test]
30815    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
30816        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30817            request_override: Some(activity_completion_backend_recovery),
30818            ..MockWorkerBehavior::default()
30819        });
30820        let client = Client::builder(server.base_url())
30821            .timeout(Duration::from_secs(2))
30822            .build()
30823            .expect("client");
30824        let handler_calls = Arc::new(AtomicUsize::new(0));
30825        let mut worker = Worker::new(client, "recover-queue")
30826            .worker_id("recover-worker")
30827            .poll_timeout(Duration::from_millis(10));
30828        worker.register_activity("recover.activity", {
30829            let handler_calls = Arc::clone(&handler_calls);
30830            move |_ctx, _args| {
30831                let handler_calls = Arc::clone(&handler_calls);
30832                async move {
30833                    handler_calls.fetch_add(1, Ordering::SeqCst);
30834                    Ok(json!("done"))
30835                }
30836            }
30837        });
30838
30839        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30840        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30841        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
30842        assert_eq!(bodies.len(), 2);
30843        assert_eq!(bodies[0], bodies[1]);
30844    }
30845
30846    #[tokio::test]
30847    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
30848        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30849            request_override: Some(workflow_completion_backend_recovery),
30850            ..MockWorkerBehavior::default()
30851        });
30852        let client = Client::builder(server.base_url())
30853            .timeout(Duration::from_secs(2))
30854            .build()
30855            .expect("client");
30856        let handler_calls = Arc::new(AtomicUsize::new(0));
30857        let mut worker = Worker::new(client, "recover-queue")
30858            .worker_id("recover-worker")
30859            .poll_timeout(Duration::from_millis(10));
30860        worker.register_workflow("recover.workflow", {
30861            let handler_calls = Arc::clone(&handler_calls);
30862            move |_ctx, _args| {
30863                let handler_calls = Arc::clone(&handler_calls);
30864                async move {
30865                    handler_calls.fetch_add(1, Ordering::SeqCst);
30866                    Ok(json!("done"))
30867                }
30868            }
30869        });
30870
30871        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
30872        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30873        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30874        assert_eq!(bodies.len(), 2);
30875        assert_eq!(bodies[0], bodies[1]);
30876    }
30877
30878    #[tokio::test]
30879    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
30880        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30881            request_override: Some(activity_completion_stale_after_backend_recovery),
30882            ..MockWorkerBehavior::default()
30883        });
30884        let client = Client::builder(server.base_url())
30885            .timeout(Duration::from_secs(2))
30886            .build()
30887            .expect("client");
30888        let handler_calls = Arc::new(AtomicUsize::new(0));
30889        let mut worker = Worker::new(client, "recover-queue")
30890            .worker_id("recover-worker")
30891            .poll_timeout(Duration::from_millis(10));
30892        worker.register_activity("recover.activity", {
30893            let handler_calls = Arc::clone(&handler_calls);
30894            move |_ctx, _args| {
30895                let handler_calls = Arc::clone(&handler_calls);
30896                async move {
30897                    handler_calls.fetch_add(1, Ordering::SeqCst);
30898                    Ok(json!("done"))
30899                }
30900            }
30901        });
30902
30903        assert_eq!(
30904            worker
30905                .run_once()
30906                .await
30907                .expect("authoritative stale outcome"),
30908            1
30909        );
30910        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30911        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
30912        assert_eq!(bodies.len(), 2);
30913        assert_eq!(bodies[0], bodies[1]);
30914    }
30915
30916    #[test]
30917    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
30918        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
30919        let response = json!({
30920            "reason":"backend_unavailable", "operation":"complete_activity_task",
30921            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
30922            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
30923            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
30924        });
30925        let path = "/worker/activity-tasks/recover-activity/complete";
30926        let error = |body: Value| Error::Http {
30927            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30928            body: body.to_string(),
30929        };
30930        assert_eq!(
30931            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
30932            Some(Duration::from_secs(1))
30933        );
30934
30935        for (field, invalid) in [
30936            ("operation", json!("poll_activity_task")),
30937            ("outcome", json!("rejected")),
30938            ("worker_id", json!("another-worker")),
30939            ("task_queue", json!("recover-queue")),
30940            ("retryable", json!(false)),
30941            ("retry_after_seconds", json!(0)),
30942            ("task_id", json!("another-task")),
30943            ("lease_owner", json!("another-worker")),
30944            ("activity_attempt_id", json!("another-attempt")),
30945        ] {
30946            let mut invalid_response = response.clone();
30947            invalid_response[field] = invalid;
30948            assert_eq!(
30949                worker_fenced_completion_retry_after(
30950                    &error(invalid_response),
30951                    path,
30952                    Some(&request)
30953                ),
30954                None,
30955                "must not retry mismatched {field}"
30956            );
30957        }
30958        assert_eq!(
30959            worker_fenced_completion_retry_after(&error(response), path, None),
30960            None
30961        );
30962    }
30963
30964    #[tokio::test]
30965    async fn shutdown_interrupts_fenced_completion_backend_wait() {
30966        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30967            request_override: Some(activity_completion_remains_unavailable),
30968            ..MockWorkerBehavior::default()
30969        });
30970        let client = Client::builder(server.base_url())
30971            .timeout(Duration::from_secs(2))
30972            .build()
30973            .expect("client");
30974        let stop = Arc::new(AtomicBool::new(false));
30975        let worker = Worker::new(client, "recover-queue")
30976            .worker_id("recover-worker")
30977            .with_storage_admission(Arc::clone(&stop));
30978        let completion = tokio::spawn(async move {
30979            worker
30980                .client
30981                .complete_activity_task(
30982                    "recover-activity",
30983                    "recover-attempt",
30984                    "recover-worker",
30985                    json!("done"),
30986                    DEFAULT_CODEC,
30987                )
30988                .await
30989        });
30990        let path = "/api/worker/activity-tasks/recover-activity/complete";
30991        tokio::time::timeout(Duration::from_secs(2), async {
30992            while server.request_count(path) == 0 {
30993                tokio::time::sleep(Duration::from_millis(10)).await;
30994            }
30995        })
30996        .await
30997        .expect("first completion request");
30998        stop.store(true, Ordering::SeqCst);
30999        let error = tokio::time::timeout(Duration::from_secs(1), completion)
31000            .await
31001            .expect("shutdown must interrupt retry wait")
31002            .expect("completion task")
31003            .expect_err("backend is still unavailable");
31004        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
31005        assert_eq!(server.request_count(path), 1);
31006    }
31007}