Skip to main content

durable_workflow/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod cancellation_context;
4mod cancellation_replay_clock;
5mod cancellation_scope;
6mod cancellation_scope_history;
7mod cancellation_scope_replay;
8mod cooperative_cancellation;
9mod local_activity;
10mod runtime_payloads;
11mod runtime_uploads;
12mod sticky_worker;
13mod sticky_workflow_cache;
14mod worker_session;
15mod workflow_hydration;
16
17pub use cancellation_context::{
18    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
19};
20pub use cancellation_scope::CancellationScopeOpenReceipt;
21#[doc(hidden)]
22pub use cancellation_scope_history::{
23    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
24};
25#[doc(hidden)]
26pub use cancellation_scope_replay::CancellationScopeRequested;
27
28pub use cooperative_cancellation::{
29    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
30    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
31    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
32    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
33};
34
35use std::{
36    any::{type_name, Any, TypeId},
37    collections::{BTreeMap, BTreeSet, HashMap},
38    future::Future,
39    io::{self, Read},
40    pin::Pin,
41    sync::{
42        atomic::{AtomicBool, Ordering},
43        Arc, Mutex, OnceLock,
44    },
45    task::{Context as TaskContext, Poll},
46    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
47};
48
49use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
50use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
51use chrono::DateTime;
52use futures_util::{
53    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
54};
55pub use local_activity::LocalActivityOptions;
56use serde::{
57    de::DeserializeOwned,
58    ser::{SerializeMap, SerializeSeq},
59    Deserialize, Deserializer, Serialize, Serializer,
60};
61pub use serde_json::{json, Value};
62use sha2::{Digest, Sha256};
63pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
64use thiserror::Error;
65pub use uuid::Uuid;
66pub use worker_session::{WorkerSession, WorkerSessionOptions};
67
68pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
69pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
70
71/// Select the worker request protocol without enabling optional capabilities.
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
73#[non_exhaustive]
74pub enum WorkerProtocolVersion {
75    /// Compatibility with Servers that implement only worker protocol 1.19.
76    V119,
77    /// The default worker protocol.
78    #[default]
79    V120,
80}
81
82impl WorkerProtocolVersion {
83    fn as_str(self) -> &'static str {
84        match self {
85            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
86            Self::V120 => WORKER_PROTOCOL_VERSION,
87        }
88    }
89}
90const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
91/// First additive worker protocol that defines portable worker-affinity features.
92pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
93pub const CONTROL_PLANE_VERSION: &str = "2";
94pub const DEFAULT_CODEC: &str = "avro";
95pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
96/// Worker-registration capability for authored condition-wait occurrence identity.
97pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
98    "condition_wait_occurrence_identity";
99/// Worker-registration capability for portable memo upserts.
100pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
101/// Worker-registration capability for server-routed read-only queries.
102pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
103/// Worker-registration capability for canonical typed search attributes.
104pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
105/// Worker-registration capability for synchronous workflow updates.
106pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
107/// Worker-registration capability for durable named input streams.
108pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
109/// Worker-registration capability for persisted first-completion selection.
110pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
111pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
112pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
113pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
114pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
115pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
116/// First additive worker protocol that defines query-task transport.
117pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
118/// First additive worker protocol that defines typed search-attribute upserts.
119pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
120/// First additive worker protocol that defines portable memo upserts.
121pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
122/// First additive worker protocol that preserves declared search-attribute types.
123pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
124/// First additive worker protocol that defines external durable condition waits.
125pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
126/// First additive worker protocol that preserves authored condition-wait occurrences.
127pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
128/// First additive worker protocol that defines durable selection groups.
129pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
130
131pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
132    let Some((major, minor)) = version.split_once('.') else {
133        return false;
134    };
135    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
136}
137
138fn validate_user_signal_name(signal_name: &str) -> Result<()> {
139    if signal_name == MESSAGE_STREAM_SIGNAL {
140        return Err(Error::Codec(format!(
141            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
142        )));
143    }
144    Ok(())
145}
146
147const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
148const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
149    "Workflow task waiting for scheduled history.";
150const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
151const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
152const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
153const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
154const MAX_MEMO_ENTRIES: usize = 100;
155const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
156const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
157
158const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
159    "lease_expired",
160    "query_task_not_found",
161    "query_task_not_leased",
162    "query_task_timed_out",
163];
164
165/// Manifest for the default service-worker profile.
166///
167/// Inline local execution is enabled separately by [`Worker::local_activities`].
168/// Local execution, sessions and caching require explicit Worker configuration.
169pub fn portable_worker_affinity_capability_manifest() -> Value {
170    json!({
171        "local_activities": {
172            "supported": false,
173            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
174            "reason": "rust_worker_does_not_execute_record_local_activity",
175        },
176        "worker_sessions": {
177            "supported": false,
178            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
179            "reason": "rust_worker_has_no_typed_session_lifecycle",
180        },
181        "sticky_execution": {
182            "supported": false,
183            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
184            "reason": "rust_worker_uses_complete_durable_history_replay",
185        },
186    })
187}
188
189/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
190pub const AVRO_VALUE_SCHEMA_JSON: &str =
191    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
192pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
193pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
194const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
195
196static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
197static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
198    OnceLock::new();
199
200#[derive(Clone, Copy)]
201enum RequestProtocol {
202    ControlPlane,
203    DefaultWorker,
204    Worker(&'static str),
205}
206
207pub type Result<T> = std::result::Result<T, Error>;
208
209#[derive(Debug, Error)]
210pub enum Error {
211    #[error("transport error: {0}")]
212    Transport(#[from] reqwest::Error),
213    #[error(
214        "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"
215    )]
216    InvalidBaseUrl,
217    #[error("json error: {0}")]
218    Json(#[from] serde_json::Error),
219    #[error("http {status}: {body}")]
220    Http {
221        status: reqwest::StatusCode,
222        body: String,
223    },
224    #[error("codec error: {0}")]
225    Codec(String),
226    #[error(transparent)]
227    QueryFailed(QueryFailure),
228    #[error(transparent)]
229    Protocol(ProtocolFailure),
230    #[error(transparent)]
231    NonDeterministicReplay(ReplayFailure),
232    #[error(transparent)]
233    ChildWorkflowFailed(ChildWorkflowFailure),
234    #[error(transparent)]
235    ActivityFailed(ActivityFailure),
236    #[error(transparent)]
237    ParallelFailed(ParallelFailure),
238    #[error(transparent)]
239    SagaCompensationFailed(SagaCompensationFailure),
240    #[error(transparent)]
241    InvalidParallelGroup(ParallelGroupError),
242    #[error(transparent)]
243    DurableOperationCancelled(DurableOperationCancelled),
244    #[error(transparent)]
245    WorkflowCancellationRequested(WorkflowCancellationRequested),
246    #[error(transparent)]
247    CooperativeCancellationRequested(CooperativeCancellationRequested),
248    #[error(transparent)]
249    CancellationScopeRequested(CancellationScopeRequested),
250    #[error(transparent)]
251    WorkflowCommandRejected(WorkflowCommandRejection),
252    #[error(transparent)]
253    WorkflowFailed(WorkflowTerminalOutcome),
254    #[error(transparent)]
255    WorkflowCancelled(WorkflowTerminalOutcome),
256    #[error(transparent)]
257    WorkflowTerminated(WorkflowTerminalOutcome),
258    #[error(transparent)]
259    WorkflowTimedOut(WorkflowTerminalOutcome),
260    #[error(transparent)]
261    ActivityTaskRejected(ActivityTaskRejection),
262    #[error("workflow handler {0:?} is not registered")]
263    WorkflowNotRegistered(String),
264    #[error("activity handler {0:?} is not registered")]
265    ActivityNotRegistered(String),
266    #[error(
267        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
268    )]
269    HandlerType {
270        handler_kind: HandlerKind,
271        handler_name: String,
272        value_kind: HandlerValueKind,
273        rust_type: &'static str,
274        message: String,
275    },
276    #[error("workflow future yielded without emitting a durable command")]
277    WorkflowYieldedWithoutCommand,
278    #[error(
279        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
280    )]
281    MissingWorkflowCommandIdentity,
282    #[error("workflow state lock is poisoned")]
283    WorkflowStatePoisoned,
284    #[error("timer duration is too large for the worker protocol")]
285    TimerDurationOverflow,
286    #[error(transparent)]
287    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
288    #[error(transparent)]
289    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
290    #[error("operation timed out")]
291    Timeout,
292    #[error(
293        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
294    )]
295    MissingRoleCredentials {
296        role: &'static str,
297        opposite_role: &'static str,
298    },
299    #[error("worker loop error: {0}")]
300    WorkerLoop(String),
301    #[error(
302        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
303    )]
304    UnsupportedUpdateValidators { workflow_type: String },
305    #[error("{primary}; worker deregistration also failed: {deregistration}")]
306    WorkerShutdown {
307        primary: Box<Error>,
308        deregistration: Box<Error>,
309    },
310    #[error("invalid child workflow options: {0}")]
311    InvalidChildWorkflowOptions(String),
312    #[error("invalid workflow memo update: {0}")]
313    InvalidMemoUpdate(String),
314    #[error(
315        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
316    )]
317    WorkflowMemoUpdatesUnavailable,
318    #[error("cooperative cancellation is unavailable: {0}")]
319    CooperativeCancellationUnavailable(String),
320    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
321    CancellationScopeExecutionUnavailable,
322    #[error("invalid cooperative cancellation: {0}")]
323    InvalidCooperativeCancellation(String),
324    #[error("activity execution no longer owns its claim: {0}")]
325    ActivityExecutionAbandoned(String),
326    #[error(transparent)]
327    InvalidActivityOptions(ActivityOptionsError),
328    #[error(transparent)]
329    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
330    #[doc(hidden)]
331    #[error("workflow requested continue as new")]
332    ContinueAsNew(ContinueAsNewRequest),
333}
334
335/// Handler namespaces checked independently within a Worker.
336#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
337pub enum RegistrationKind {
338    Workflow,
339    Activity,
340    Query,
341    Update,
342}
343
344impl std::fmt::Display for RegistrationKind {
345    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346        formatter.write_str(match self {
347            Self::Workflow => "workflow",
348            Self::Activity => "activity",
349            Self::Query => "query",
350            Self::Update => "update",
351        })
352    }
353}
354
355/// The authoring adapter and source location of a handler registration.
356#[derive(Clone, Debug, PartialEq, Eq)]
357pub struct HandlerRegistration {
358    pub method: &'static str,
359    pub handler_type: &'static str,
360    pub file: &'static str,
361    pub line: u32,
362    pub column: u32,
363}
364
365impl std::fmt::Display for HandlerRegistration {
366    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
367        write!(
368            formatter,
369            "{} at {}:{}:{} ({})",
370            self.method, self.file, self.line, self.column, self.handler_type
371        )
372    }
373}
374
375/// Ambiguous local configuration, rejected before contacting Server.
376#[derive(Clone, Debug, Error, PartialEq, Eq)]
377#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
378pub struct DuplicateRegistrationError {
379    pub handler_kind: RegistrationKind,
380    pub handler_name: String,
381    /// Query/update registrations are scoped to their owning workflow type.
382    pub workflow_type: Option<String>,
383    pub first_definition: HandlerRegistration,
384    pub second_definition: HandlerRegistration,
385}
386
387impl From<DuplicateRegistrationError> for Error {
388    fn from(error: DuplicateRegistrationError) -> Self {
389        Self::WorkerLoop(error.to_string())
390    }
391}
392
393/// Validation failure for a durable condition-wait definition.
394#[derive(Clone, Debug, Error, PartialEq, Eq)]
395pub enum ConditionWaitOptionsError {
396    #[error("condition_key must be non-empty")]
397    EmptyKey,
398    #[error("condition_definition_fingerprint must be non-empty")]
399    EmptyPredicateIdentity,
400    #[error("condition timeout is too large for the worker protocol")]
401    TimeoutOverflow,
402}
403
404/// Stable identity and optional durable timeout for a condition wait.
405///
406/// `predicate_identity` is recorded as the worker protocol's
407/// `condition_definition_fingerprint` and must change whenever predicate
408/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
409/// is written inline; it derives this identity from the predicate tokens.
410#[derive(Clone, Debug, PartialEq, Eq)]
411pub struct ConditionWaitOptions {
412    condition_key: String,
413    predicate_identity: String,
414    timeout: Option<Duration>,
415}
416
417impl ConditionWaitOptions {
418    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
419        Self {
420            condition_key: condition_key.into(),
421            predicate_identity: predicate_identity.into(),
422            timeout: None,
423        }
424    }
425
426    pub fn timeout(mut self, timeout: Duration) -> Self {
427        self.timeout = Some(timeout);
428        self
429    }
430
431    fn validate(
432        &self,
433    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
434        let condition_key = self.condition_key.trim();
435        if condition_key.is_empty() {
436            return Err(ConditionWaitOptionsError::EmptyKey);
437        }
438        let predicate_identity = self.predicate_identity.trim();
439        if predicate_identity.is_empty() {
440            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
441        }
442        let timeout_seconds = self
443            .timeout
444            .map(|timeout| {
445                timeout
446                    .as_secs()
447                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
448                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
449            })
450            .transpose()?;
451
452        Ok(ValidatedConditionWaitOptions {
453            condition_key: condition_key.to_string(),
454            predicate_identity: predicate_identity.to_string(),
455            timeout_seconds,
456        })
457    }
458}
459
460#[derive(Clone, Debug, PartialEq, Eq)]
461struct ValidatedConditionWaitOptions {
462    condition_key: String,
463    predicate_identity: String,
464    timeout_seconds: Option<u64>,
465}
466
467const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
468
469/// Unambiguous terminal result of a durable condition wait.
470#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
471#[serde(rename_all = "snake_case")]
472pub enum ConditionWaitResult {
473    Satisfied,
474    TimedOut,
475}
476
477impl ConditionWaitResult {
478    pub fn is_satisfied(self) -> bool {
479        self == Self::Satisfied
480    }
481
482    pub fn is_timed_out(self) -> bool {
483        self == Self::TimedOut
484    }
485}
486
487/// Build the stable condition definition identity used by [`wait_condition!`].
488#[doc(hidden)]
489pub fn __condition_definition_fingerprint(source: &str) -> String {
490    let mut digest = Sha256::new();
491    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
492    digest.update(source.as_bytes());
493    format!("sha256:{:x}", digest.finalize())
494}
495
496/// Create a durable condition wait whose predicate definition is fingerprinted
497/// from its inline Rust tokens.
498///
499/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
500/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
501#[macro_export]
502macro_rules! wait_condition {
503    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
504        $ctx.wait_condition(
505            $crate::ConditionWaitOptions::new(
506                $key,
507                $crate::__condition_definition_fingerprint(concat!(
508                    module_path!(),
509                    "\0",
510                    stringify!($predicate)
511                )),
512            )
513            .timeout($timeout),
514            $predicate,
515        )
516    }};
517    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
518        $ctx.wait_condition(
519            $crate::ConditionWaitOptions::new(
520                $key,
521                $crate::__condition_definition_fingerprint(concat!(
522                    module_path!(),
523                    "\0",
524                    stringify!($predicate)
525                )),
526            ),
527            $predicate,
528        )
529    }};
530}
531
532const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
533const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
534const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
535const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
536const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
537
538/// Validation failure for a typed workflow search-attribute update.
539#[derive(Clone, Debug, Error, PartialEq, Eq)]
540pub enum SearchAttributeUpdateError {
541    #[error("search-attribute update requires at least one attribute")]
542    Empty,
543    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
544    InvalidKey(String),
545    #[error("search-attribute update exceeds the limit of 100 attributes")]
546    TooManyAttributes,
547    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
548    ValueTooLong {
549        key: String,
550        kind: &'static str,
551        limit: usize,
552    },
553    #[error(
554        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
555    )]
556    EmptyString(String),
557    #[error("search attribute {0:?} has a non-finite float value")]
558    NonFiniteFloat(String),
559    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
560    InvalidDateTime(String),
561    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
562    PayloadTooLarge,
563}
564
565/// One public typed search-attribute value.
566#[derive(Clone, Debug, PartialEq)]
567pub enum SearchAttributeValue {
568    String(String),
569    Keyword(String),
570    KeywordList(Vec<String>),
571    Int(i64),
572    Float(f64),
573    Bool(bool),
574    DateTime(String),
575    Delete,
576}
577
578impl SearchAttributeValue {
579    fn type_name(&self) -> Option<&'static str> {
580        match self {
581            Self::String(_) => Some("string"),
582            Self::Keyword(_) => Some("keyword"),
583            Self::KeywordList(_) => Some("keyword_list"),
584            Self::Int(_) => Some("int"),
585            Self::Float(_) => Some("float"),
586            Self::Bool(_) => Some("bool"),
587            Self::DateTime(_) => Some("datetime"),
588            Self::Delete => None,
589        }
590    }
591
592    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
593        let normalize_string = |value: String, kind: &'static str, limit: usize| {
594            let value = value.trim().to_string();
595            if value.is_empty() {
596                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
597            }
598            if value.len() > limit {
599                return Err(SearchAttributeUpdateError::ValueTooLong {
600                    key: key.to_string(),
601                    kind,
602                    limit,
603                });
604            }
605            Ok(value)
606        };
607
608        match self {
609            Self::String(value) => Ok(Self::String(normalize_string(
610                value,
611                "string",
612                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
613            )?)),
614            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
615                value,
616                "keyword",
617                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
618            )?)),
619            Self::KeywordList(values) => {
620                let values = values
621                    .into_iter()
622                    .map(|value| {
623                        let value = value.trim().to_string();
624                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
625                            return Err(SearchAttributeUpdateError::ValueTooLong {
626                                key: key.to_string(),
627                                kind: "keyword-list entry",
628                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
629                            });
630                        }
631                        Ok(value)
632                    })
633                    .collect::<std::result::Result<Vec<_>, _>>()?;
634                Ok(Self::KeywordList(values))
635            }
636            Self::Float(value) if !value.is_finite() => {
637                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
638            }
639            Self::DateTime(value) => {
640                let value =
641                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
642                if DateTime::parse_from_rfc3339(&value).is_err() {
643                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
644                }
645                Ok(Self::DateTime(value))
646            }
647            value => Ok(value),
648        }
649    }
650
651    fn into_json(self) -> Value {
652        match self {
653            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
654                Value::String(value)
655            }
656            Self::KeywordList(values) => {
657                Value::Array(values.into_iter().map(Value::String).collect())
658            }
659            Self::Int(value) => json!(value),
660            Self::Float(value) => json!(value),
661            Self::Bool(value) => json!(value),
662            Self::Delete => Value::Null,
663        }
664    }
665}
666
667/// Validated typed workflow-side search-attribute mutation.
668#[derive(Clone, Debug, Default, PartialEq)]
669pub struct SearchAttributeUpdate {
670    attributes: BTreeMap<String, SearchAttributeValue>,
671}
672
673impl SearchAttributeUpdate {
674    pub fn new() -> Self {
675        Self::default()
676    }
677
678    pub fn set(
679        mut self,
680        key: impl Into<String>,
681        value: SearchAttributeValue,
682    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
683        let key = key.into();
684        validate_search_attribute_key(&key)?;
685        if !self.attributes.contains_key(&key)
686            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
687        {
688            return Err(SearchAttributeUpdateError::TooManyAttributes);
689        }
690        self.attributes.insert(key.clone(), value.normalized(&key)?);
691        self.validate_size()?;
692        Ok(self)
693    }
694
695    pub fn string(
696        self,
697        key: impl Into<String>,
698        value: impl Into<String>,
699    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
700        self.set(key, SearchAttributeValue::String(value.into()))
701    }
702
703    pub fn keyword(
704        self,
705        key: impl Into<String>,
706        value: impl Into<String>,
707    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
708        self.set(key, SearchAttributeValue::Keyword(value.into()))
709    }
710
711    pub fn keyword_list<I, V>(
712        self,
713        key: impl Into<String>,
714        values: I,
715    ) -> std::result::Result<Self, SearchAttributeUpdateError>
716    where
717        I: IntoIterator<Item = V>,
718        V: Into<String>,
719    {
720        self.set(
721            key,
722            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
723        )
724    }
725
726    pub fn int(
727        self,
728        key: impl Into<String>,
729        value: i64,
730    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
731        self.set(key, SearchAttributeValue::Int(value))
732    }
733
734    pub fn float(
735        self,
736        key: impl Into<String>,
737        value: f64,
738    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
739        self.set(key, SearchAttributeValue::Float(value))
740    }
741
742    pub fn bool(
743        self,
744        key: impl Into<String>,
745        value: bool,
746    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
747        self.set(key, SearchAttributeValue::Bool(value))
748    }
749
750    pub fn datetime(
751        self,
752        key: impl Into<String>,
753        value: impl Into<String>,
754    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
755        self.set(key, SearchAttributeValue::DateTime(value.into()))
756    }
757
758    pub fn delete(
759        self,
760        key: impl Into<String>,
761    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
762        self.set(key, SearchAttributeValue::Delete)
763    }
764
765    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
766        let (attributes, _) = self.clone().into_wire_parts();
767        if serde_json::to_vec(&attributes)
768            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
769            .unwrap_or(true)
770        {
771            return Err(SearchAttributeUpdateError::PayloadTooLarge);
772        }
773        Ok(())
774    }
775
776    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
777        let mut attributes = serde_json::Map::new();
778        let mut attribute_types = BTreeMap::new();
779        for (key, value) in self.attributes {
780            if let Some(type_name) = value.type_name() {
781                attribute_types.insert(key.clone(), type_name.to_string());
782            }
783            attributes.insert(key, value.into_json());
784        }
785        (Value::Object(attributes), attribute_types)
786    }
787
788    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
789        if self.attributes.is_empty() {
790            return Err(SearchAttributeUpdateError::Empty);
791        }
792        self.validate_size()
793    }
794}
795
796fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
797    let valid = !key.is_empty()
798        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
799        && key
800            .bytes()
801            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
802    if valid {
803        Ok(())
804    } else {
805        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
806    }
807}
808
809/// The registered handler family reported by [`Error::HandlerType`].
810#[derive(Clone, Copy, Debug, PartialEq, Eq)]
811pub enum HandlerKind {
812    Workflow,
813    Activity,
814}
815
816impl std::fmt::Display for HandlerKind {
817    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
818        formatter.write_str(match self {
819            Self::Workflow => "workflow",
820            Self::Activity => "activity",
821        })
822    }
823}
824
825/// Whether a typed handler failed to adapt its input or result.
826#[derive(Clone, Copy, Debug, PartialEq, Eq)]
827pub enum HandlerValueKind {
828    Input,
829    Result,
830}
831
832impl std::fmt::Display for HandlerValueKind {
833    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
834        formatter.write_str(match self {
835            Self::Input => "input",
836            Self::Result => "result",
837        })
838    }
839}
840
841/// The lifecycle command sent to a workflow execution.
842#[derive(Clone, Copy, Debug, PartialEq, Eq)]
843pub enum WorkflowCommandKind {
844    Cancel,
845    Terminate,
846}
847
848impl WorkflowCommandKind {
849    fn as_str(self) -> &'static str {
850        match self {
851            Self::Cancel => "cancel",
852            Self::Terminate => "terminate",
853        }
854    }
855}
856
857/// Optional structured fields for a cancellation or termination request.
858#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
859pub struct WorkflowCommandOptions {
860    #[serde(skip_serializing_if = "Option::is_none")]
861    pub reason: Option<String>,
862    #[serde(skip_serializing_if = "Option::is_none")]
863    pub request_id: Option<String>,
864}
865
866/// Server-enforced timeout policy for a workflow start.
867///
868/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
869/// only bounds how long the caller waits. A server deadline produces a terminal
870/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
871/// `run_timeout`.
872#[derive(Clone, Debug, PartialEq, Eq)]
873pub struct WorkflowStartOptions {
874    pub execution_timeout_seconds: u64,
875    pub run_timeout_seconds: u64,
876}
877
878impl Default for WorkflowStartOptions {
879    fn default() -> Self {
880        Self {
881            execution_timeout_seconds: 3600,
882            run_timeout_seconds: 600,
883        }
884    }
885}
886
887impl WorkflowStartOptions {
888    pub fn new() -> Self {
889        Self::default()
890    }
891
892    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
893        self.execution_timeout_seconds = seconds;
894        self
895    }
896
897    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
898        self.run_timeout_seconds = seconds;
899        self
900    }
901
902    fn validate(&self) -> Result<()> {
903        if self.execution_timeout_seconds == 0 {
904            return Err(Error::Codec(
905                "execution_timeout_seconds must be at least 1".to_string(),
906            ));
907        }
908        if self.run_timeout_seconds == 0 {
909            return Err(Error::Codec(
910                "run_timeout_seconds must be at least 1".to_string(),
911            ));
912        }
913        if self.run_timeout_seconds > self.execution_timeout_seconds {
914            return Err(Error::Codec(
915                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
916            ));
917        }
918
919        Ok(())
920    }
921}
922
923/// Optional routing overrides for a continue-as-new transition.
924///
925/// Omitted values retain the current workflow type and task queue. Server-owned
926/// instance metadata is not accepted here and is carried by the server.
927#[derive(Clone, Debug, Default, PartialEq, Eq)]
928pub struct ContinueAsNewOptions {
929    pub workflow_type: Option<String>,
930    pub task_queue: Option<String>,
931}
932
933impl ContinueAsNewOptions {
934    pub fn new() -> Self {
935        Self::default()
936    }
937
938    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
939        self.workflow_type = Some(workflow_type.into());
940        self
941    }
942
943    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
944        self.task_queue = Some(task_queue.into());
945        self
946    }
947
948    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
949        for (field, value) in [
950            ("workflow_type", self.workflow_type.as_deref()),
951            ("task_queue", self.task_queue.as_deref()),
952        ] {
953            if value.is_some_and(|value| value.trim().is_empty()) {
954                return Err(ContinueAsNewOptionsError {
955                    field,
956                    message: format!("{field} must not be empty"),
957                });
958            }
959        }
960        Ok(())
961    }
962}
963
964/// A stable validation error raised before a continue-as-new command is emitted.
965#[derive(Clone, Debug, Error, PartialEq, Eq)]
966#[error("invalid continue-as-new option {field}: {message}")]
967pub struct ContinueAsNewOptionsError {
968    pub field: &'static str,
969    pub message: String,
970}
971
972/// Public history-budget information attached to the current workflow task.
973#[derive(Clone, Debug, Default, PartialEq, Eq)]
974pub struct WorkflowHistoryBudget {
975    pub event_count: u64,
976    pub size_bytes: Option<u64>,
977    pub continue_as_new_recommended: bool,
978    pub pressure: Option<String>,
979}
980
981#[doc(hidden)]
982#[derive(Clone, Debug)]
983pub struct ContinueAsNewRequest {
984    arguments: AvroValue,
985    options: ContinueAsNewOptions,
986}
987
988impl WorkflowCommandOptions {
989    pub fn new() -> Self {
990        Self::default()
991    }
992
993    pub fn reason(mut self, reason: impl Into<String>) -> Self {
994        self.reason = Some(reason.into());
995        self
996    }
997
998    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
999        self.request_id = Some(request_id.into());
1000        self
1001    }
1002}
1003
1004/// The accepted, machine-readable result of a lifecycle command.
1005#[derive(Clone, Debug, PartialEq)]
1006pub struct WorkflowCommandResult {
1007    pub command: WorkflowCommandKind,
1008    pub workflow_id: String,
1009    pub run_id: Option<String>,
1010    pub outcome: Option<String>,
1011    pub reason: Option<String>,
1012    pub command_status: Option<String>,
1013    pub raw: Value,
1014}
1015
1016/// A new run continuing a failed run from its recorded activity boundary.
1017#[derive(Clone, Debug, PartialEq)]
1018pub struct WorkflowRedriveResult {
1019    pub workflow_id: String,
1020    pub source_run_id: String,
1021    pub run_id: String,
1022    pub resume_step_sequence: u64,
1023    pub raw: Value,
1024}
1025
1026/// A stable rejection returned by instance- or selected-run lifecycle commands.
1027#[derive(Clone, Debug, Error)]
1028#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1029pub struct WorkflowCommandRejection {
1030    pub command: WorkflowCommandKind,
1031    pub status: u16,
1032    pub reason: String,
1033    pub message: String,
1034    pub workflow_id: String,
1035    pub run_id: Option<String>,
1036    pub target_scope: Option<String>,
1037    pub body: Value,
1038}
1039
1040/// Stable terminal categories returned by [`WorkflowHandle::result`].
1041#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1042pub enum WorkflowTerminalKind {
1043    Failed,
1044    Cancelled,
1045    Terminated,
1046    TimedOut,
1047}
1048
1049/// A typed terminal workflow outcome with durable identity and failure metadata.
1050///
1051/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1052/// of parsing its display representation. Fields remain `None` when an older
1053/// server did not publish that metadata.
1054#[derive(Clone, Debug, Error)]
1055#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1056pub struct WorkflowTerminalOutcome {
1057    pub kind: WorkflowTerminalKind,
1058    pub workflow_id: String,
1059    pub run_id: Option<String>,
1060    pub reason: String,
1061    pub failure_category: Option<String>,
1062    pub failure_id: Option<String>,
1063    pub exception_type: Option<String>,
1064    pub exception_class: Option<String>,
1065    pub non_retryable: Option<bool>,
1066    pub message: Option<String>,
1067    pub exception: Option<Value>,
1068    pub raw: Value,
1069}
1070
1071/// A worker-side activity settlement or heartbeat rejected by durable state.
1072#[derive(Clone, Debug, Error)]
1073#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1074pub struct ActivityTaskRejection {
1075    pub operation: String,
1076    pub status: u16,
1077    pub reason: String,
1078    pub task_id: String,
1079    pub activity_attempt_id: String,
1080    pub cancel_requested: bool,
1081    pub can_continue: Option<bool>,
1082    pub run_closed_reason: Option<String>,
1083    pub body: Value,
1084}
1085
1086/// Stable validation categories for [`ActivityOptions`].
1087#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1088pub enum ActivityOptionsErrorKind {
1089    EmptyTaskQueue,
1090    EmptyRetryPolicy,
1091    InvalidMaxAttempts,
1092    BackoffWithoutRetryBudget,
1093    TooManyBackoffIntervals,
1094    InvalidBackoffCoefficient,
1095    BackoffGenerationTooLarge,
1096    BackoffOverflow,
1097    EmptyNonRetryableErrorType,
1098    TimeoutNotPositive,
1099    MissingTotalTimeout,
1100    TimeoutOverflow,
1101    TimeoutOrder,
1102}
1103
1104/// A machine-readable activity-options validation failure.
1105#[derive(Clone, Debug, Error, PartialEq, Eq)]
1106#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1107pub struct ActivityOptionsError {
1108    pub kind: ActivityOptionsErrorKind,
1109    pub field: Option<&'static str>,
1110    pub message: String,
1111}
1112
1113impl ActivityOptionsError {
1114    fn new(
1115        kind: ActivityOptionsErrorKind,
1116        field: Option<&'static str>,
1117        message: impl Into<String>,
1118    ) -> Self {
1119        Self {
1120            kind,
1121            field,
1122            message: message.into(),
1123        }
1124    }
1125}
1126
1127/// Stable terminal categories returned when an awaited activity does not succeed.
1128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1129pub enum ActivityFailureKind {
1130    Failed,
1131    Cancelled,
1132    TimedOut,
1133}
1134
1135/// A stable, machine-readable terminal activity failure.
1136///
1137/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1138/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1139#[derive(Clone, Debug, Error, PartialEq)]
1140#[error("activity failed ({reason}): {message}")]
1141pub struct ActivityFailure {
1142    pub kind: ActivityFailureKind,
1143    pub reason: String,
1144    pub message: String,
1145    pub activity_execution_id: Option<String>,
1146    pub activity_attempt_id: Option<String>,
1147    pub activity_type: Option<String>,
1148    pub activity_class: Option<String>,
1149    pub attempt_number: Option<u64>,
1150    pub failure_id: Option<String>,
1151    pub failure_category: Option<String>,
1152    pub timeout_kind: Option<String>,
1153    pub non_retryable: bool,
1154    pub exception_type: Option<String>,
1155    pub exception_class: Option<String>,
1156    pub code: Option<Value>,
1157    pub exception: Option<Value>,
1158}
1159
1160/// Stable terminal categories returned when an awaited child does not succeed.
1161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1162pub enum ChildWorkflowFailureKind {
1163    Failed,
1164    Cancelled,
1165    Terminated,
1166}
1167
1168/// A stable, machine-readable child workflow failure delivered to its parent.
1169///
1170/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1171/// of parsing the display message. Child and parent identifiers retain the
1172/// relationship recorded in durable history across worker restarts.
1173#[derive(Clone, Debug, Error)]
1174#[error("child workflow failed ({reason}): {message}")]
1175pub struct ChildWorkflowFailure {
1176    pub kind: ChildWorkflowFailureKind,
1177    pub reason: String,
1178    pub message: String,
1179    pub parent_workflow_id: Option<String>,
1180    pub parent_workflow_run_id: Option<String>,
1181    pub child_workflow_id: Option<String>,
1182    pub child_workflow_run_id: Option<String>,
1183    pub child_workflow_type: Option<String>,
1184    pub failure_id: Option<String>,
1185    pub failure_category: Option<String>,
1186    pub exception_type: Option<String>,
1187    pub exception_class: Option<String>,
1188    pub non_retryable: bool,
1189    pub code: Option<Value>,
1190    pub exception: Option<Value>,
1191}
1192
1193/// The identity of one durable workflow execution.
1194#[derive(Clone, Debug, PartialEq, Eq)]
1195pub struct WorkflowIdentity {
1196    pub workflow_id: Option<String>,
1197    pub run_id: Option<String>,
1198}
1199
1200/// A successful child result together with its durable parent-child identity.
1201#[derive(Clone, Debug, PartialEq)]
1202pub struct ChildWorkflowResult {
1203    pub parent: WorkflowIdentity,
1204    pub child: WorkflowIdentity,
1205    pub child_workflow_type: Option<String>,
1206    pub result: Value,
1207}
1208
1209/// Lossless successful child result for fixed Avro Value workflows.
1210#[derive(Clone, Debug, PartialEq)]
1211pub struct ChildWorkflowAvroResult {
1212    pub parent: WorkflowIdentity,
1213    pub child: WorkflowIdentity,
1214    pub child_workflow_type: Option<String>,
1215    pub result: AvroValue,
1216}
1217
1218/// Stable user-facing identity for one member of a durable selection group.
1219#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1220#[serde(untagged)]
1221pub enum SelectionKey {
1222    Index(usize),
1223    Name(String),
1224}
1225
1226impl From<usize> for SelectionKey {
1227    fn from(value: usize) -> Self {
1228        Self::Index(value)
1229    }
1230}
1231
1232impl From<String> for SelectionKey {
1233    fn from(value: String) -> Self {
1234        Self::Name(value)
1235    }
1236}
1237
1238impl From<&str> for SelectionKey {
1239    fn from(value: &str) -> Self {
1240        Self::Name(value.to_string())
1241    }
1242}
1243
1244/// Typed result of explicitly awaiting a cancelled non-winning operation.
1245#[derive(Clone, Debug, Error, PartialEq, Eq)]
1246#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1247pub struct DurableOperationCancelled {
1248    pub selection_group_id: String,
1249    pub member_key: SelectionKey,
1250    pub member_index: usize,
1251    pub operation_kind: String,
1252    pub operation_identity: String,
1253}
1254
1255/// Stable identity for one enclosing deterministic parallel group.
1256///
1257/// The same fields are attached to every ordinary activity, timer, or child
1258/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1259/// no Rust-specific wire command is introduced.
1260#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1261pub struct ParallelGroupMetadata {
1262    pub parallel_group_id: String,
1263    pub parallel_group_kind: String,
1264    pub parallel_group_base_sequence: u64,
1265    pub parallel_group_size: usize,
1266    pub parallel_group_index: usize,
1267    #[serde(default, skip_serializing_if = "Option::is_none")]
1268    pub parallel_group_mode: Option<String>,
1269    #[serde(default, skip_serializing_if = "Option::is_none")]
1270    pub selection_member_key: Option<SelectionKey>,
1271    #[serde(default, skip_serializing_if = "Option::is_none")]
1272    pub selection_member_index: Option<usize>,
1273    #[serde(default, skip_serializing_if = "Option::is_none")]
1274    pub selection_member_base_sequence: Option<u64>,
1275    #[serde(default, skip_serializing_if = "Option::is_none")]
1276    pub selection_member_size: Option<usize>,
1277    #[serde(default, skip_serializing_if = "Option::is_none")]
1278    pub selection_member_kind: Option<String>,
1279}
1280
1281/// One input-ordered result returned by [`WorkflowContext::parallel`].
1282#[derive(Clone, Debug, PartialEq)]
1283pub enum ParallelResult {
1284    Activity(Value),
1285    ChildWorkflow(ChildWorkflowResult),
1286    Timer,
1287    Signal(Vec<Value>),
1288    Condition(ConditionWaitResult),
1289    Group(Vec<ParallelResult>),
1290}
1291
1292/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1293#[derive(Clone, Debug, PartialEq)]
1294pub enum ParallelAvroResult {
1295    Activity(AvroValue),
1296    ChildWorkflow(ChildWorkflowAvroResult),
1297    Timer,
1298    Signal(Vec<AvroValue>),
1299    Condition(ConditionWaitResult),
1300    Group(Vec<ParallelAvroResult>),
1301}
1302
1303impl ParallelAvroResult {
1304    fn into_json_result(self) -> Result<ParallelResult> {
1305        match self {
1306            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1307            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1308                parent: result.parent,
1309                child: result.child,
1310                child_workflow_type: result.child_workflow_type,
1311                result: result.result.into_json()?,
1312            })),
1313            Self::Timer => Ok(ParallelResult::Timer),
1314            Self::Signal(values) => Ok(ParallelResult::Signal(
1315                values
1316                    .into_iter()
1317                    .map(AvroValue::into_json)
1318                    .collect::<Result<Vec<_>>>()?,
1319            )),
1320            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1321            Self::Group(results) => Ok(ParallelResult::Group(
1322                results
1323                    .into_iter()
1324                    .map(Self::into_json_result)
1325                    .collect::<Result<Vec<_>>>()?,
1326            )),
1327        }
1328    }
1329}
1330
1331/// One successful leaf retained when another parallel member failed.
1332#[derive(Clone, Debug, PartialEq)]
1333pub struct ParallelCompletion {
1334    pub member_path: Vec<usize>,
1335    pub result: ParallelResult,
1336}
1337
1338/// A deterministic join failed after some siblings had already completed.
1339///
1340/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1341/// error. `completed` is declaration ordered and contains only durable
1342/// successes observed in the same replay. Late sibling completions can add
1343/// entries on a later replay without changing `member_path` or the selected
1344/// positional failure.
1345#[derive(Debug, Error)]
1346#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1347pub struct ParallelFailure {
1348    pub group_id: String,
1349    pub member_path: Vec<usize>,
1350    pub group_path: Vec<ParallelGroupMetadata>,
1351    pub completed: Vec<ParallelCompletion>,
1352    #[source]
1353    pub cause: Box<Error>,
1354}
1355
1356/// Stable validation error returned before an invalid group emits commands.
1357#[derive(Clone, Debug, Error, PartialEq, Eq)]
1358#[error("invalid deterministic parallel group ({reason}): {message}")]
1359pub struct ParallelGroupError {
1360    pub reason: &'static str,
1361    pub member_path: Vec<usize>,
1362    pub message: String,
1363}
1364
1365/// Cooperative workflow cancellation observed at an author-controlled point.
1366#[derive(Clone, Debug, Error, PartialEq, Eq)]
1367#[error("workflow cancellation was requested")]
1368pub struct WorkflowCancellationRequested;
1369
1370/// A forward saga failure followed by a terminal compensation failure.
1371#[derive(Debug, Error)]
1372#[error(
1373    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1374)]
1375pub struct SagaCompensationFailure {
1376    pub initiating_failure: Box<Error>,
1377    pub compensation_failure: Box<Error>,
1378    pub compensation_activity_type: String,
1379    pub compensation_registration_order: usize,
1380}
1381
1382/// Server behavior when a parent closes while its child is still open.
1383#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1384pub enum ParentClosePolicy {
1385    #[default]
1386    Abandon,
1387    /// Legacy terminal cancellation without cooperative cleanup.
1388    RequestCancel,
1389    /// Request cooperative cleanup with the original lineage and deadline.
1390    RequestCancellation,
1391    Terminate,
1392}
1393
1394impl ParentClosePolicy {
1395    fn as_str(self) -> &'static str {
1396        match self {
1397            Self::Abandon => "abandon",
1398            Self::RequestCancel => "request_cancel",
1399            Self::RequestCancellation => "request_cancellation",
1400            Self::Terminate => "terminate",
1401        }
1402    }
1403}
1404
1405/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1406#[non_exhaustive]
1407#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1408pub enum CancellationPolicy {
1409    /// Request cancellation and continue without waiting. Historical Activity default.
1410    TryCancel,
1411    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1412    WaitCancellationCompleted,
1413    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1414    #[default]
1415    Abandon,
1416}
1417
1418impl CancellationPolicy {
1419    fn as_str(self) -> &'static str {
1420        match self {
1421            Self::TryCancel => "try_cancel",
1422            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1423            Self::Abandon => "abandon",
1424        }
1425    }
1426}
1427
1428/// Durable retry policy for one child workflow invocation.
1429#[derive(Clone, Debug, Default, PartialEq, Eq)]
1430pub struct ChildWorkflowRetryPolicy {
1431    pub max_attempts: Option<u32>,
1432    pub backoff_seconds: Vec<u64>,
1433    pub non_retryable_error_types: Vec<String>,
1434}
1435
1436/// Options recorded with a child-workflow command.
1437///
1438/// The task queue is mandatory so routing is explicit and replay-stable.
1439#[derive(Clone, Debug, PartialEq, Eq)]
1440pub struct ChildWorkflowOptions {
1441    pub task_queue: String,
1442    pub parent_close_policy: ParentClosePolicy,
1443    pub cancellation_policy: CancellationPolicy,
1444    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1445    pub execution_timeout_seconds: Option<u64>,
1446    pub run_timeout_seconds: Option<u64>,
1447}
1448
1449impl ChildWorkflowOptions {
1450    pub fn new(task_queue: impl Into<String>) -> Self {
1451        Self {
1452            task_queue: task_queue.into(),
1453            parent_close_policy: ParentClosePolicy::Abandon,
1454            cancellation_policy: CancellationPolicy::Abandon,
1455            retry_policy: None,
1456            execution_timeout_seconds: None,
1457            run_timeout_seconds: None,
1458        }
1459    }
1460
1461    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1462        self.parent_close_policy = policy;
1463        self
1464    }
1465
1466    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1467        self.cancellation_policy = policy;
1468        self
1469    }
1470
1471    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1472        self.retry_policy = Some(policy);
1473        self
1474    }
1475
1476    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1477        self.execution_timeout_seconds = Some(seconds);
1478        self
1479    }
1480
1481    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1482        self.run_timeout_seconds = Some(seconds);
1483        self
1484    }
1485}
1486
1487/// Backoff intervals for one durable activity retry policy.
1488#[derive(Clone, Debug, PartialEq, Eq)]
1489pub enum ActivityBackoff {
1490    /// Use these intervals between attempts. The server repeats the final
1491    /// interval if the retry budget contains more attempts than entries.
1492    Explicit(Vec<Duration>),
1493    /// Generate one interval for every retry using integer exponential growth.
1494    Exponential {
1495        initial_interval: Duration,
1496        coefficient: u32,
1497        maximum_interval: Option<Duration>,
1498    },
1499}
1500
1501/// Durable server-side retry policy for one activity execution.
1502#[derive(Clone, Debug, Default, PartialEq, Eq)]
1503pub struct ActivityRetryPolicy {
1504    pub max_attempts: Option<u32>,
1505    pub backoff: Option<ActivityBackoff>,
1506    pub non_retryable_error_types: Vec<String>,
1507}
1508
1509impl ActivityRetryPolicy {
1510    /// Start a policy with a finite attempt budget, including the first attempt.
1511    pub fn new(max_attempts: u32) -> Self {
1512        Self {
1513            max_attempts: Some(max_attempts),
1514            ..Self::default()
1515        }
1516    }
1517
1518    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1519        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1520        self
1521    }
1522
1523    pub fn exponential_backoff(
1524        mut self,
1525        initial_interval: Duration,
1526        coefficient: u32,
1527        maximum_interval: Option<Duration>,
1528    ) -> Self {
1529        self.backoff = Some(ActivityBackoff::Exponential {
1530            initial_interval,
1531            coefficient,
1532            maximum_interval,
1533        });
1534        self
1535    }
1536
1537    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1538        self.non_retryable_error_types.push(error_type.into());
1539        self
1540    }
1541
1542    pub fn non_retryable_error_types(
1543        mut self,
1544        error_types: impl IntoIterator<Item = impl Into<String>>,
1545    ) -> Self {
1546        self.non_retryable_error_types
1547            .extend(error_types.into_iter().map(Into::into));
1548        self
1549    }
1550}
1551
1552/// Options recorded atomically on one deterministic `schedule_activity` command.
1553///
1554/// Durations are rounded up to whole seconds when encoded, so the server never
1555/// receives a shorter timeout or backoff than the caller requested.
1556#[derive(Clone, Debug, Default, PartialEq, Eq)]
1557pub struct ActivityOptions {
1558    pub task_queue: Option<String>,
1559    pub retry_policy: Option<ActivityRetryPolicy>,
1560    pub start_to_close_timeout: Option<Duration>,
1561    pub schedule_to_start_timeout: Option<Duration>,
1562    pub schedule_to_close_timeout: Option<Duration>,
1563    pub heartbeat_timeout: Option<Duration>,
1564    pub cancellation_policy: Option<CancellationPolicy>,
1565}
1566
1567impl ActivityOptions {
1568    pub fn new() -> Self {
1569        Self::default()
1570    }
1571
1572    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1573        self.task_queue = Some(task_queue.into());
1574        self
1575    }
1576
1577    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1578        self.retry_policy = Some(policy);
1579        self
1580    }
1581
1582    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1583        self.start_to_close_timeout = Some(timeout);
1584        self
1585    }
1586
1587    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1588        self.schedule_to_start_timeout = Some(timeout);
1589        self
1590    }
1591
1592    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1593        self.schedule_to_close_timeout = Some(timeout);
1594        self
1595    }
1596
1597    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1598        self.heartbeat_timeout = Some(timeout);
1599        self
1600    }
1601
1602    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1603        self.cancellation_policy = Some(policy);
1604        self
1605    }
1606
1607    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1608        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1609            && self.schedule_to_close_timeout.is_none()
1610        {
1611            return Err(ActivityOptionsError::new(
1612                ActivityOptionsErrorKind::MissingTotalTimeout,
1613                Some("schedule_to_close_timeout"),
1614                "remote Activity Abandon requires a finite positive total timeout",
1615            ));
1616        }
1617        if self
1618            .task_queue
1619            .as_deref()
1620            .is_some_and(|queue| queue.trim().is_empty())
1621        {
1622            return Err(ActivityOptionsError::new(
1623                ActivityOptionsErrorKind::EmptyTaskQueue,
1624                Some("task_queue"),
1625                "task_queue must not be empty",
1626            ));
1627        }
1628
1629        for (field, value) in [
1630            ("start_to_close_timeout", self.start_to_close_timeout),
1631            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1632            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1633            ("heartbeat_timeout", self.heartbeat_timeout),
1634        ] {
1635            if value.is_some_and(|value| value.is_zero()) {
1636                return Err(ActivityOptionsError::new(
1637                    ActivityOptionsErrorKind::TimeoutNotPositive,
1638                    Some(field),
1639                    format!("{field} must be positive"),
1640                ));
1641            }
1642        }
1643
1644        validate_timeout_order(
1645            "heartbeat_timeout",
1646            self.heartbeat_timeout,
1647            "start_to_close_timeout",
1648            self.start_to_close_timeout,
1649        )?;
1650        validate_timeout_order(
1651            "start_to_close_timeout",
1652            self.start_to_close_timeout,
1653            "schedule_to_close_timeout",
1654            self.schedule_to_close_timeout,
1655        )?;
1656        validate_timeout_order(
1657            "schedule_to_start_timeout",
1658            self.schedule_to_start_timeout,
1659            "schedule_to_close_timeout",
1660            self.schedule_to_close_timeout,
1661        )?;
1662
1663        Ok(ValidatedActivityOptions {
1664            task_queue: self.task_queue.clone(),
1665            retry_policy: self
1666                .retry_policy
1667                .as_ref()
1668                .map(validate_activity_retry_policy)
1669                .transpose()?,
1670            start_to_close_timeout: timeout_seconds(
1671                "start_to_close_timeout",
1672                self.start_to_close_timeout,
1673            )?,
1674            schedule_to_start_timeout: timeout_seconds(
1675                "schedule_to_start_timeout",
1676                self.schedule_to_start_timeout,
1677            )?,
1678            schedule_to_close_timeout: timeout_seconds(
1679                "schedule_to_close_timeout",
1680                self.schedule_to_close_timeout,
1681            )?,
1682            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1683            cancellation_policy: self.cancellation_policy,
1684        })
1685    }
1686}
1687
1688/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1689///
1690/// Constructors capture arguments but perform no I/O. The join validates the
1691/// complete tree, attaches the existing parallel-group metadata to every
1692/// ordinary command, schedules all leaves, and then suspends.
1693pub enum ParallelOperation {
1694    Activity {
1695        activity_type: String,
1696        options: ActivityOptions,
1697        arguments: Result<AvroValue>,
1698    },
1699    ChildWorkflow {
1700        workflow_type: String,
1701        options: ChildWorkflowOptions,
1702        arguments: Result<AvroValue>,
1703    },
1704    Timer(Duration),
1705    Signal(String),
1706    Condition {
1707        options: ConditionWaitOptions,
1708        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1709    },
1710    Group(Vec<ParallelOperation>),
1711}
1712
1713impl ParallelOperation {
1714    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1715        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1716    }
1717
1718    pub fn activity_with_options<T: Serialize>(
1719        activity_type: impl Into<String>,
1720        options: ActivityOptions,
1721        args: T,
1722    ) -> Self {
1723        Self::Activity {
1724            activity_type: activity_type.into(),
1725            options,
1726            arguments: AvroValue::from_serialize(&args),
1727        }
1728    }
1729
1730    pub fn child_workflow<T: Serialize>(
1731        workflow_type: impl Into<String>,
1732        options: ChildWorkflowOptions,
1733        args: T,
1734    ) -> Self {
1735        Self::ChildWorkflow {
1736            workflow_type: workflow_type.into(),
1737            options,
1738            arguments: AvroValue::from_serialize(&args),
1739        }
1740    }
1741
1742    pub fn timer(duration: Duration) -> Self {
1743        Self::Timer(duration)
1744    }
1745
1746    pub fn signal(signal_name: impl Into<String>) -> Self {
1747        Self::Signal(signal_name.into())
1748    }
1749
1750    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1751    where
1752        F: Fn() -> Result<bool> + Send + 'static,
1753    {
1754        Self::Condition {
1755            options,
1756            predicate: Box::new(predicate),
1757        }
1758    }
1759
1760    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1761        Self::Group(operations)
1762    }
1763}
1764
1765#[derive(Clone, Debug)]
1766struct ValidatedActivityOptions {
1767    task_queue: Option<String>,
1768    retry_policy: Option<Value>,
1769    start_to_close_timeout: Option<u64>,
1770    schedule_to_start_timeout: Option<u64>,
1771    schedule_to_close_timeout: Option<u64>,
1772    heartbeat_timeout: Option<u64>,
1773    cancellation_policy: Option<CancellationPolicy>,
1774}
1775
1776fn validate_timeout_order(
1777    smaller_name: &'static str,
1778    smaller: Option<Duration>,
1779    larger_name: &'static str,
1780    larger: Option<Duration>,
1781) -> std::result::Result<(), ActivityOptionsError> {
1782    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1783        return Err(ActivityOptionsError::new(
1784            ActivityOptionsErrorKind::TimeoutOrder,
1785            Some(smaller_name),
1786            format!("{smaller_name} must be <= {larger_name}"),
1787        ));
1788    }
1789    Ok(())
1790}
1791
1792fn timeout_seconds(
1793    field: &'static str,
1794    value: Option<Duration>,
1795) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1796    value
1797        .map(|value| {
1798            activity_protocol_seconds(value).ok_or_else(|| {
1799                ActivityOptionsError::new(
1800                    ActivityOptionsErrorKind::TimeoutOverflow,
1801                    Some(field),
1802                    format!("{field} is too large for the worker protocol"),
1803                )
1804            })
1805        })
1806        .transpose()
1807}
1808
1809fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1810    value
1811        .as_secs()
1812        .checked_add(u64::from(value.subsec_nanos() > 0))
1813}
1814
1815fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1816    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1817}
1818
1819fn validate_activity_retry_policy(
1820    policy: &ActivityRetryPolicy,
1821) -> std::result::Result<Value, ActivityOptionsError> {
1822    if policy.max_attempts.is_none()
1823        && policy.backoff.is_none()
1824        && policy.non_retryable_error_types.is_empty()
1825    {
1826        return Err(ActivityOptionsError::new(
1827            ActivityOptionsErrorKind::EmptyRetryPolicy,
1828            Some("retry_policy"),
1829            "retry_policy must configure at least one field",
1830        ));
1831    }
1832    if policy.max_attempts == Some(0) {
1833        return Err(ActivityOptionsError::new(
1834            ActivityOptionsErrorKind::InvalidMaxAttempts,
1835            Some("retry_policy.max_attempts"),
1836            "max_attempts must be >= 1",
1837        ));
1838    }
1839    if policy
1840        .non_retryable_error_types
1841        .iter()
1842        .any(|error_type| error_type.trim().is_empty())
1843    {
1844        return Err(ActivityOptionsError::new(
1845            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
1846            Some("retry_policy.non_retryable_error_types"),
1847            "non_retryable_error_types must not contain empty values",
1848        ));
1849    }
1850
1851    let backoff_seconds = match &policy.backoff {
1852        None => None,
1853        Some(backoff) => {
1854            let max_attempts = policy.max_attempts.ok_or_else(|| {
1855                ActivityOptionsError::new(
1856                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
1857                    Some("retry_policy.backoff"),
1858                    "backoff requires max_attempts",
1859                )
1860            })?;
1861            let retry_count = max_attempts.saturating_sub(1) as usize;
1862            let intervals = match backoff {
1863                ActivityBackoff::Explicit(intervals) => {
1864                    if intervals.len() > retry_count {
1865                        return Err(ActivityOptionsError::new(
1866                            ActivityOptionsErrorKind::TooManyBackoffIntervals,
1867                            Some("retry_policy.backoff"),
1868                            "backoff interval count must not exceed max_attempts - 1",
1869                        ));
1870                    }
1871                    intervals.clone()
1872                }
1873                ActivityBackoff::Exponential {
1874                    initial_interval,
1875                    coefficient,
1876                    maximum_interval,
1877                } => {
1878                    if *coefficient < 1 {
1879                        return Err(ActivityOptionsError::new(
1880                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
1881                            Some("retry_policy.backoff.coefficient"),
1882                            "backoff coefficient must be >= 1",
1883                        ));
1884                    }
1885                    if retry_count > 10_000 {
1886                        return Err(ActivityOptionsError::new(
1887                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
1888                            Some("retry_policy.max_attempts"),
1889                            "generated backoff supports at most 10000 retry intervals",
1890                        ));
1891                    }
1892                    let mut current = *initial_interval;
1893                    let mut intervals = Vec::with_capacity(retry_count);
1894                    for _ in 0..retry_count {
1895                        let interval = maximum_interval
1896                            .map(|maximum| current.min(maximum))
1897                            .unwrap_or(current);
1898                        intervals.push(interval);
1899                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
1900                            break;
1901                        }
1902                        current = current.checked_mul(*coefficient).ok_or_else(|| {
1903                            ActivityOptionsError::new(
1904                                ActivityOptionsErrorKind::BackoffOverflow,
1905                                Some("retry_policy.backoff"),
1906                                "generated backoff interval overflowed",
1907                            )
1908                        })?;
1909                    }
1910                    intervals
1911                }
1912            };
1913            Some(
1914                intervals
1915                    .into_iter()
1916                    .map(|interval| {
1917                        activity_protocol_seconds(interval).ok_or_else(|| {
1918                            ActivityOptionsError::new(
1919                                ActivityOptionsErrorKind::BackoffOverflow,
1920                                Some("retry_policy.backoff"),
1921                                "backoff interval is too large for the worker protocol",
1922                            )
1923                        })
1924                    })
1925                    .collect::<std::result::Result<Vec<_>, _>>()?,
1926            )
1927        }
1928    };
1929
1930    let mut encoded = serde_json::Map::new();
1931    if let Some(max_attempts) = policy.max_attempts {
1932        encoded.insert("max_attempts".to_string(), json!(max_attempts));
1933    }
1934    if let Some(backoff_seconds) = backoff_seconds {
1935        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
1936    }
1937    if !policy.non_retryable_error_types.is_empty() {
1938        let mut canonical_error_types = Vec::new();
1939        for error_type in policy
1940            .non_retryable_error_types
1941            .iter()
1942            .map(|error_type| error_type.trim())
1943        {
1944            if !canonical_error_types.contains(&error_type) {
1945                canonical_error_types.push(error_type);
1946            }
1947        }
1948        encoded.insert(
1949            "non_retryable_error_types".to_string(),
1950            json!(canonical_error_types),
1951        );
1952    }
1953    Ok(Value::Object(encoded))
1954}
1955
1956/// A stable, machine-readable failure raised when workflow code no longer
1957/// reconstructs the durable command stream recorded in history.
1958#[derive(Clone, Debug, Error)]
1959#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
1960pub struct ReplayFailure {
1961    pub reason: String,
1962    pub sequence: Option<u64>,
1963    pub expected: Option<String>,
1964    pub actual: Option<String>,
1965    pub message: String,
1966}
1967
1968impl ReplayFailure {
1969    fn new(
1970        reason: impl Into<String>,
1971        sequence: Option<u64>,
1972        expected: Option<String>,
1973        actual: Option<String>,
1974        message: impl Into<String>,
1975    ) -> Self {
1976        Self {
1977            reason: reason.into(),
1978            sequence,
1979            expected,
1980            actual,
1981            message: message.into(),
1982        }
1983    }
1984}
1985
1986/// A stable, machine-readable workflow query or query-task settlement failure.
1987#[derive(Clone, Debug, Error)]
1988#[error("query failed ({reason}, HTTP {status}): {message}")]
1989pub struct QueryFailure {
1990    pub status: u16,
1991    pub reason: String,
1992    pub message: String,
1993    pub body: Value,
1994}
1995
1996/// A stable failure returned when a server rejects an SDK protocol version.
1997#[derive(Clone, Debug, Error)]
1998#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
1999pub struct ProtocolFailure {
2000    pub status: u16,
2001    pub reason: String,
2002    pub message: String,
2003    pub supported_version: Option<String>,
2004    pub requested_version: Option<String>,
2005    pub body: Value,
2006}
2007
2008#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2009pub struct PayloadEnvelope {
2010    pub codec: String,
2011    pub blob: String,
2012}
2013
2014impl PayloadEnvelope {
2015    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2016        encode_payload(value, DEFAULT_CODEC)
2017    }
2018
2019    /// Encode an explicit typed value, including the bytes branch that JSON
2020    /// serialization cannot represent.
2021    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2022        encode_avro_value(value)
2023    }
2024}
2025
2026/// Native adapter for the fixed language-neutral Avro Value schema.
2027#[derive(Clone, Debug)]
2028pub enum AvroValue {
2029    Null,
2030    Boolean(bool),
2031    Long(i64),
2032    Double(f64),
2033    Bytes(Vec<u8>),
2034    String(String),
2035    Array(Vec<AvroValue>),
2036    Map(BTreeMap<String, AvroValue>),
2037}
2038
2039impl PartialEq for AvroValue {
2040    fn eq(&self, other: &Self) -> bool {
2041        match (self, other) {
2042            (Self::Null, Self::Null) => true,
2043            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2044            (Self::Long(left), Self::Long(right)) => left == right,
2045            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2046            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2047            (Self::String(left), Self::String(right)) => left == right,
2048            (Self::Array(left), Self::Array(right)) => left == right,
2049            (Self::Map(left), Self::Map(right)) => left == right,
2050            _ => false,
2051        }
2052    }
2053}
2054
2055impl AvroValue {
2056    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2057        Self::from_serde_value(
2058            serde_value::to_value(value).map_err(|error| {
2059                Error::Codec(format!("could not adapt value for Avro: {error}"))
2060            })?,
2061        )
2062    }
2063
2064    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2065        use serde_value::Value as SerdeValue;
2066
2067        match value {
2068            SerdeValue::Unit => Ok(Self::Null),
2069            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2070            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2071            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2072            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2073            SerdeValue::I64(value) => Ok(Self::Long(value)),
2074            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2075            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2076            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2077            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2078                Error::Codec(
2079                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2080                        .to_string(),
2081                )
2082            }),
2083            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2084            SerdeValue::F64(value) => Self::finite_double(value),
2085            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2086            SerdeValue::String(value) => Ok(Self::String(value)),
2087            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2088            SerdeValue::Option(None) => Ok(Self::Null),
2089            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2090                Self::from_serde_value(*value)
2091            }
2092            SerdeValue::Seq(values) => values
2093                .into_iter()
2094                .map(Self::from_serde_value)
2095                .collect::<Result<Vec<_>>>()
2096                .map(Self::Array),
2097            SerdeValue::Map(values) => values
2098                .into_iter()
2099                .map(|(key, value)| {
2100                    let SerdeValue::String(key) = key else {
2101                        return Err(Error::Codec(
2102                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2103                        ));
2104                    };
2105
2106                    Ok((key, Self::from_serde_value(value)?))
2107                })
2108                .collect::<Result<BTreeMap<_, _>>>()
2109                .map(Self::Map),
2110        }
2111    }
2112
2113    fn finite_double(value: f64) -> Result<Self> {
2114        if !value.is_finite() {
2115            return Err(Error::Codec(
2116                "non_finite_float: Avro Value doubles must be finite".to_string(),
2117            ));
2118        }
2119
2120        Ok(Self::Double(value))
2121    }
2122
2123    fn into_json(self) -> Result<Value> {
2124        match self {
2125            Self::Null => Ok(Value::Null),
2126            Self::Boolean(value) => Ok(Value::Bool(value)),
2127            Self::Long(value) => Ok(Value::Number(value.into())),
2128            Self::Double(value) => serde_json::Number::from_f64(value)
2129                .map(Value::Number)
2130                .ok_or_else(|| {
2131                    Error::Codec(
2132                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2133                    )
2134                }),
2135            Self::Bytes(value) => Ok(json!({
2136                "$type": "bytes",
2137                "base64": BASE64.encode(value),
2138            })),
2139            Self::String(value) => Ok(Value::String(value)),
2140            Self::Array(values) => values
2141                .into_iter()
2142                .map(Self::into_json)
2143                .collect::<Result<Vec<_>>>()
2144                .map(Value::Array),
2145            Self::Map(values) => values
2146                .into_iter()
2147                .map(|(key, value)| Ok((key, value.into_json()?)))
2148                .collect::<Result<serde_json::Map<_, _>>>()
2149                .map(Value::Object),
2150        }
2151    }
2152
2153    fn into_serde_value(self) -> serde_value::Value {
2154        use serde_value::Value as SerdeValue;
2155
2156        match self {
2157            Self::Null => SerdeValue::Unit,
2158            Self::Boolean(value) => SerdeValue::Bool(value),
2159            Self::Long(value) => SerdeValue::I64(value),
2160            Self::Double(value) => SerdeValue::F64(value),
2161            Self::Bytes(value) => SerdeValue::Bytes(value),
2162            Self::String(value) => SerdeValue::String(value),
2163            Self::Array(values) => {
2164                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2165            }
2166            Self::Map(values) => SerdeValue::Map(
2167                values
2168                    .into_iter()
2169                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2170                    .collect(),
2171            ),
2172        }
2173    }
2174
2175    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2176        self.into_serde_value().deserialize_into().map_err(|error| {
2177            Error::Codec(format!(
2178                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2179            ))
2180        })
2181    }
2182}
2183
2184impl Serialize for AvroValue {
2185    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2186    where
2187        S: Serializer,
2188    {
2189        match self {
2190            Self::Null => serializer.serialize_unit(),
2191            Self::Boolean(value) => serializer.serialize_bool(*value),
2192            Self::Long(value) => serializer.serialize_i64(*value),
2193            Self::Double(value) => serializer.serialize_f64(*value),
2194            Self::Bytes(value) => serializer.serialize_bytes(value),
2195            Self::String(value) => serializer.serialize_str(value),
2196            Self::Array(values) => {
2197                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2198                for value in values {
2199                    sequence.serialize_element(value)?;
2200                }
2201                sequence.end()
2202            }
2203            Self::Map(values) => {
2204                let mut map = serializer.serialize_map(Some(values.len()))?;
2205                for (key, value) in values {
2206                    map.serialize_entry(key, value)?;
2207                }
2208                map.end()
2209            }
2210        }
2211    }
2212}
2213
2214pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2215    let datum = avro_value_to_datum(value)?;
2216    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2217        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2218    let mut bytes = Vec::with_capacity(datum.len() + 10);
2219    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2220    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2221    bytes.extend_from_slice(&datum);
2222    Ok(PayloadEnvelope {
2223        codec: DEFAULT_CODEC.to_string(),
2224        blob: BASE64.encode(bytes),
2225    })
2226}
2227
2228pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2229    if envelope.codec != DEFAULT_CODEC {
2230        return Err(unsupported_payload_codec(&envelope.codec));
2231    }
2232    decode_avro_value_blob(&envelope.blob)
2233}
2234
2235pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2236    let blob = match codec {
2237        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2238        other => return Err(unsupported_payload_codec(other)),
2239    };
2240
2241    Ok(PayloadEnvelope {
2242        codec: codec.to_string(),
2243        blob,
2244    })
2245}
2246
2247pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2248    match envelope.codec.as_str() {
2249        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2250        other => Err(unsupported_payload_codec(other)),
2251    }
2252}
2253
2254fn handler_type_error<T>(
2255    handler_kind: HandlerKind,
2256    handler_name: &str,
2257    value_kind: HandlerValueKind,
2258    message: impl Into<String>,
2259) -> Error {
2260    Error::HandlerType {
2261        handler_kind,
2262        handler_name: handler_name.to_string(),
2263        value_kind,
2264        rust_type: type_name::<T>(),
2265        message: message.into(),
2266    }
2267}
2268
2269fn decode_handler_input<T: DeserializeOwned>(
2270    arguments: AvroValue,
2271    handler_kind: HandlerKind,
2272    handler_name: &str,
2273) -> Result<T> {
2274    let argument = match arguments {
2275        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2276            arguments.pop().expect("one typed handler argument")
2277        }
2278        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2279        AvroValue::Array(arguments) => {
2280            return Err(handler_type_error::<T>(
2281                handler_kind,
2282                handler_name,
2283                HandlerValueKind::Input,
2284                format!(
2285                    "typed handlers accept one request value, but the task carried {} arguments",
2286                    arguments.len()
2287                ),
2288            ));
2289        }
2290        argument => argument,
2291    };
2292
2293    argument.deserialize().map_err(|error| {
2294        handler_type_error::<T>(
2295            handler_kind,
2296            handler_name,
2297            HandlerValueKind::Input,
2298            error.to_string(),
2299        )
2300    })
2301}
2302
2303fn encode_handler_result<T: Serialize>(
2304    result: &T,
2305    handler_kind: HandlerKind,
2306    handler_name: &str,
2307) -> Result<AvroValue> {
2308    AvroValue::from_serialize(result).map_err(|error| {
2309        handler_type_error::<T>(
2310            handler_kind,
2311            handler_name,
2312            HandlerValueKind::Result,
2313            error.to_string(),
2314        )
2315    })
2316}
2317
2318fn decode_handler_result<T: DeserializeOwned>(
2319    result: AvroValue,
2320    handler_kind: HandlerKind,
2321    handler_name: &str,
2322) -> Result<T> {
2323    result.deserialize().map_err(|error| {
2324        handler_type_error::<T>(
2325            handler_kind,
2326            handler_name,
2327            HandlerValueKind::Result,
2328            error.to_string(),
2329        )
2330    })
2331}
2332
2333#[cfg(test)]
2334fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2335    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2336}
2337
2338fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2339    validate_payload_codec(fallback_codec)?;
2340
2341    if value.is_null() {
2342        return Ok(Value::Null);
2343    }
2344
2345    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2346        return decode_blob(blob, codec);
2347    }
2348
2349    if let Some(blob) = value.as_str() {
2350        return decode_blob(blob, fallback_codec);
2351    }
2352
2353    Err(untagged_payload_value())
2354}
2355
2356fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2357    let envelope = match codec {
2358        DEFAULT_CODEC => encode_avro_value(value)?,
2359        other => return Err(unsupported_payload_codec(other)),
2360    };
2361    Ok(serde_json::to_value(envelope)?)
2362}
2363
2364fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2365    validate_payload_codec(fallback_codec)?;
2366
2367    if value.is_null() {
2368        return Ok(AvroValue::Null);
2369    }
2370
2371    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2372        validate_payload_codec(codec)?;
2373        return decode_avro_value_blob(blob);
2374    }
2375
2376    if let Some(blob) = value.as_str() {
2377        return match fallback_codec {
2378            DEFAULT_CODEC => decode_avro_value_blob(blob),
2379            other => Err(unsupported_payload_codec(other)),
2380        };
2381    }
2382
2383    Err(untagged_payload_value())
2384}
2385
2386fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2387    match value {
2388        AvroValue::Null => AvroValue::Array(Vec::new()),
2389        AvroValue::Array(_) => value,
2390        other => AvroValue::Array(vec![other]),
2391    }
2392}
2393
2394fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2395    match codec {
2396        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2397        other => Err(unsupported_payload_codec(other)),
2398    }
2399}
2400
2401fn validate_payload_codec(codec: &str) -> Result<()> {
2402    match codec {
2403        DEFAULT_CODEC => Ok(()),
2404        MISSING_TASK_PAYLOAD_CODEC => {
2405            Err(invalid_task_payload_codec("task payload_codec is missing"))
2406        }
2407        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2408        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2409            "task payload_codec must be a string",
2410        )),
2411        other => Err(unsupported_payload_codec(other)),
2412    }
2413}
2414
2415fn invalid_task_payload_codec(reason: &str) -> Error {
2416    Error::Codec(format!(
2417        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2418    ))
2419}
2420
2421fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2422    let Some(object) = value.as_object() else {
2423        return Ok(None);
2424    };
2425    if !object.contains_key("codec") && !object.contains_key("blob") {
2426        return Ok(None);
2427    }
2428
2429    let codec = object
2430        .get("codec")
2431        .and_then(Value::as_str)
2432        .ok_or_else(invalid_payload_envelope)?;
2433    validate_payload_codec(codec)?;
2434    let blob = object
2435        .get("blob")
2436        .and_then(Value::as_str)
2437        .ok_or_else(invalid_payload_envelope)?;
2438    Ok(Some((codec, blob)))
2439}
2440
2441fn invalid_payload_envelope() -> Error {
2442    Error::Codec(
2443        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2444            .to_string(),
2445    )
2446}
2447
2448fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2449    for command in commands {
2450        let Some(command) = command.as_object() else {
2451            continue;
2452        };
2453        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2454            continue;
2455        };
2456        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2457            continue;
2458        };
2459
2460        if let Some(codec) = command.get("payload_codec") {
2461            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2462            validate_payload_codec(codec)?;
2463        }
2464
2465        let payload = command
2466            .get(payload_field)
2467            .ok_or_else(invalid_payload_envelope)?;
2468        if runtime_payloads::Reference::parse(payload)?.is_none() {
2469            validate_outbound_payload_envelope(payload)?;
2470        }
2471    }
2472    Ok(())
2473}
2474
2475fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2476    if commands.iter().any(|command| {
2477        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2478            && command
2479                .get("condition_wait_occurrence_id")
2480                .and_then(Value::as_str)
2481                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2482    }) {
2483        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2484    } else if commands.iter().any(|command| {
2485        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2486            && command.get("attribute_types").is_some()
2487    }) {
2488        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2489    } else if commands
2490        .iter()
2491        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2492    {
2493        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2494    } else if commands
2495        .iter()
2496        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2497    {
2498        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2499    } else if commands.iter().any(|command| {
2500        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2501    }) {
2502        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2503    } else {
2504        MINIMUM_WORKER_PROTOCOL_VERSION
2505    }
2506}
2507
2508fn workflow_completion_protocol_version_with_message_streams(
2509    commands: &[Value],
2510    has_message_stream_metadata: bool,
2511) -> &'static str {
2512    let command_protocol = workflow_completion_protocol_version(commands);
2513    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2514        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2515    } else {
2516        command_protocol
2517    }
2518}
2519
2520fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2521    match command_type {
2522        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2523        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2524        "start_service_operation" => Some("request_payload"),
2525        "upsert_memo" => Some("entries"),
2526        _ => None,
2527    }
2528}
2529
2530fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2531    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2532        return Err(untagged_payload_value());
2533    };
2534    validate_payload_codec(codec)?;
2535    decode_avro_value_blob(blob)?;
2536    Ok(())
2537}
2538
2539fn unsupported_payload_codec(codec: &str) -> Error {
2540    Error::Codec(format!(
2541        "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"
2542    ))
2543}
2544
2545fn untagged_payload_value() -> Error {
2546    Error::Codec(
2547        "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"
2548            .to_string(),
2549    )
2550}
2551
2552fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2553    let bytes = BASE64.decode(blob).map_err(|err| {
2554        Error::Codec(format!(
2555            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2556        ))
2557    })?;
2558
2559    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2560        return Err(unsupported_payload_codec("json"));
2561    }
2562
2563    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2564        return Err(Error::Codec(
2565            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2566        ));
2567    }
2568
2569    let fingerprint: [u8; 8] = bytes[2..10]
2570        .try_into()
2571        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2572    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2573        return Err(Error::Codec(format!(
2574            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2575            fingerprint
2576                .iter()
2577                .map(|byte| format!("{byte:02x}"))
2578                .collect::<String>()
2579        )));
2580    }
2581
2582    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2583    // The current fingerprint selects the current immutable schema, so reader
2584    // resolution would only re-walk the same recursive union. Future retained
2585    // writer fingerprints supply a distinct reader schema in this branch.
2586    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2587    if datum_reader.truncated {
2588        return Err(Error::Codec(
2589            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2590        ));
2591    }
2592    let datum = datum.map_err(|err| {
2593        Error::Codec(format!(
2594            "invalid_payload_framing: malformed Avro Value datum: {err}"
2595        ))
2596    })?;
2597    if datum_reader.remaining() != 0 {
2598        return Err(Error::Codec(format!(
2599            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2600            datum_reader.remaining()
2601        )));
2602    }
2603    avro_value_from_datum(datum)
2604}
2605
2606struct StrictAvroDatumReader<'a> {
2607    bytes: &'a [u8],
2608    offset: usize,
2609    truncated: bool,
2610}
2611
2612impl<'a> StrictAvroDatumReader<'a> {
2613    fn new(bytes: &'a [u8]) -> Self {
2614        Self {
2615            bytes,
2616            offset: 0,
2617            truncated: false,
2618        }
2619    }
2620
2621    fn remaining(&self) -> usize {
2622        self.bytes.len() - self.offset
2623    }
2624}
2625
2626impl Read for StrictAvroDatumReader<'_> {
2627    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2628        let count = buffer.len().min(self.remaining());
2629        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2630        self.offset += count;
2631        if count < buffer.len() {
2632            self.truncated = true;
2633        }
2634
2635        Ok(count)
2636    }
2637}
2638
2639fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2640    let branch = match value {
2641        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2642        AvroValue::Boolean(value) => AvroDatum::Union(
2643            1,
2644            Box::new(AvroDatum::Record(vec![(
2645                "boolean".to_string(),
2646                AvroDatum::Boolean(*value),
2647            )])),
2648        ),
2649        AvroValue::Long(value) => AvroDatum::Union(
2650            2,
2651            Box::new(AvroDatum::Record(vec![(
2652                "long".to_string(),
2653                AvroDatum::Long(*value),
2654            )])),
2655        ),
2656        AvroValue::Double(value) => {
2657            if !value.is_finite() {
2658                return Err(Error::Codec(
2659                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2660                ));
2661            }
2662            AvroDatum::Union(
2663                3,
2664                Box::new(AvroDatum::Record(vec![(
2665                    "double".to_string(),
2666                    AvroDatum::Double(*value),
2667                )])),
2668            )
2669        }
2670        AvroValue::Bytes(value) => AvroDatum::Union(
2671            4,
2672            Box::new(AvroDatum::Record(vec![(
2673                "bytes".to_string(),
2674                AvroDatum::Bytes(value.clone()),
2675            )])),
2676        ),
2677        AvroValue::String(value) => AvroDatum::Union(
2678            5,
2679            Box::new(AvroDatum::Record(vec![(
2680                "string".to_string(),
2681                AvroDatum::String(value.clone()),
2682            )])),
2683        ),
2684        AvroValue::Array(values) => AvroDatum::Union(
2685            6,
2686            Box::new(AvroDatum::Record(vec![(
2687                "items".to_string(),
2688                AvroDatum::Array(
2689                    values
2690                        .iter()
2691                        .map(avro_value_to_datum)
2692                        .collect::<Result<Vec<_>>>()?,
2693                ),
2694            )])),
2695        ),
2696        AvroValue::Map(values) => AvroDatum::Union(
2697            7,
2698            Box::new(AvroDatum::Record(vec![(
2699                "entries".to_string(),
2700                AvroDatum::Array(
2701                    values
2702                        .iter()
2703                        .map(|(key, value)| {
2704                            Ok(AvroDatum::Record(vec![
2705                                ("key".to_string(), AvroDatum::String(key.clone())),
2706                                ("value".to_string(), avro_value_to_datum(value)?),
2707                            ]))
2708                        })
2709                        .collect::<Result<Vec<_>>>()?,
2710                ),
2711            )])),
2712        ),
2713    };
2714    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2715}
2716
2717fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2718    let AvroDatum::Record(mut outer) = datum else {
2719        return Err(Error::Codec(
2720            "invalid_payload_framing: datum is not a Value record".to_string(),
2721        ));
2722    };
2723    let (_, branch) = outer
2724        .pop()
2725        .filter(|(name, _)| name == "value")
2726        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2727    let AvroDatum::Union(_, branch) = branch else {
2728        return Err(Error::Codec(
2729            "invalid_payload_framing: invalid Value union".to_string(),
2730        ));
2731    };
2732    match *branch {
2733        AvroDatum::Null => Ok(AvroValue::Null),
2734        AvroDatum::Record(mut fields) => {
2735            let (name, value) = fields.pop().ok_or_else(|| {
2736                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2737            })?;
2738            match (name.as_str(), value) {
2739                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2740                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2741                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2742                    Ok(AvroValue::Double(value))
2743                }
2744                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2745                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2746                ("items", AvroDatum::Array(values)) => values
2747                    .into_iter()
2748                    .map(avro_value_from_datum)
2749                    .collect::<Result<Vec<_>>>()
2750                    .map(AvroValue::Array),
2751                ("entries", AvroDatum::Map(values)) => values
2752                    .into_iter()
2753                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2754                    .collect::<Result<BTreeMap<_, _>>>()
2755                    .map(AvroValue::Map),
2756                _ => Err(Error::Codec(
2757                    "invalid_payload_framing: unknown Value branch".to_string(),
2758                )),
2759            }
2760        }
2761        _ => Err(Error::Codec(
2762            "invalid_payload_framing: invalid Value branch".to_string(),
2763        )),
2764    }
2765}
2766
2767fn avro_value_schema() -> Result<&'static Schema> {
2768    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2769        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2770            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2771    }) {
2772        Ok(schema) => Ok(schema),
2773        Err(message) => Err(Error::Codec(message.clone())),
2774    }
2775}
2776
2777fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2778    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2779        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2780        // have the same block representation when each ordered array record
2781        // contains the map key followed by its value, so this encoding-only
2782        // adaptation lets the official encoder retain BTreeMap wire order.
2783        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2784            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2785        let entries_schema = schema
2786            .pointer_mut("/fields/0/type/7/fields/0/type")
2787            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2788        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2789            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2790        }
2791        *entries_schema = json!({
2792            "type": "array",
2793            "items": {
2794                "type": "record",
2795                "name": "MapEntry",
2796                "fields": [
2797                    {"name": "key", "type": "string"},
2798                    {"name": "value", "type": "Value"}
2799                ]
2800            }
2801        });
2802        Schema::parse_str(&schema.to_string())
2803            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2804    }) {
2805        Ok(schema) => Ok(schema),
2806        Err(message) => Err(Error::Codec(message.clone())),
2807    }
2808}
2809
2810#[derive(Clone, Debug)]
2811pub struct Client {
2812    http: reqwest::Client,
2813    hydration_timeout: Duration,
2814    base_url: String,
2815    token: Option<String>,
2816    control_token: Option<String>,
2817    worker_token: Option<String>,
2818    namespace: String,
2819    max_external_payload_bytes: usize,
2820    worker_storage_admission: Option<WorkerStorageAdmission>,
2821    cooperative_worker_protocol: bool,
2822    worker_protocol_version: WorkerProtocolVersion,
2823    local_activities_enabled: bool,
2824    worker_sessions_enabled: bool,
2825    max_concurrent_worker_sessions: usize,
2826    worker_build_id: Option<String>,
2827    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2828    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2829}
2830
2831impl Client {
2832    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2833        Self::builder(base_url).build()
2834    }
2835
2836    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2837        ClientBuilder {
2838            base_url: base_url.into(),
2839            token: None,
2840            control_token: None,
2841            worker_token: None,
2842            namespace: "default".to_string(),
2843            timeout: Duration::from_secs(60),
2844            max_external_payload_bytes: 64 * 1024 * 1024,
2845            worker_protocol_version: WorkerProtocolVersion::default(),
2846        }
2847    }
2848
2849    pub async fn health(&self) -> Result<Value> {
2850        self.request_json(
2851            reqwest::Method::GET,
2852            "/health",
2853            RequestProtocol::ControlPlane,
2854            Option::<&Value>::None,
2855        )
2856        .await
2857    }
2858
2859    pub async fn cluster_info(&self) -> Result<Value> {
2860        self.request_json(
2861            reqwest::Method::GET,
2862            "/cluster/info",
2863            RequestProtocol::ControlPlane,
2864            Option::<&Value>::None,
2865        )
2866        .await
2867    }
2868
2869    pub async fn start_workflow<T: Serialize>(
2870        &self,
2871        workflow_type: &str,
2872        task_queue: &str,
2873        workflow_id: &str,
2874        input: T,
2875    ) -> Result<WorkflowHandle> {
2876        self.start_workflow_with_options(
2877            workflow_type,
2878            task_queue,
2879            workflow_id,
2880            WorkflowStartOptions::default(),
2881            input,
2882        )
2883        .await
2884    }
2885
2886    /// Start a workflow with explicit server-enforced execution and run
2887    /// deadlines.
2888    pub async fn start_workflow_with_options<T: Serialize>(
2889        &self,
2890        workflow_type: &str,
2891        task_queue: &str,
2892        workflow_id: &str,
2893        options: WorkflowStartOptions,
2894        input: T,
2895    ) -> Result<WorkflowHandle> {
2896        options.validate()?;
2897        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2898        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2899        let body = json!({
2900            "workflow_id": workflow_id,
2901            "workflow_type": workflow_type,
2902            "task_queue": task_queue,
2903            "input": input_envelope,
2904            "execution_timeout_seconds": options.execution_timeout_seconds,
2905            "run_timeout_seconds": options.run_timeout_seconds
2906        });
2907
2908        let data: Value = self
2909            .request_json(
2910                reqwest::Method::POST,
2911                "/workflows",
2912                RequestProtocol::ControlPlane,
2913                Some(&body),
2914            )
2915            .await?;
2916
2917        Ok(WorkflowHandle {
2918            client: self.clone(),
2919            workflow_id: data
2920                .get("workflow_id")
2921                .and_then(Value::as_str)
2922                .unwrap_or(workflow_id)
2923                .to_string(),
2924            run_id: data
2925                .get("run_id")
2926                .and_then(Value::as_str)
2927                .map(str::to_string),
2928            workflow_type: data
2929                .get("workflow_type")
2930                .and_then(Value::as_str)
2931                .unwrap_or(workflow_type)
2932                .to_string(),
2933        })
2934    }
2935
2936    pub async fn signal_workflow<T: Serialize>(
2937        &self,
2938        workflow_id: &str,
2939        signal_name: &str,
2940        input: T,
2941    ) -> Result<Value> {
2942        self.signal_workflow_target(workflow_id, None, signal_name, input)
2943            .await
2944    }
2945
2946    /// Append one idempotently identified item to an instance-scoped input stream.
2947    pub async fn append_message_stream<T: Serialize>(
2948        &self,
2949        workflow_id: &str,
2950        stream_name: &str,
2951        message_id: &str,
2952        input: T,
2953    ) -> Result<Value> {
2954        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2955        let body = json!({
2956            "message_id": message_id,
2957            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2958        });
2959        self.request_json(
2960            reqwest::Method::POST,
2961            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2962            RequestProtocol::ControlPlane,
2963            Some(&body),
2964        )
2965        .await
2966    }
2967
2968    /// Signal only if `run_id` is still the current run for this instance.
2969    pub async fn signal_workflow_run<T: Serialize>(
2970        &self,
2971        workflow_id: &str,
2972        run_id: &str,
2973        signal_name: &str,
2974        input: T,
2975    ) -> Result<Value> {
2976        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
2977            .await
2978    }
2979
2980    async fn signal_workflow_target<T: Serialize>(
2981        &self,
2982        workflow_id: &str,
2983        run_id: Option<&str>,
2984        signal_name: &str,
2985        input: T,
2986    ) -> Result<Value> {
2987        validate_user_signal_name(signal_name)?;
2988        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2989        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2990        let body = json!({
2991            "input": input_envelope
2992        });
2993        let path = match run_id {
2994            Some(run_id) => {
2995                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
2996            }
2997            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
2998        };
2999        self.request_json(
3000            reqwest::Method::POST,
3001            &path,
3002            RequestProtocol::ControlPlane,
3003            Some(&body),
3004        )
3005        .await
3006    }
3007
3008    /// Close the current run as cancelled immediately.
3009    ///
3010    /// Server revokes open tasks and timers without resuming workflow code for
3011    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3012    /// request on a supporting runtime and opted-in worker.
3013    pub async fn cancel_workflow(
3014        &self,
3015        workflow_id: &str,
3016        options: WorkflowCommandOptions,
3017    ) -> Result<WorkflowCommandResult> {
3018        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3019            .await
3020    }
3021
3022    /// Close the selected run as cancelled, only if `run_id` is still current.
3023    pub async fn cancel_workflow_run(
3024        &self,
3025        workflow_id: &str,
3026        run_id: &str,
3027        options: WorkflowCommandOptions,
3028    ) -> Result<WorkflowCommandResult> {
3029        self.workflow_command(
3030            workflow_id,
3031            Some(run_id),
3032            WorkflowCommandKind::Cancel,
3033            options,
3034        )
3035        .await
3036    }
3037
3038    /// Forcefully terminate the current run for an instance.
3039    pub async fn terminate_workflow(
3040        &self,
3041        workflow_id: &str,
3042        options: WorkflowCommandOptions,
3043    ) -> Result<WorkflowCommandResult> {
3044        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3045            .await
3046    }
3047
3048    /// Forcefully terminate only if `run_id` is still current.
3049    pub async fn terminate_workflow_run(
3050        &self,
3051        workflow_id: &str,
3052        run_id: &str,
3053        options: WorkflowCommandOptions,
3054    ) -> Result<WorkflowCommandResult> {
3055        self.workflow_command(
3056            workflow_id,
3057            Some(run_id),
3058            WorkflowCommandKind::Terminate,
3059            options,
3060        )
3061        .await
3062    }
3063
3064    /// Continue a failed run from its recorded activity failure boundary.
3065    pub async fn redrive_workflow_run(
3066        &self,
3067        workflow_id: &str,
3068        failed_run_id: &str,
3069        request_id: Option<&str>,
3070    ) -> Result<WorkflowRedriveResult> {
3071        let body = request_id
3072            .map(|id| json!({"request_id": id}))
3073            .unwrap_or_else(|| json!({}));
3074        let data: Value = self
3075            .request_json(
3076                reqwest::Method::POST,
3077                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3078                RequestProtocol::ControlPlane,
3079                Some(&body),
3080            )
3081            .await?;
3082        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3083            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3084        {
3085            return Err(Error::Codec(
3086                "redrive response was not accepted".to_string(),
3087            ));
3088        }
3089        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3090            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3091        {
3092            return Err(Error::Codec(
3093                "redrive response does not match the requested source run".to_string(),
3094            ));
3095        }
3096        let run_id = data
3097            .get("run_id")
3098            .and_then(Value::as_str)
3099            .filter(|id| !id.is_empty() && *id != failed_run_id)
3100            .ok_or_else(|| {
3101                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3102            })?;
3103        let resume_step_sequence = data
3104            .get("resume_step_sequence")
3105            .and_then(Value::as_u64)
3106            .filter(|sequence| *sequence > 0)
3107            .ok_or_else(|| {
3108                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3109            })?;
3110        Ok(WorkflowRedriveResult {
3111            workflow_id: workflow_id.to_string(),
3112            source_run_id: failed_run_id.to_string(),
3113            run_id: run_id.to_string(),
3114            resume_step_sequence,
3115            raw: data,
3116        })
3117    }
3118
3119    async fn workflow_command(
3120        &self,
3121        workflow_id: &str,
3122        run_id: Option<&str>,
3123        command: WorkflowCommandKind,
3124        options: WorkflowCommandOptions,
3125    ) -> Result<WorkflowCommandResult> {
3126        let path = match run_id {
3127            Some(run_id) => format!(
3128                "/workflows/{workflow_id}/runs/{run_id}/{}",
3129                command.as_str()
3130            ),
3131            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3132        };
3133        let data = match self
3134            .request_json(
3135                reqwest::Method::POST,
3136                &path,
3137                RequestProtocol::ControlPlane,
3138                Some(&options),
3139            )
3140            .await
3141        {
3142            Ok(data) => data,
3143            Err(Error::Http { status, body }) => {
3144                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3145                    command,
3146                    status,
3147                    body,
3148                    workflow_id,
3149                    run_id,
3150                )));
3151            }
3152            Err(error) => return Err(error),
3153        };
3154
3155        Ok(workflow_command_result(command, data, workflow_id, run_id))
3156    }
3157
3158    /// Execute a named, read-only query against a running or completed workflow.
3159    ///
3160    /// Arguments and results use the platform payload envelope. Server and
3161    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3162    /// reason, HTTP status, and original response body.
3163    pub async fn query_workflow<T: Serialize>(
3164        &self,
3165        workflow_id: &str,
3166        query_name: &str,
3167        input: T,
3168    ) -> Result<Value> {
3169        self.query_workflow_target(workflow_id, None, query_name, input)
3170            .await
3171    }
3172
3173    /// Query only if `run_id` is still current, preventing accidental retargeting.
3174    pub async fn query_workflow_run<T: Serialize>(
3175        &self,
3176        workflow_id: &str,
3177        run_id: &str,
3178        query_name: &str,
3179        input: T,
3180    ) -> Result<Value> {
3181        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3182            .await
3183    }
3184
3185    /// Query a workflow and return the lossless fixed Avro Value result.
3186    pub async fn query_workflow_avro_value<T: Serialize>(
3187        &self,
3188        workflow_id: &str,
3189        query_name: &str,
3190        input: T,
3191    ) -> Result<AvroValue> {
3192        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3193            .await
3194    }
3195
3196    /// Query a selected run and return the lossless fixed Avro Value result.
3197    pub async fn query_workflow_run_avro_value<T: Serialize>(
3198        &self,
3199        workflow_id: &str,
3200        run_id: &str,
3201        query_name: &str,
3202        input: T,
3203    ) -> Result<AvroValue> {
3204        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3205            .await
3206    }
3207
3208    async fn query_workflow_avro_value_target<T: Serialize>(
3209        &self,
3210        workflow_id: &str,
3211        run_id: Option<&str>,
3212        query_name: &str,
3213        input: T,
3214    ) -> Result<AvroValue> {
3215        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3216        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3217        let path = match run_id {
3218            Some(run_id) => {
3219                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3220            }
3221            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3222        };
3223        let response: Value = match self
3224            .request_json(
3225                reqwest::Method::POST,
3226                &path,
3227                RequestProtocol::ControlPlane,
3228                Some(&body),
3229            )
3230            .await
3231        {
3232            Ok(response) => response,
3233            Err(Error::Http { status, body }) => {
3234                return Err(Error::QueryFailed(query_failure(status, body)));
3235            }
3236            Err(error) => return Err(error),
3237        };
3238
3239        let envelope = response
3240            .get("result_envelope")
3241            .filter(|envelope| !envelope.is_null())
3242            .ok_or_else(|| {
3243                Error::Codec(
3244                    "missing_payload_envelope: typed query result requires result_envelope"
3245                        .to_string(),
3246                )
3247            })?;
3248        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3249    }
3250
3251    async fn query_workflow_target<T: Serialize>(
3252        &self,
3253        workflow_id: &str,
3254        run_id: Option<&str>,
3255        query_name: &str,
3256        input: T,
3257    ) -> Result<Value> {
3258        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3259        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3260        let body = json!({
3261            "input": input_envelope
3262        });
3263        let path = match run_id {
3264            Some(run_id) => {
3265                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3266            }
3267            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3268        };
3269        let response: Value = match self
3270            .request_json(
3271                reqwest::Method::POST,
3272                &path,
3273                RequestProtocol::ControlPlane,
3274                Some(&body),
3275            )
3276            .await
3277        {
3278            Ok(response) => response,
3279            Err(Error::Http { status, body }) => {
3280                return Err(Error::QueryFailed(query_failure(status, body)));
3281            }
3282            Err(error) => return Err(error),
3283        };
3284
3285        if let Some(envelope) = response
3286            .get("result_envelope")
3287            .filter(|envelope| !envelope.is_null())
3288        {
3289            return decode_wire_value(envelope, DEFAULT_CODEC);
3290        }
3291
3292        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3293    }
3294
3295    /// Send a synchronous update using fixed Avro Value arguments.
3296    pub async fn update_workflow<T: Serialize>(
3297        &self,
3298        workflow_id: &str,
3299        update_name: &str,
3300        input: T,
3301        request_id: Option<&str>,
3302    ) -> Result<Value> {
3303        let response = self
3304            .update_workflow_response(workflow_id, update_name, input, request_id)
3305            .await?;
3306        if let Some(envelope) = response
3307            .get("result_envelope")
3308            .filter(|envelope| !envelope.is_null())
3309        {
3310            return decode_wire_value(envelope, DEFAULT_CODEC);
3311        }
3312        Ok(response.get("result").cloned().unwrap_or(response))
3313    }
3314
3315    /// Send a synchronous update and retain a bytes-capable Avro result.
3316    pub async fn update_workflow_avro_value<T: Serialize>(
3317        &self,
3318        workflow_id: &str,
3319        update_name: &str,
3320        input: T,
3321        request_id: Option<&str>,
3322    ) -> Result<AvroValue> {
3323        let response = self
3324            .update_workflow_response(workflow_id, update_name, input, request_id)
3325            .await?;
3326        let envelope = response
3327            .get("result_envelope")
3328            .filter(|envelope| !envelope.is_null())
3329            .ok_or_else(|| {
3330                Error::Codec(
3331                    "missing_payload_envelope: typed update result requires result_envelope"
3332                        .to_string(),
3333                )
3334            })?;
3335        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3336    }
3337
3338    async fn update_workflow_response<T: Serialize>(
3339        &self,
3340        workflow_id: &str,
3341        update_name: &str,
3342        input: T,
3343        request_id: Option<&str>,
3344    ) -> Result<Value> {
3345        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3346        let mut body = json!({
3347            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3348            "wait_for": "completed",
3349        });
3350        if let Some(request_id) = request_id {
3351            body["request_id"] = json!(request_id);
3352        }
3353        self.request_json(
3354            reqwest::Method::POST,
3355            &format!("/workflows/{workflow_id}/update/{update_name}"),
3356            RequestProtocol::ControlPlane,
3357            Some(&body),
3358        )
3359        .await
3360    }
3361
3362    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3363        let path = format!("/workflows/{workflow_id}");
3364        let mut data: WorkflowDescription = self
3365            .request_json(
3366                reqwest::Method::GET,
3367                &path,
3368                RequestProtocol::ControlPlane,
3369                Option::<&Value>::None,
3370            )
3371            .await?;
3372        data.decode_payloads()?;
3373        Ok(data)
3374    }
3375
3376    /// Describe one selected run, including historical terminal runs.
3377    pub async fn describe_workflow_run(
3378        &self,
3379        workflow_id: &str,
3380        run_id: &str,
3381    ) -> Result<WorkflowDescription> {
3382        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3383        let mut data: WorkflowDescription = self
3384            .request_json(
3385                reqwest::Method::GET,
3386                &path,
3387                RequestProtocol::ControlPlane,
3388                Option::<&Value>::None,
3389            )
3390            .await?;
3391        data.decode_payloads()?;
3392        Ok(data)
3393    }
3394
3395    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3396        let mut path = format!(
3397            "/workflows/{}/runs/{}/streams",
3398            percent_encode_path_segment(workflow_id),
3399            percent_encode_path_segment(run_id),
3400        );
3401        if let Some(stream_name) = stream_name {
3402            path.push('/');
3403            path.push_str(&percent_encode_path_segment(stream_name));
3404        }
3405        path
3406    }
3407
3408    /// List the run-scoped output streams already opened by a workflow.
3409    pub async fn list_workflow_streams(
3410        &self,
3411        workflow_id: &str,
3412        run_id: &str,
3413    ) -> Result<Vec<WorkflowStreamDescription>> {
3414        let response: WorkflowStreamListResponse = self
3415            .request_json(
3416                reqwest::Method::GET,
3417                &Self::workflow_stream_path(workflow_id, run_id, None),
3418                RequestProtocol::ControlPlane,
3419                Option::<&Value>::None,
3420            )
3421            .await?;
3422        Ok(response.streams)
3423    }
3424
3425    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3426    pub async fn describe_workflow_stream(
3427        &self,
3428        workflow_id: &str,
3429        run_id: &str,
3430        stream_name: &str,
3431    ) -> Result<WorkflowStreamDescription> {
3432        let response: WorkflowStreamDescriptionResponse = self
3433            .request_json(
3434                reqwest::Method::GET,
3435                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3436                RequestProtocol::ControlPlane,
3437                Option::<&Value>::None,
3438            )
3439            .await?;
3440        Ok(response.stream)
3441    }
3442
3443    /// Read one bounded page beginning at a zero-based offset.
3444    ///
3445    /// Delivery is at least once: persist `next_offset` only after processing
3446    /// the page. The future is cancellation-safe; dropping it cancels the
3447    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3448    /// service contract.
3449    pub async fn subscribe_workflow_stream(
3450        &self,
3451        workflow_id: &str,
3452        run_id: &str,
3453        stream_name: &str,
3454        from_offset: u64,
3455        max_items: usize,
3456        wait: Duration,
3457    ) -> Result<WorkflowStreamPage> {
3458        let max_items = max_items.clamp(1, 500);
3459        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3460        let path = format!(
3461            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3462            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3463        );
3464        let response: WorkflowStreamPageResponse = self
3465            .request_json_with_timeout(
3466                reqwest::Method::GET,
3467                &path,
3468                RequestProtocol::ControlPlane,
3469                Option::<&Value>::None,
3470                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3471            )
3472            .await?;
3473
3474        let items = response
3475            .items
3476            .into_iter()
3477            .map(|raw| {
3478                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3479                let envelope = raw.get("payload").cloned();
3480                let payload = envelope
3481                    .as_ref()
3482                    .filter(|value| value.get("blob").is_some())
3483                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3484                    .transpose()?
3485                    .map(AvroValue::into_json)
3486                    .transpose()?;
3487                Ok(WorkflowStreamItem {
3488                    offset,
3489                    payload,
3490                    payload_envelope: envelope,
3491                    payload_reference: raw
3492                        .get("payload_reference")
3493                        .and_then(Value::as_str)
3494                        .map(str::to_string),
3495                    payload_codec: raw
3496                        .get("payload_codec")
3497                        .and_then(Value::as_str)
3498                        .map(str::to_string),
3499                    idempotency_key: raw
3500                        .get("idempotency_key")
3501                        .and_then(Value::as_str)
3502                        .map(str::to_string),
3503                    item_type: raw
3504                        .get("item_type")
3505                        .and_then(Value::as_str)
3506                        .map(str::to_string),
3507                    content_type: raw
3508                        .get("content_type")
3509                        .and_then(Value::as_str)
3510                        .map(str::to_string),
3511                    origin: raw
3512                        .get("origin")
3513                        .and_then(Value::as_str)
3514                        .map(str::to_string),
3515                    origin_reference: raw
3516                        .get("origin_reference")
3517                        .and_then(Value::as_str)
3518                        .map(str::to_string),
3519                    emitted_at: raw
3520                        .get("emitted_at")
3521                        .and_then(Value::as_str)
3522                        .map(str::to_string),
3523                    raw,
3524                })
3525            })
3526            .collect::<Result<Vec<_>>>()?;
3527        Ok(WorkflowStreamPage {
3528            stream: response.stream,
3529            items,
3530            next_offset: response.next_offset,
3531            terminal: response.terminal,
3532        })
3533    }
3534
3535    /// Append inline Avro envelopes or opaque external payload references.
3536    pub async fn append_workflow_stream(
3537        &self,
3538        workflow_id: &str,
3539        run_id: &str,
3540        stream_name: &str,
3541        items: &[WorkflowStreamAppendItem],
3542        max_pending_items: Option<u64>,
3543    ) -> Result<WorkflowStreamAppendResult> {
3544        if items.is_empty() {
3545            return Err(Error::Codec(
3546                "workflow_stream_items_empty: append requires at least one item".to_string(),
3547            ));
3548        }
3549        let mut body = json!({
3550            "items": items
3551                .iter()
3552                .map(|item| item.wire_value(None))
3553                .collect::<Vec<_>>(),
3554        });
3555        if let Some(max_pending_items) = max_pending_items {
3556            if max_pending_items == 0 {
3557                return Err(Error::Codec(
3558                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3559                        .to_string(),
3560                ));
3561            }
3562            body["max_pending_items"] = json!(max_pending_items);
3563        }
3564        let response: WorkflowStreamAppendResponse = self
3565            .request_json(
3566                reqwest::Method::POST,
3567                &format!(
3568                    "{}/items",
3569                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3570                ),
3571                RequestProtocol::ControlPlane,
3572                Some(&body),
3573            )
3574            .await?;
3575        Ok(WorkflowStreamAppendResult {
3576            stream: response.stream,
3577            accepted_offsets: response.accepted_offsets,
3578            accepted: response.accepted,
3579            deduped: response.deduped,
3580        })
3581    }
3582
3583    /// Close a stream, or mark it errored when `error_reason` is supplied.
3584    pub async fn close_workflow_stream(
3585        &self,
3586        workflow_id: &str,
3587        run_id: &str,
3588        stream_name: &str,
3589        error_reason: Option<&str>,
3590        retention_seconds: Option<u64>,
3591    ) -> Result<WorkflowStreamDescription> {
3592        let mut body = json!({});
3593        if let Some(error_reason) = error_reason {
3594            body["error_reason"] = json!(error_reason);
3595        }
3596        if let Some(retention_seconds) = retention_seconds {
3597            if retention_seconds == 0 {
3598                return Err(Error::Codec(
3599                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3600                        .to_string(),
3601                ));
3602            }
3603            body["retention_seconds"] = json!(retention_seconds);
3604        }
3605        let response: WorkflowStreamDescriptionResponse = self
3606            .request_json(
3607                reqwest::Method::POST,
3608                &format!(
3609                    "{}/close",
3610                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3611                ),
3612                RequestProtocol::ControlPlane,
3613                Some(&body),
3614            )
3615            .await?;
3616        Ok(response.stream)
3617    }
3618
3619    pub async fn register_worker(
3620        &self,
3621        worker_id: &str,
3622        task_queue: &str,
3623        supported_workflow_types: Vec<String>,
3624        supported_activity_types: Vec<String>,
3625        max_concurrent_workflow_tasks: usize,
3626        max_concurrent_activity_tasks: usize,
3627    ) -> Result<RegisterWorkerResponse> {
3628        self.register_worker_with_capabilities(
3629            worker_id,
3630            task_queue,
3631            supported_workflow_types,
3632            supported_activity_types,
3633            max_concurrent_workflow_tasks,
3634            max_concurrent_activity_tasks,
3635            Vec::new(),
3636        )
3637        .await
3638    }
3639
3640    /// Register a worker and explicitly advertise additive worker capabilities.
3641    pub async fn register_worker_with_capabilities(
3642        &self,
3643        worker_id: &str,
3644        task_queue: &str,
3645        supported_workflow_types: Vec<String>,
3646        supported_activity_types: Vec<String>,
3647        max_concurrent_workflow_tasks: usize,
3648        max_concurrent_activity_tasks: usize,
3649        capabilities: Vec<String>,
3650    ) -> Result<RegisterWorkerResponse> {
3651        self.register_worker_with_command_contracts(
3652            worker_id,
3653            task_queue,
3654            supported_workflow_types,
3655            supported_activity_types,
3656            max_concurrent_workflow_tasks,
3657            max_concurrent_activity_tasks,
3658            capabilities,
3659            Value::Object(serde_json::Map::new()),
3660        )
3661        .await
3662    }
3663
3664    /// Register a worker and advertise its named query and update handlers.
3665    ///
3666    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3667    /// so a workflow contract with a non-empty or malformed
3668    /// `update_validators` declaration returns
3669    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3670    #[allow(clippy::too_many_arguments)]
3671    pub async fn register_worker_with_command_contracts(
3672        &self,
3673        worker_id: &str,
3674        task_queue: &str,
3675        supported_workflow_types: Vec<String>,
3676        supported_activity_types: Vec<String>,
3677        max_concurrent_workflow_tasks: usize,
3678        max_concurrent_activity_tasks: usize,
3679        capabilities: Vec<String>,
3680        workflow_command_contracts: Value,
3681    ) -> Result<RegisterWorkerResponse> {
3682        self.register_worker_with_definition_fingerprints(
3683            worker_id,
3684            task_queue,
3685            supported_workflow_types,
3686            supported_activity_types,
3687            max_concurrent_workflow_tasks,
3688            max_concurrent_activity_tasks,
3689            capabilities,
3690            workflow_command_contracts,
3691            None,
3692        )
3693        .await
3694    }
3695
3696    #[allow(clippy::too_many_arguments)]
3697    async fn register_worker_with_definition_fingerprints(
3698        &self,
3699        worker_id: &str,
3700        task_queue: &str,
3701        supported_workflow_types: Vec<String>,
3702        supported_activity_types: Vec<String>,
3703        max_concurrent_workflow_tasks: usize,
3704        max_concurrent_activity_tasks: usize,
3705        capabilities: Vec<String>,
3706        workflow_command_contracts: Value,
3707        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3708    ) -> Result<RegisterWorkerResponse> {
3709        if let Some(contracts) = workflow_command_contracts.as_object() {
3710            for (workflow_type, contract) in contracts {
3711                let Some(update_validators) = contract.get("update_validators") else {
3712                    continue;
3713                };
3714                if !update_validators
3715                    .as_array()
3716                    .is_some_and(|validators| validators.is_empty())
3717                {
3718                    return Err(Error::UnsupportedUpdateValidators {
3719                        workflow_type: workflow_type.clone(),
3720                    });
3721                }
3722            }
3723        }
3724
3725        let mut body = json!({
3726            "worker_id": worker_id,
3727            "task_queue": task_queue,
3728            "runtime": "rust",
3729            "sdk_version": SDK_VERSION,
3730            "supported_workflow_types": supported_workflow_types,
3731            "supported_activity_types": supported_activity_types,
3732            "capabilities": capabilities,
3733            "capability_manifest": portable_worker_affinity_capability_manifest(),
3734            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3735            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3736        });
3737        if let Some(build_id) = &self.worker_build_id {
3738            if build_id.is_empty() || build_id.len() > 255 {
3739                return Err(Error::WorkerLoop(
3740                    "worker build ID must contain 1 to 255 bytes".into(),
3741                ));
3742            }
3743            body["build_id"] = json!(build_id);
3744        }
3745        if self.sticky_cache.is_some() {
3746            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
3747                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
3748                "implementation":"bounded_durable_history_cache"});
3749        }
3750        if self.local_activities_enabled {
3751            body["capability_manifest"]["local_activities"] = json!({"supported":true,
3752                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3753        }
3754        if self.worker_sessions_enabled {
3755            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
3756                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3757            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
3758        }
3759        if workflow_command_contracts
3760            .as_object()
3761            .is_some_and(|contracts| !contracts.is_empty())
3762        {
3763            body["workflow_command_contracts"] = workflow_command_contracts;
3764        }
3765        if let Some(fingerprints) = workflow_definition_fingerprints {
3766            body["workflow_definition_fingerprints"] = json!(fingerprints);
3767        }
3768
3769        let response: Value = self
3770            .request_json(
3771                reqwest::Method::POST,
3772                "/worker/register",
3773                RequestProtocol::DefaultWorker,
3774                Some(&body),
3775            )
3776            .await?;
3777        if self.sticky_cache.is_some() {
3778            self.confirm_sticky_registration(&response, worker_id, task_queue)
3779                .await?;
3780        }
3781        if self.local_activities_enabled || self.worker_sessions_enabled {
3782            let compatible = response["registered"].as_bool() == Some(true)
3783                && response["worker_id"].as_str() == Some(worker_id)
3784                && response["namespace"].as_str() == Some(self.namespace.as_str())
3785                && response["task_queue"].as_str() == Some(task_queue)
3786                && response["protocol_version"]
3787                    .as_str()
3788                    .and_then(|version| version.strip_prefix("1."))
3789                    .and_then(|minor| minor.parse::<u64>().ok())
3790                    .is_some_and(|minor| minor >= 18)
3791                && (!self.local_activities_enabled
3792                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
3793                        == Some(true))
3794                && (!self.worker_sessions_enabled
3795                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
3796                        == Some(true)
3797                        && response["capabilities"].as_array().is_some_and(|accepted| {
3798                            capabilities.iter().all(|capability| {
3799                                accepted
3800                                    .iter()
3801                                    .any(|value| value.as_str() == Some(capability.as_str()))
3802                            })
3803                        })));
3804            if !compatible {
3805                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
3806                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
3807                } else {
3808                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
3809                });
3810                if response["registered"] == true
3811                    && response["worker_id"].as_str() == Some(worker_id)
3812                {
3813                    if let Err(deregistration) =
3814                        self.deregister_worker_registration(worker_id).await
3815                    {
3816                        return Err(Error::WorkerShutdown {
3817                            primary: Box::new(error),
3818                            deregistration: Box::new(deregistration),
3819                        });
3820                    }
3821                }
3822                return Err(error);
3823            }
3824        }
3825        if self.cooperative_worker_protocol {
3826            let compatible = response["registered"].as_bool() == Some(true)
3827                && response["worker_id"].as_str() == Some(worker_id)
3828                && response["namespace"].as_str() == Some(self.namespace.as_str())
3829                && response["task_queue"].as_str() == Some(task_queue)
3830                && response["protocol_version"]
3831                    .as_str()
3832                    .is_some_and(cooperative_cancellation::supports_protocol)
3833                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
3834                    == Some(true)
3835                && response["capabilities"].as_array().is_some_and(|accepted| {
3836                    capabilities.iter().all(|capability| {
3837                        accepted
3838                            .iter()
3839                            .any(|value| value.as_str() == Some(capability.as_str()))
3840                    })
3841                });
3842            if !compatible {
3843                let error = Error::CooperativeCancellationUnavailable(
3844                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3845                );
3846                if response["registered"].as_bool() == Some(true)
3847                    && response["worker_id"].as_str() == Some(worker_id)
3848                {
3849                    if let Err(deregistration) =
3850                        self.deregister_worker_registration(worker_id).await
3851                    {
3852                        return Err(Error::WorkerShutdown {
3853                            primary: Box::new(error),
3854                            deregistration: Box::new(deregistration),
3855                        });
3856                    }
3857                }
3858                return Err(error);
3859            }
3860        }
3861        Ok(serde_json::from_value(response)?)
3862    }
3863
3864    /// Gracefully remove one worker's registration through the worker plane.
3865    ///
3866    /// This operation is separate from operator-facing worker management. It
3867    /// uses worker-protocol authentication and returns the server's lease
3868    /// recovery result.
3869    pub async fn deregister_worker_registration(
3870        &self,
3871        worker_id: &str,
3872    ) -> Result<WorkerDeregistrationEnvelope> {
3873        let path = format!(
3874            "/worker/registrations/{}",
3875            percent_encode_path_segment(worker_id)
3876        );
3877        self.request_json(
3878            reqwest::Method::DELETE,
3879            &path,
3880            RequestProtocol::DefaultWorker,
3881            Option::<&Value>::None,
3882        )
3883        .await
3884    }
3885
3886    /// Long-poll for an ephemeral, read-only workflow query task.
3887    pub async fn poll_query_task(
3888        &self,
3889        worker_id: &str,
3890        task_queue: &str,
3891        timeout: Duration,
3892    ) -> Result<Option<QueryTask>> {
3893        Ok(self
3894            .poll_query_task_response(worker_id, task_queue, timeout)
3895            .await?
3896            .task)
3897    }
3898
3899    /// Poll a query task while preserving server stop and drain metadata.
3900    pub async fn poll_query_task_response(
3901        &self,
3902        worker_id: &str,
3903        task_queue: &str,
3904        timeout: Duration,
3905    ) -> Result<PollQueryTaskResponse> {
3906        let poll_request_id = unique_request_id("rust-query-poll");
3907        self.poll_query_task_response_with_request_id(
3908            worker_id,
3909            task_queue,
3910            timeout,
3911            &poll_request_id,
3912            1,
3913        )
3914        .await
3915    }
3916
3917    async fn poll_query_task_response_with_request_id(
3918        &self,
3919        worker_id: &str,
3920        task_queue: &str,
3921        timeout: Duration,
3922        poll_request_id: &str,
3923        transport_retries: usize,
3924    ) -> Result<PollQueryTaskResponse> {
3925        let timeout_seconds = long_poll_timeout_seconds(timeout);
3926        let body = json!({
3927            "worker_id": worker_id,
3928            "task_queue": task_queue,
3929            "poll_request_id": poll_request_id,
3930            "timeout_seconds": timeout_seconds,
3931        });
3932        self.poll_request_json(
3933            "/worker/query-tasks/poll",
3934            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3935            &body,
3936            timeout + Duration::from_secs(5),
3937            transport_retries,
3938        )
3939        .await
3940    }
3941
3942    /// Complete a query task without appending workflow history.
3943    pub async fn complete_query_task<T: Serialize>(
3944        &self,
3945        query_task_id: &str,
3946        lease_owner: &str,
3947        query_task_attempt: u64,
3948        result: T,
3949        codec: &str,
3950    ) -> Result<Value> {
3951        let typed_result = AvroValue::from_serialize(&result)?;
3952        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3953        self.complete_query_task_with_envelope(
3954            query_task_id,
3955            lease_owner,
3956            query_task_attempt,
3957            typed_result.into_json()?,
3958            result_envelope,
3959        )
3960        .await
3961    }
3962
3963    async fn complete_query_task_with_envelope(
3964        &self,
3965        query_task_id: &str,
3966        lease_owner: &str,
3967        query_task_attempt: u64,
3968        result: Value,
3969        result_envelope: Value,
3970    ) -> Result<Value> {
3971        let body = json!({
3972            "lease_owner": lease_owner,
3973            "query_task_attempt": query_task_attempt,
3974            "result": result,
3975            "result_envelope": result_envelope,
3976        });
3977        let path = format!("/worker/query-tasks/{query_task_id}/complete");
3978        let response = self
3979            .request_json(
3980                reqwest::Method::POST,
3981                &path,
3982                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3983                Some(&body),
3984            )
3985            .await;
3986        query_task_response(response)
3987    }
3988
3989    /// Report a stable machine-readable query-task failure.
3990    pub async fn fail_query_task(
3991        &self,
3992        query_task_id: &str,
3993        lease_owner: &str,
3994        query_task_attempt: u64,
3995        message: impl Into<String>,
3996        reason: impl Into<String>,
3997        failure_type: impl Into<String>,
3998    ) -> Result<Value> {
3999        let body = json!({
4000            "lease_owner": lease_owner,
4001            "query_task_attempt": query_task_attempt,
4002            "failure": {
4003                "message": message.into(),
4004                "reason": reason.into(),
4005                "type": failure_type.into(),
4006            }
4007        });
4008        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4009        let response = self
4010            .request_json(
4011                reqwest::Method::POST,
4012                &path,
4013                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4014                Some(&body),
4015            )
4016            .await;
4017        query_task_response(response)
4018    }
4019
4020    pub async fn heartbeat_worker(
4021        &self,
4022        worker_id: &str,
4023        workflow_available: usize,
4024        activity_available: usize,
4025    ) -> Result<Value> {
4026        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4027            .await
4028    }
4029
4030    async fn heartbeat_worker_with_sessions(
4031        &self,
4032        worker_id: &str,
4033        workflow_available: usize,
4034        activity_available: usize,
4035        session_available: Option<usize>,
4036    ) -> Result<Value> {
4037        let mut body = json!({
4038            "worker_id": worker_id,
4039            "task_slots": {
4040                "workflow_available": workflow_available,
4041                "activity_available": activity_available
4042            },
4043            "process_metrics": {
4044                "process_id": std::process::id(),
4045                "process_uptime_seconds": 0
4046            }
4047        });
4048
4049        if let Some(available) = session_available {
4050            body["task_slots"]["session_available"] = json!(available);
4051        }
4052
4053        self.request_json(
4054            reqwest::Method::POST,
4055            "/worker/heartbeat",
4056            RequestProtocol::DefaultWorker,
4057            Some(&body),
4058        )
4059        .await
4060    }
4061
4062    pub async fn poll_workflow_task(
4063        &self,
4064        worker_id: &str,
4065        task_queue: &str,
4066        timeout: Duration,
4067    ) -> Result<Option<WorkflowTask>> {
4068        Ok(self
4069            .poll_workflow_task_response(worker_id, task_queue, timeout)
4070            .await?
4071            .task)
4072    }
4073
4074    pub async fn poll_workflow_task_response(
4075        &self,
4076        worker_id: &str,
4077        task_queue: &str,
4078        timeout: Duration,
4079    ) -> Result<PollWorkflowTaskResponse> {
4080        let poll_request_id = unique_request_id("rust-workflow-poll");
4081        self.poll_workflow_task_response_with_request_id(
4082            worker_id,
4083            task_queue,
4084            timeout,
4085            &poll_request_id,
4086            1,
4087        )
4088        .await
4089    }
4090
4091    async fn poll_workflow_task_response_with_request_id(
4092        &self,
4093        worker_id: &str,
4094        task_queue: &str,
4095        timeout: Duration,
4096        poll_request_id: &str,
4097        transport_retries: usize,
4098    ) -> Result<PollWorkflowTaskResponse> {
4099        let body = json!({
4100            "worker_id": worker_id,
4101            "task_queue": task_queue,
4102            "poll_request_id": poll_request_id,
4103            "timeout_seconds": long_poll_timeout_seconds(timeout),
4104            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4105        });
4106        let mut wire: Value = self
4107            .poll_request_json_unresolved(
4108                "/worker/workflow-tasks/poll",
4109                RequestProtocol::DefaultWorker,
4110                &body,
4111                timeout + Duration::from_secs(5),
4112                transport_retries,
4113            )
4114            .await?;
4115        let claim =
4116            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4117        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4118            self.resolve_runtime_payloads(
4119                &mut wire,
4120                "/worker/workflow-tasks/poll",
4121                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4122            )
4123            .await?;
4124            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4125            if let Some(task) = data.task.as_mut() {
4126                self.fetch_remaining_workflow_history(worker_id, task)
4127                    .await?;
4128            }
4129            Ok(data)
4130        })
4131        .await?;
4132        Ok(data)
4133    }
4134
4135    async fn fetch_remaining_workflow_history(
4136        &self,
4137        worker_id: &str,
4138        task: &mut WorkflowTask,
4139    ) -> Result<()> {
4140        let mut next_token = task.next_history_page_token.clone();
4141        let mut seen = BTreeSet::new();
4142
4143        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4144            if seen.len() >= 128 || !seen.insert(token.clone()) {
4145                return Err(Error::Codec(
4146                    "workflow history pagination exceeded its page bound or repeated a token"
4147                        .into(),
4148                ));
4149            }
4150            let lease_owner = task
4151                .lease_owner
4152                .clone()
4153                .unwrap_or_else(|| worker_id.to_string());
4154            let page = self
4155                .workflow_task_history_page(
4156                    &task.task_id,
4157                    &lease_owner,
4158                    task.workflow_task_attempt,
4159                    &token,
4160                )
4161                .await?;
4162
4163            task.append_history_page(page);
4164
4165            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4166                return Err(Error::Codec(
4167                    "workflow history pagination returned the same page token".to_string(),
4168                ));
4169            }
4170
4171            next_token = task.next_history_page_token.clone();
4172        }
4173
4174        Ok(())
4175    }
4176
4177    async fn workflow_task_history_page(
4178        &self,
4179        task_id: &str,
4180        lease_owner: &str,
4181        workflow_task_attempt: u64,
4182        next_history_page_token: &str,
4183    ) -> Result<WorkflowTaskHistoryPage> {
4184        let body = json!({
4185            "lease_owner": lease_owner,
4186            "workflow_task_attempt": workflow_task_attempt,
4187            "next_history_page_token": next_history_page_token
4188        });
4189        let path = format!("/worker/workflow-tasks/{task_id}/history");
4190
4191        self.request_json(
4192            reqwest::Method::POST,
4193            &path,
4194            RequestProtocol::DefaultWorker,
4195            Some(&body),
4196        )
4197        .await
4198    }
4199
4200    pub async fn complete_workflow_task(
4201        &self,
4202        task_id: &str,
4203        lease_owner: &str,
4204        workflow_task_attempt: u64,
4205        commands: Vec<Value>,
4206    ) -> Result<Value> {
4207        self.complete_workflow_task_with_message_streams(
4208            task_id,
4209            lease_owner,
4210            workflow_task_attempt,
4211            commands,
4212            Vec::new(),
4213            Vec::new(),
4214            None,
4215        )
4216        .await
4217    }
4218
4219    #[allow(clippy::too_many_arguments)]
4220    async fn complete_workflow_task_with_message_streams(
4221        &self,
4222        task_id: &str,
4223        lease_owner: &str,
4224        workflow_task_attempt: u64,
4225        commands: Vec<Value>,
4226        message_stream_cursors: Vec<Value>,
4227        message_stream_waits: Vec<Value>,
4228        sticky_cache: Option<Value>,
4229    ) -> Result<Value> {
4230        validate_workflow_task_commands(&commands)?;
4231        let has_message_stream_metadata =
4232            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4233        if has_message_stream_metadata
4234            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4235        {
4236            return Err(Error::Codec(
4237                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4238                    .to_string(),
4239            ));
4240        }
4241        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4242            &commands,
4243            has_message_stream_metadata,
4244        );
4245        let protocol_version = if sticky_cache.is_some()
4246            && protocol_version
4247                .strip_prefix("1.")
4248                .and_then(|minor| minor.parse::<u64>().ok())
4249                .is_some_and(|minor| minor < 18)
4250        {
4251            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4252        } else {
4253            protocol_version
4254        };
4255        let mut body = json!({
4256            "lease_owner": lease_owner,
4257            "workflow_task_attempt": workflow_task_attempt,
4258            "commands": commands
4259        });
4260        if !message_stream_cursors.is_empty() {
4261            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4262        }
4263        if !message_stream_waits.is_empty() {
4264            body["message_stream_waits"] = Value::Array(message_stream_waits);
4265        }
4266        if let Some(claim) = sticky_cache {
4267            body["sticky_cache"] = claim;
4268        }
4269        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4270        self.request_json(
4271            reqwest::Method::POST,
4272            &path,
4273            RequestProtocol::Worker(protocol_version),
4274            Some(&body),
4275        )
4276        .await
4277    }
4278
4279    pub async fn fail_workflow_task(
4280        &self,
4281        task_id: &str,
4282        lease_owner: &str,
4283        workflow_task_attempt: u64,
4284        message: impl Into<String>,
4285    ) -> Result<Value> {
4286        self.fail_workflow_task_with_type(
4287            task_id,
4288            lease_owner,
4289            workflow_task_attempt,
4290            message,
4291            "RustWorkflowTaskFailure",
4292        )
4293        .await
4294    }
4295
4296    async fn fail_workflow_task_with_type(
4297        &self,
4298        task_id: &str,
4299        lease_owner: &str,
4300        workflow_task_attempt: u64,
4301        message: impl Into<String>,
4302        failure_type: &str,
4303    ) -> Result<Value> {
4304        let body = json!({
4305            "lease_owner": lease_owner,
4306            "workflow_task_attempt": workflow_task_attempt,
4307            "failure": {
4308                "message": message.into(),
4309                "type": failure_type
4310            }
4311        });
4312        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4313        self.request_json(
4314            reqwest::Method::POST,
4315            &path,
4316            RequestProtocol::DefaultWorker,
4317            Some(&body),
4318        )
4319        .await
4320    }
4321
4322    pub async fn poll_activity_task(
4323        &self,
4324        worker_id: &str,
4325        task_queue: &str,
4326        timeout: Duration,
4327    ) -> Result<Option<ActivityTask>> {
4328        Ok(self
4329            .poll_activity_task_response(worker_id, task_queue, timeout)
4330            .await?
4331            .task)
4332    }
4333
4334    /// Poll an activity task while preserving server stop and drain metadata.
4335    pub async fn poll_activity_task_response(
4336        &self,
4337        worker_id: &str,
4338        task_queue: &str,
4339        timeout: Duration,
4340    ) -> Result<PollActivityTaskResponse> {
4341        let poll_request_id = unique_request_id("rust-activity-poll");
4342        self.poll_activity_task_response_with_request_id(
4343            worker_id,
4344            task_queue,
4345            timeout,
4346            &poll_request_id,
4347            1,
4348        )
4349        .await
4350        .map(worker_session::SessionPollResponse::ordinary)
4351    }
4352
4353    async fn poll_activity_task_response_with_request_id(
4354        &self,
4355        worker_id: &str,
4356        task_queue: &str,
4357        timeout: Duration,
4358        poll_request_id: &str,
4359        transport_retries: usize,
4360    ) -> Result<worker_session::SessionPollResponse> {
4361        let body = json!({
4362            "worker_id": worker_id,
4363            "task_queue": task_queue,
4364            "poll_request_id": poll_request_id,
4365            "timeout_seconds": long_poll_timeout_seconds(timeout),
4366        });
4367        let data: worker_session::SessionPollResponse = self
4368            .poll_request_json(
4369                "/worker/activity-tasks/poll",
4370                RequestProtocol::DefaultWorker,
4371                &body,
4372                timeout + Duration::from_secs(5),
4373                transport_retries,
4374            )
4375            .await?;
4376        Ok(data)
4377    }
4378
4379    pub async fn complete_activity_task<T: Serialize>(
4380        &self,
4381        task_id: &str,
4382        activity_attempt_id: &str,
4383        lease_owner: &str,
4384        result: T,
4385        codec: &str,
4386    ) -> Result<Value> {
4387        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4388        let body = json!({
4389            "activity_attempt_id": activity_attempt_id,
4390            "lease_owner": lease_owner,
4391            "result": result
4392        });
4393        let path = format!("/worker/activity-tasks/{task_id}/complete");
4394        activity_task_response(
4395            self.request_json(
4396                reqwest::Method::POST,
4397                &path,
4398                RequestProtocol::DefaultWorker,
4399                Some(&body),
4400            )
4401            .await,
4402            "complete",
4403            task_id,
4404            activity_attempt_id,
4405        )
4406    }
4407
4408    pub async fn fail_activity_task(
4409        &self,
4410        task_id: &str,
4411        activity_attempt_id: &str,
4412        lease_owner: &str,
4413        message: impl Into<String>,
4414        non_retryable: bool,
4415    ) -> Result<Value> {
4416        let body = json!({
4417            "activity_attempt_id": activity_attempt_id,
4418            "lease_owner": lease_owner,
4419            "failure": {
4420                "message": message.into(),
4421                "type": "RustActivityFailure",
4422                "non_retryable": non_retryable
4423            }
4424        });
4425        let path = format!("/worker/activity-tasks/{task_id}/fail");
4426        activity_task_response(
4427            self.request_json(
4428                reqwest::Method::POST,
4429                &path,
4430                RequestProtocol::DefaultWorker,
4431                Some(&body),
4432            )
4433            .await,
4434            "fail",
4435            task_id,
4436            activity_attempt_id,
4437        )
4438    }
4439
4440    /// Record a flat map of scalar/null activity progress metadata.
4441    ///
4442    /// Heartbeat details use the Server's bounded JSON progress contract.
4443    /// They are not workflow payload envelopes.
4444    pub async fn heartbeat_activity_task<T: Serialize>(
4445        &self,
4446        task_id: &str,
4447        activity_attempt_id: &str,
4448        lease_owner: &str,
4449        details: T,
4450    ) -> Result<ActivityHeartbeatResponse> {
4451        serde_json::from_value(
4452            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4453                .await?,
4454        )
4455        .map_err(Error::from)
4456    }
4457
4458    async fn heartbeat_activity_task_value<T: Serialize>(
4459        &self,
4460        task_id: &str,
4461        activity_attempt_id: &str,
4462        lease_owner: &str,
4463        details: T,
4464    ) -> Result<Value> {
4465        let details = AvroValue::from_serialize(&details)?.into_json()?;
4466        let body = json!({
4467            "activity_attempt_id": activity_attempt_id,
4468            "lease_owner": lease_owner,
4469            "details": details
4470        });
4471        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4472        activity_task_response(
4473            self.request_json(
4474                reqwest::Method::POST,
4475                &path,
4476                RequestProtocol::DefaultWorker,
4477                Some(&body),
4478            )
4479            .await,
4480            "heartbeat",
4481            task_id,
4482            activity_attempt_id,
4483        )
4484    }
4485
4486    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4487        &self,
4488        method: reqwest::Method,
4489        path: &str,
4490        protocol: RequestProtocol,
4491        body: Option<&B>,
4492    ) -> Result<T> {
4493        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4494            .await
4495    }
4496
4497    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4498        &self,
4499        method: reqwest::Method,
4500        path: &str,
4501        protocol: RequestProtocol,
4502        body: Option<&B>,
4503        timeout: Duration,
4504    ) -> Result<T> {
4505        let mut value: Value = self
4506            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4507            .await?;
4508        let protocol = match protocol {
4509            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4510                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4511            }
4512            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4513        };
4514        self.resolve_runtime_payloads(&mut value, path, protocol)
4515            .await?;
4516        Ok(serde_json::from_value(value)?)
4517    }
4518
4519    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4520        &self,
4521        method: reqwest::Method,
4522        path: &str,
4523        protocol: RequestProtocol,
4524        body: Option<&B>,
4525        timeout: Duration,
4526    ) -> Result<T> {
4527        let protocol = match protocol {
4528            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4529                let selected = self.worker_protocol_version.as_str();
4530                if self.cooperative_worker_protocol
4531                    && !cooperative_cancellation::supports_protocol(selected)
4532                {
4533                    return Err(Error::CooperativeCancellationUnavailable(
4534                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4535                    ));
4536                }
4537                if let RequestProtocol::Worker(minimum) = protocol {
4538                    let supported = minimum
4539                        .strip_prefix("1.")
4540                        .and_then(|minor| minor.parse::<u64>().ok())
4541                        .zip(
4542                            selected
4543                                .strip_prefix("1.")
4544                                .and_then(|minor| minor.parse::<u64>().ok()),
4545                        )
4546                        .is_some_and(|(minimum, selected)| selected >= minimum);
4547                    if !supported {
4548                        return Err(Error::WorkerLoop(format!(
4549                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4550                        )));
4551                    }
4552                }
4553                RequestProtocol::Worker(selected)
4554            }
4555            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4556        };
4557        let auth_token = self.auth_token(protocol)?;
4558        let mut request = self
4559            .http
4560            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4561            .timeout(timeout)
4562            .header(reqwest::header::ACCEPT, "application/json")
4563            .header(reqwest::header::CONTENT_TYPE, "application/json")
4564            .header("X-Namespace", &self.namespace);
4565
4566        match protocol {
4567            RequestProtocol::DefaultWorker => {
4568                request = request.header(
4569                    "X-Durable-Workflow-Protocol-Version",
4570                    self.worker_protocol_version.as_str(),
4571                );
4572            }
4573            RequestProtocol::Worker(version) => {
4574                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4575            }
4576            RequestProtocol::ControlPlane => {
4577                request = request.header(
4578                    "X-Durable-Workflow-Control-Plane-Version",
4579                    CONTROL_PLANE_VERSION,
4580                );
4581            }
4582        }
4583
4584        if let Some(token) = auth_token {
4585            request = request.bearer_auth(token);
4586        }
4587
4588        if let Some(body) = body {
4589            let mut body = serde_json::to_value(body)?;
4590            if matches!(
4591                method,
4592                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4593            ) {
4594                self.externalize_runtime_payloads(&mut body, path, protocol)
4595                    .await?;
4596            }
4597            request = request.json(&body);
4598        }
4599
4600        let request = request.build()?;
4601        let request_body = request
4602            .body()
4603            .and_then(reqwest::Body::as_bytes)
4604            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4605        let poll_request_id = path.ends_with("/poll").then(|| {
4606            request_body
4607                .as_ref()
4608                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4609                .unwrap_or_default()
4610        });
4611        let mut storage_retries = 0_usize;
4612
4613        loop {
4614            // Keep the serialized body and lease/poll identity across admission pauses.
4615            let response = self
4616                .http
4617                .execute(request.try_clone().ok_or_else(|| {
4618                    Error::WorkerLoop("worker request body cannot be retried".to_string())
4619                })?)
4620                .await?;
4621            let status = response.status();
4622            let bytes = response.bytes().await?;
4623
4624            if !status.is_success() {
4625                let body = String::from_utf8_lossy(&bytes).to_string();
4626                if let Some(protocol) = protocol_failure(status, &body) {
4627                    return Err(Error::Protocol(protocol));
4628                }
4629                let error = Error::Http { status, body };
4630                if self
4631                    .wait_for_storage_admission(
4632                        &error,
4633                        protocol,
4634                        Some(path),
4635                        poll_request_id.as_deref(),
4636                        request_body.as_ref(),
4637                        &mut storage_retries,
4638                    )
4639                    .await
4640                {
4641                    continue;
4642                }
4643                return Err(error);
4644            }
4645
4646            if bytes.is_empty() {
4647                return Ok(serde_json::from_value(Value::Null)?);
4648            }
4649
4650            return Ok(serde_json::from_slice(&bytes)?);
4651        }
4652    }
4653
4654    async fn wait_for_storage_admission(
4655        &self,
4656        error: &Error,
4657        protocol: RequestProtocol,
4658        path: Option<&str>,
4659        poll_request_id: Option<&str>,
4660        request_body: Option<&Value>,
4661        retries: &mut usize,
4662    ) -> bool {
4663        let Some(admission) = self
4664            .worker_storage_admission
4665            .as_ref()
4666            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4667        else {
4668            return false;
4669        };
4670        let Some(advertised_delay) = worker_storage_admission_retry_after(error, poll_request_id)
4671            .or_else(|| {
4672                path.and_then(|path| {
4673                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4674                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4675                })
4676            })
4677        else {
4678            return false;
4679        };
4680        *retries = retries.saturating_add(1);
4681        let delay = worker_retry_delay(admission.policy, *retries)
4682            .max(advertised_delay)
4683            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4684        let deadline = tokio::time::Instant::now() + delay;
4685        loop {
4686            if admission.stop.load(Ordering::SeqCst) {
4687                return false;
4688            }
4689            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
4690            if remaining.is_zero() {
4691                return true;
4692            }
4693            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4694        }
4695    }
4696
4697    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4698        &self,
4699        path: &str,
4700        protocol: RequestProtocol,
4701        body: &B,
4702        timeout: Duration,
4703        max_retries: usize,
4704    ) -> Result<T> {
4705        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
4706            .await
4707    }
4708
4709    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
4710        &self,
4711        path: &str,
4712        protocol: RequestProtocol,
4713        body: &B,
4714        timeout: Duration,
4715        max_retries: usize,
4716    ) -> Result<T> {
4717        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
4718            .await
4719    }
4720
4721    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
4722        &self,
4723        path: &str,
4724        protocol: RequestProtocol,
4725        body: &B,
4726        timeout: Duration,
4727        max_retries: usize,
4728        resolve: bool,
4729    ) -> Result<T> {
4730        let mut retries = 0;
4731
4732        loop {
4733            let response = if resolve {
4734                self.request_json_with_timeout(
4735                    reqwest::Method::POST,
4736                    path,
4737                    protocol,
4738                    Some(body),
4739                    timeout,
4740                )
4741                .await
4742            } else {
4743                self.request_json_unresolved_with_timeout(
4744                    reqwest::Method::POST,
4745                    path,
4746                    protocol,
4747                    Some(body),
4748                    timeout,
4749                )
4750                .await
4751            };
4752
4753            match response {
4754                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4755                response => return worker_poll_response(response),
4756            }
4757        }
4758    }
4759
4760    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4761        match protocol {
4762            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4763                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4764                    return Ok(Some(token));
4765                }
4766                if self.control_token.is_some() {
4767                    return Err(Error::MissingRoleCredentials {
4768                        role: "worker",
4769                        opposite_role: "control",
4770                    });
4771                }
4772                Ok(None)
4773            }
4774            RequestProtocol::ControlPlane => {
4775                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4776                    return Ok(Some(token));
4777                }
4778                if self.worker_token.is_some() {
4779                    return Err(Error::MissingRoleCredentials {
4780                        role: "control",
4781                        opposite_role: "worker",
4782                    });
4783                }
4784                Ok(None)
4785            }
4786        }
4787    }
4788}
4789
4790fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4791    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4792    let reason = body
4793        .get("reason")
4794        .and_then(Value::as_str)
4795        .unwrap_or("query_rejected")
4796        .to_string();
4797    let message = body
4798        .get("message")
4799        .or_else(|| body.get("error"))
4800        .and_then(Value::as_str)
4801        .unwrap_or("workflow query was rejected")
4802        .to_string();
4803
4804    QueryFailure {
4805        status: status.as_u16(),
4806        reason,
4807        message,
4808        body,
4809    }
4810}
4811
4812fn workflow_command_result(
4813    command: WorkflowCommandKind,
4814    data: Value,
4815    workflow_id: &str,
4816    run_id: Option<&str>,
4817) -> WorkflowCommandResult {
4818    WorkflowCommandResult {
4819        command,
4820        workflow_id: data
4821            .get("workflow_id")
4822            .and_then(Value::as_str)
4823            .unwrap_or(workflow_id)
4824            .to_string(),
4825        run_id: data
4826            .get("run_id")
4827            .and_then(Value::as_str)
4828            .or(run_id)
4829            .map(str::to_string),
4830        outcome: data
4831            .get("outcome")
4832            .and_then(Value::as_str)
4833            .map(str::to_string),
4834        reason: data
4835            .get("reason")
4836            .and_then(Value::as_str)
4837            .map(str::to_string),
4838        command_status: data
4839            .get("command_status")
4840            .and_then(Value::as_str)
4841            .map(str::to_string),
4842        raw: data,
4843    }
4844}
4845
4846fn workflow_command_rejection(
4847    command: WorkflowCommandKind,
4848    status: reqwest::StatusCode,
4849    raw_body: String,
4850    workflow_id: &str,
4851    run_id: Option<&str>,
4852) -> WorkflowCommandRejection {
4853    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4854    WorkflowCommandRejection {
4855        command,
4856        status: status.as_u16(),
4857        reason: body
4858            .get("reason")
4859            .and_then(Value::as_str)
4860            .unwrap_or("workflow_command_rejected")
4861            .to_string(),
4862        message: body
4863            .get("message")
4864            .or_else(|| body.get("error"))
4865            .and_then(Value::as_str)
4866            .unwrap_or("workflow lifecycle command was rejected")
4867            .to_string(),
4868        workflow_id: body
4869            .get("workflow_id")
4870            .and_then(Value::as_str)
4871            .unwrap_or(workflow_id)
4872            .to_string(),
4873        run_id: body
4874            .get("run_id")
4875            .and_then(Value::as_str)
4876            .or(run_id)
4877            .map(str::to_string),
4878        target_scope: body
4879            .get("target_scope")
4880            .and_then(Value::as_str)
4881            .map(str::to_string),
4882        body,
4883    }
4884}
4885
4886fn query_task_response(response: Result<Value>) -> Result<Value> {
4887    match response {
4888        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4889        response => response,
4890    }
4891}
4892
4893fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4894    match response {
4895        Err(Error::Http { status, body })
4896            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
4897        {
4898            Ok(serde_json::from_str(&body)?)
4899        }
4900        response => response,
4901    }
4902}
4903
4904fn worker_poll_body_is_stop(body: &str) -> bool {
4905    serde_json::from_str::<Value>(body)
4906        .ok()
4907        .is_some_and(|body| {
4908            worker_poll_is_stop(
4909                body.get("poll_status").and_then(Value::as_str),
4910                body.get("reason").and_then(Value::as_str),
4911            )
4912        })
4913}
4914
4915fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
4916    matches!(poll_status, Some("draining" | "stopped"))
4917        || matches!(reason, Some("worker_draining" | "worker_stopped"))
4918}
4919
4920fn query_task_rejection_is_final(error: &Error) -> bool {
4921    matches!(
4922        error,
4923        Error::QueryFailed(failure)
4924            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
4925    )
4926}
4927
4928fn activity_task_response<T>(
4929    response: Result<T>,
4930    operation: &str,
4931    task_id: &str,
4932    activity_attempt_id: &str,
4933) -> Result<T> {
4934    match response {
4935        Err(Error::Http { status, body }) => {
4936            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
4937            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
4938                operation: operation.to_string(),
4939                status: status.as_u16(),
4940                reason: body
4941                    .get("reason")
4942                    .and_then(Value::as_str)
4943                    .unwrap_or("activity_task_rejected")
4944                    .to_string(),
4945                task_id: body
4946                    .get("task_id")
4947                    .and_then(Value::as_str)
4948                    .unwrap_or(task_id)
4949                    .to_string(),
4950                activity_attempt_id: body
4951                    .get("activity_attempt_id")
4952                    .and_then(Value::as_str)
4953                    .unwrap_or(activity_attempt_id)
4954                    .to_string(),
4955                cancel_requested: body
4956                    .get("cancel_requested")
4957                    .and_then(Value::as_bool)
4958                    .unwrap_or(false),
4959                can_continue: body.get("can_continue").and_then(Value::as_bool),
4960                run_closed_reason: body
4961                    .get("run_closed_reason")
4962                    .and_then(Value::as_str)
4963                    .map(str::to_string),
4964                body,
4965            }))
4966        }
4967        response => response,
4968    }
4969}
4970
4971fn activity_task_rejection_is_final(error: &Error) -> bool {
4972    matches!(
4973        error,
4974        Error::ActivityTaskRejected(rejection)
4975            if matches!(
4976                rejection.reason.as_str(),
4977                "run_cancelled"
4978                    | "run_terminated"
4979                    | "attempt_closed"
4980                    | "stale_attempt"
4981                    | "activity_cancelled"
4982                    | "task_cancelled"
4983                    | "run_closed"
4984                    | "activity_not_running"
4985                    | "attempt_not_found"
4986            )
4987    )
4988}
4989
4990fn workflow_task_completion_is_terminal_timeout(
4991    error: &Error,
4992    task_id: &str,
4993    workflow_task_attempt: u64,
4994    run_id: Option<&str>,
4995) -> bool {
4996    let Error::Http { status, body } = error else {
4997        return false;
4998    };
4999    if *status != reqwest::StatusCode::CONFLICT {
5000        return false;
5001    }
5002
5003    let Some(run_id) = run_id else {
5004        return false;
5005    };
5006    let Ok(body) = serde_json::from_str::<Value>(body) else {
5007        return false;
5008    };
5009
5010    body.get("recorded").and_then(Value::as_bool) == Some(false)
5011        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5012        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5013        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5014        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5015        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5016}
5017
5018fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5019    let body: Value = serde_json::from_str(raw_body).ok()?;
5020    let reason = body.get("reason")?.as_str()?;
5021    if !matches!(
5022        reason,
5023        "missing_protocol_version"
5024            | "unsupported_protocol_version"
5025            | "missing_control_plane_version"
5026            | "unsupported_control_plane_version"
5027    ) {
5028        return None;
5029    }
5030
5031    Some(ProtocolFailure {
5032        status: status.as_u16(),
5033        reason: reason.to_string(),
5034        message: body
5035            .get("message")
5036            .or_else(|| body.get("error"))
5037            .and_then(Value::as_str)
5038            .unwrap_or("protocol version rejected")
5039            .to_string(),
5040        supported_version: body
5041            .get("supported_version")
5042            .and_then(Value::as_str)
5043            .map(str::to_string),
5044        requested_version: body
5045            .get("requested_version")
5046            .and_then(Value::as_str)
5047            .map(str::to_string),
5048        body,
5049    })
5050}
5051
5052fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5053    timeout
5054        .as_secs()
5055        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5056        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5057}
5058
5059fn worker_operation_is_retryable(error: &Error) -> bool {
5060    if worker_poll_capacity_retry_after(error).is_some()
5061        || worker_storage_admission_body(error).is_some()
5062        || worker_backend_unavailable_body(error).is_some()
5063        || worker_operation_is_explicitly_non_retryable(error)
5064    {
5065        return false;
5066    }
5067
5068    match error {
5069        Error::Transport(error) => {
5070            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5071        }
5072        Error::Http { status, .. } => {
5073            matches!(
5074                *status,
5075                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5076            ) || status.is_server_error()
5077        }
5078        _ => false,
5079    }
5080}
5081
5082fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5083    let body: Value = match error {
5084        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5085        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5086        _ => return None,
5087    };
5088    matches!(
5089        body.get("reason").and_then(Value::as_str),
5090        Some("storage_pressure" | "storage_admission_unavailable")
5091    )
5092    .then_some(body)
5093}
5094
5095fn worker_storage_admission_retry_after(
5096    error: &Error,
5097    poll_request_id: Option<&str>,
5098) -> Option<Duration> {
5099    let Error::Http { status, .. } = error else {
5100        return None;
5101    };
5102    let body = worker_storage_admission_body(error)?;
5103    let delay = body.get("retry_after_seconds")?.as_u64()?;
5104    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5105        || delay == 0
5106        || body.get("retryable") != Some(&Value::Bool(true))
5107        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5108        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5109        || body
5110            .get("request_admitted")
5111            .is_some_and(|admitted| admitted != &Value::Bool(false))
5112    {
5113        return None;
5114    }
5115    match poll_request_id {
5116        Some(id) => {
5117            if id.is_empty()
5118                || body.get("task") != Some(&Value::Null)
5119                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5120                || body.get("poll_status") != body.get("reason")
5121                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5122                || body.get("claim_admitted") != Some(&Value::Bool(false))
5123            {
5124                return None;
5125            }
5126        }
5127        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5128        None => {}
5129    }
5130    Some(Duration::from_secs(delay))
5131}
5132
5133fn worker_backend_unavailable_retry_after(
5134    error: &Error,
5135    path: &str,
5136    poll_request_id: Option<&str>,
5137) -> Option<Duration> {
5138    let operation = match path {
5139        "/worker/register" => "register_worker",
5140        "/worker/heartbeat" => "heartbeat_worker",
5141        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5142        "/worker/activity-tasks/poll" => "poll_activity_task",
5143        "/worker/query-tasks/poll" => "poll_query_task",
5144        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5145        _ => return None,
5146    };
5147    let body = worker_backend_unavailable_body(error)?;
5148    let delay = body.get("retry_after_seconds")?.as_u64()?;
5149    if delay == 0
5150        || body.get("operation")?.as_str()? != operation
5151        || body.get("outcome")?.as_str()? != "unknown"
5152        || body.get("retryable") != Some(&Value::Bool(true))
5153        || body.get("worker_id")?.as_str()?.is_empty()
5154    {
5155        return None;
5156    }
5157    if let Some(id) = poll_request_id {
5158        if id.is_empty()
5159            || body.get("task") != Some(&Value::Null)
5160            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5161            || body.get("poll_request_id")?.as_str()? != id
5162            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5163        {
5164            return None;
5165        }
5166    } else if path.ends_with("/poll") {
5167        return None;
5168    }
5169    Some(Duration::from_secs(delay))
5170}
5171
5172fn worker_fenced_completion_retry_after(
5173    error: &Error,
5174    path: &str,
5175    request_body: Option<&Value>,
5176) -> Option<Duration> {
5177    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5178        .strip_prefix("/worker/workflow-tasks/")
5179        .and_then(|tail| tail.strip_suffix("/complete"))
5180    {
5181        ("complete_workflow_task", task_id, "workflow_task_attempt")
5182    } else if let Some(task_id) = path
5183        .strip_prefix("/worker/activity-tasks/")
5184        .and_then(|tail| tail.strip_suffix("/complete"))
5185    {
5186        ("complete_activity_task", task_id, "activity_attempt_id")
5187    } else {
5188        return None;
5189    };
5190    if task_id.is_empty() || task_id.contains('/') {
5191        return None;
5192    }
5193
5194    let request = request_body?.as_object()?;
5195    let lease_owner = request.get("lease_owner")?.as_str()?;
5196    if lease_owner.is_empty() {
5197        return None;
5198    }
5199    let attempt = request.get(attempt_field)?;
5200    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5201        || (attempt_field == "activity_attempt_id"
5202            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5203    {
5204        return None;
5205    }
5206
5207    let body = worker_backend_unavailable_body(error)?;
5208    let delay = body.get("retry_after_seconds")?.as_u64()?;
5209    if delay == 0
5210        || body.get("operation")?.as_str()? != operation
5211        || body.get("outcome")?.as_str()? != "unknown"
5212        || body.get("retryable") != Some(&Value::Bool(true))
5213        || body.get("worker_id")?.as_str()? != lease_owner
5214        || body.get("task_queue") != Some(&Value::Null)
5215        || body.get("task_id")?.as_str()? != task_id
5216        || body.get("lease_owner")?.as_str()? != lease_owner
5217        || body.get(attempt_field) != Some(attempt)
5218    {
5219        return None;
5220    }
5221
5222    Some(Duration::from_secs(delay))
5223}
5224
5225fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5226    let Error::Http { status, body } = error else {
5227        return None;
5228    };
5229    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5230        return None;
5231    }
5232    let body: Value = serde_json::from_str(body).ok()?;
5233    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5234}
5235
5236fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5237    let Error::Http { body, .. } = error else {
5238        return false;
5239    };
5240
5241    serde_json::from_str::<Value>(body)
5242        .ok()
5243        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5244        == Some(false)
5245}
5246
5247fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5248    let Error::Http { status, body } = error else {
5249        return None;
5250    };
5251    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5252        return None;
5253    }
5254
5255    let body = serde_json::from_str::<Value>(body).ok()?;
5256    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5257        == Some("long_poll_capacity_exhausted")
5258        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5259    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5260        return None;
5261    }
5262
5263    Some(Duration::from_secs(
5264        body.get("retry_after_seconds")
5265            .and_then(Value::as_u64)
5266            .unwrap_or_default(),
5267    ))
5268}
5269
5270fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5271    let exponent = retry.saturating_sub(1).min(31) as u32;
5272    policy
5273        .initial_backoff
5274        .saturating_mul(1_u32 << exponent)
5275        .min(policy.max_backoff)
5276}
5277
5278#[derive(Debug)]
5279pub struct ClientBuilder {
5280    base_url: String,
5281    token: Option<String>,
5282    control_token: Option<String>,
5283    worker_token: Option<String>,
5284    namespace: String,
5285    timeout: Duration,
5286    max_external_payload_bytes: usize,
5287    worker_protocol_version: WorkerProtocolVersion,
5288}
5289
5290impl ClientBuilder {
5291    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5292    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5293        self.worker_protocol_version = version;
5294        self
5295    }
5296
5297    pub fn token(mut self, token: Option<String>) -> Self {
5298        self.token = token;
5299        self
5300    }
5301
5302    pub fn control_token(mut self, token: Option<String>) -> Self {
5303        self.control_token = token;
5304        self
5305    }
5306
5307    pub fn worker_token(mut self, token: Option<String>) -> Self {
5308        self.worker_token = token;
5309        self
5310    }
5311
5312    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5313        self.namespace = namespace.into();
5314        self
5315    }
5316
5317    pub fn timeout(mut self, timeout: Duration) -> Self {
5318        self.timeout = timeout;
5319        self
5320    }
5321
5322    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5323    /// References are fetched only from this client's authenticated runtime.
5324    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5325        self.max_external_payload_bytes = bytes;
5326        self
5327    }
5328
5329    pub fn build(self) -> Result<Client> {
5330        let base_url = self.base_url.trim_end_matches('/').to_string();
5331        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5332            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5333            .unwrap_or_else(|_| base_url.ends_with("/api"));
5334
5335        if has_sdk_api_suffix {
5336            return Err(Error::InvalidBaseUrl);
5337        }
5338
5339        Ok(Client {
5340            http: reqwest::Client::builder()
5341                .timeout(self.timeout)
5342                .redirect(reqwest::redirect::Policy::none())
5343                .build()?,
5344            hydration_timeout: self.timeout,
5345            base_url,
5346            token: self.token,
5347            control_token: self.control_token,
5348            worker_token: self.worker_token,
5349            namespace: self.namespace,
5350            max_external_payload_bytes: self.max_external_payload_bytes,
5351            worker_storage_admission: None,
5352            cooperative_worker_protocol: false,
5353            worker_protocol_version: self.worker_protocol_version,
5354            local_activities_enabled: false,
5355            worker_sessions_enabled: false,
5356            max_concurrent_worker_sessions: 10,
5357            worker_build_id: None,
5358            sticky_cache: None,
5359            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5360        })
5361    }
5362}
5363
5364#[derive(Clone, Debug)]
5365pub struct WorkflowHandle {
5366    client: Client,
5367    pub workflow_id: String,
5368    pub run_id: Option<String>,
5369    pub workflow_type: String,
5370}
5371
5372impl WorkflowHandle {
5373    /// Describe whichever run is current for this stable workflow instance.
5374    pub async fn describe(&self) -> Result<WorkflowDescription> {
5375        self.client.describe_workflow(&self.workflow_id).await
5376    }
5377
5378    /// Describe the run identity originally selected by this handle.
5379    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5380        let run_id = self.run_id.as_deref().ok_or_else(|| {
5381            Error::Codec("run_id is required for selected-run description".to_string())
5382        })?;
5383        self.client
5384            .describe_workflow_run(&self.workflow_id, run_id)
5385            .await
5386    }
5387
5388    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5389        self.client
5390            .signal_workflow(&self.workflow_id, signal_name, input)
5391            .await
5392    }
5393
5394    pub async fn append_message<T: Serialize>(
5395        &self,
5396        stream_name: &str,
5397        message_id: &str,
5398        input: T,
5399    ) -> Result<Value> {
5400        self.client
5401            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5402            .await
5403    }
5404
5405    /// Signal only if this handle's selected run is still current.
5406    pub async fn signal_selected_run<T: Serialize>(
5407        &self,
5408        signal_name: &str,
5409        input: T,
5410    ) -> Result<Value> {
5411        let run_id = self.run_id.as_deref().ok_or_else(|| {
5412            Error::Codec("run_id is required for selected-run signaling".to_string())
5413        })?;
5414        self.client
5415            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5416            .await
5417    }
5418
5419    /// Close whichever run is current as cancelled, without workflow cleanup.
5420    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5421        self.client
5422            .cancel_workflow(&self.workflow_id, options)
5423            .await
5424    }
5425
5426    /// Request cancellation only if this handle's selected run is still current.
5427    pub async fn cancel_selected_run(
5428        &self,
5429        options: WorkflowCommandOptions,
5430    ) -> Result<WorkflowCommandResult> {
5431        let run_id = self.run_id.as_deref().ok_or_else(|| {
5432            Error::Codec("run_id is required for selected-run cancellation".to_string())
5433        })?;
5434        self.client
5435            .cancel_workflow_run(&self.workflow_id, run_id, options)
5436            .await
5437    }
5438
5439    /// Forcefully terminate whichever run is current.
5440    pub async fn terminate(
5441        &self,
5442        options: WorkflowCommandOptions,
5443    ) -> Result<WorkflowCommandResult> {
5444        self.client
5445            .terminate_workflow(&self.workflow_id, options)
5446            .await
5447    }
5448
5449    /// Terminate only if this handle's selected run is still current.
5450    pub async fn terminate_selected_run(
5451        &self,
5452        options: WorkflowCommandOptions,
5453    ) -> Result<WorkflowCommandResult> {
5454        let run_id = self.run_id.as_deref().ok_or_else(|| {
5455            Error::Codec("run_id is required for selected-run termination".to_string())
5456        })?;
5457        self.client
5458            .terminate_workflow_run(&self.workflow_id, run_id, options)
5459            .await
5460    }
5461
5462    /// Continue this handle's failed run without repeating completed activities.
5463    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5464        let run_id = self
5465            .run_id
5466            .as_deref()
5467            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5468        self.client
5469            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5470            .await
5471    }
5472
5473    /// Execute a named, read-only query against this workflow.
5474    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5475        self.client
5476            .query_workflow(&self.workflow_id, query_name, input)
5477            .await
5478    }
5479
5480    pub async fn query_avro_value<T: Serialize>(
5481        &self,
5482        query_name: &str,
5483        input: T,
5484    ) -> Result<AvroValue> {
5485        self.client
5486            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5487            .await
5488    }
5489
5490    pub async fn update<T: Serialize>(
5491        &self,
5492        update_name: &str,
5493        input: T,
5494        request_id: Option<&str>,
5495    ) -> Result<Value> {
5496        self.client
5497            .update_workflow(&self.workflow_id, update_name, input, request_id)
5498            .await
5499    }
5500
5501    pub async fn update_avro_value<T: Serialize>(
5502        &self,
5503        update_name: &str,
5504        input: T,
5505        request_id: Option<&str>,
5506    ) -> Result<AvroValue> {
5507        self.client
5508            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5509            .await
5510    }
5511
5512    /// Query only if this handle's selected run is still current.
5513    pub async fn query_selected_run<T: Serialize>(
5514        &self,
5515        query_name: &str,
5516        input: T,
5517    ) -> Result<Value> {
5518        let run_id = self
5519            .run_id
5520            .as_deref()
5521            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5522        self.client
5523            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5524            .await
5525    }
5526
5527    /// Await the final terminal outcome of the current continue-as-new chain.
5528    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5529        self.result_target(options, None).await
5530    }
5531
5532    /// Await the final result without projecting Avro bytes through JSON.
5533    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5534        self.result_avro_value_target(options, None).await
5535    }
5536
5537    /// Await the final result and decode it into a Serde application type.
5538    pub async fn result_typed<T: DeserializeOwned>(
5539        &self,
5540        options: WorkflowResultOptions,
5541    ) -> Result<T> {
5542        let result = self.result_avro_value(options).await?;
5543        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5544    }
5545
5546    /// Await only the run identity originally selected by this handle.
5547    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5548        let run_id = self.run_id.as_deref().ok_or_else(|| {
5549            Error::Codec("run_id is required for selected-run result".to_string())
5550        })?;
5551        self.result_target(options, Some(run_id)).await
5552    }
5553
5554    /// Await the selected run's result on the lossless Avro Value surface.
5555    pub async fn result_selected_run_avro_value(
5556        &self,
5557        options: WorkflowResultOptions,
5558    ) -> Result<AvroValue> {
5559        let run_id = self.run_id.as_deref().ok_or_else(|| {
5560            Error::Codec("run_id is required for selected-run result".to_string())
5561        })?;
5562        self.result_avro_value_target(options, Some(run_id)).await
5563    }
5564
5565    /// Await the selected run and decode its result into a Serde type.
5566    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5567        &self,
5568        options: WorkflowResultOptions,
5569    ) -> Result<T> {
5570        let result = self.result_selected_run_avro_value(options).await?;
5571        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5572    }
5573
5574    async fn result_avro_value_target(
5575        &self,
5576        options: WorkflowResultOptions,
5577        selected_run_id: Option<&str>,
5578    ) -> Result<AvroValue> {
5579        let started = Instant::now();
5580
5581        loop {
5582            let description = match selected_run_id {
5583                Some(run_id) => {
5584                    self.client
5585                        .describe_workflow_run(&self.workflow_id, run_id)
5586                        .await?
5587                }
5588                None => self.describe().await?,
5589            };
5590            if description.is_completed() {
5591                return description.output_avro_value.ok_or_else(|| {
5592                    Error::Codec(
5593                        "missing_payload_envelope: typed workflow result requires output_envelope"
5594                            .to_string(),
5595                    )
5596                });
5597            }
5598            if description.is_terminal() {
5599                let outcome =
5600                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5601                return Err(match outcome.kind {
5602                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5603                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5604                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5605                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5606                });
5607            }
5608            if started.elapsed() >= options.timeout {
5609                return Err(Error::Timeout);
5610            }
5611            tokio::time::sleep(options.poll_interval).await;
5612        }
5613    }
5614
5615    async fn result_target(
5616        &self,
5617        options: WorkflowResultOptions,
5618        selected_run_id: Option<&str>,
5619    ) -> Result<Value> {
5620        let started = Instant::now();
5621
5622        loop {
5623            let description = match selected_run_id {
5624                Some(run_id) => {
5625                    self.client
5626                        .describe_workflow_run(&self.workflow_id, run_id)
5627                        .await?
5628                }
5629                None => self.describe().await?,
5630            };
5631            if description.is_completed() {
5632                return Ok(description.output.unwrap_or(Value::Null));
5633            }
5634
5635            if description.is_terminal() {
5636                let outcome =
5637                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5638                return Err(match outcome.kind {
5639                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5640                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5641                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5642                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5643                });
5644            }
5645
5646            if started.elapsed() >= options.timeout {
5647                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5648                    kind: WorkflowTerminalKind::TimedOut,
5649                    workflow_id: description
5650                        .workflow_id
5651                        .clone()
5652                        .unwrap_or_else(|| self.workflow_id.clone()),
5653                    run_id: description
5654                        .run_id
5655                        .clone()
5656                        .or_else(|| selected_run_id.map(str::to_string)),
5657                    reason: "result_wait_timeout".to_string(),
5658                    failure_category: Some("client_timeout".to_string()),
5659                    failure_id: None,
5660                    exception_type: None,
5661                    exception_class: None,
5662                    non_retryable: None,
5663                    message: Some(format!(
5664                        "workflow result was not terminal within {:?}",
5665                        options.timeout
5666                    )),
5667                    exception: None,
5668                    raw: description.raw_value(),
5669                }));
5670            }
5671
5672            tokio::time::sleep(options.poll_interval).await;
5673        }
5674    }
5675}
5676
5677#[derive(Clone, Copy, Debug)]
5678pub struct WorkflowResultOptions {
5679    pub poll_interval: Duration,
5680    pub timeout: Duration,
5681}
5682
5683impl Default for WorkflowResultOptions {
5684    fn default() -> Self {
5685        Self {
5686            poll_interval: Duration::from_millis(500),
5687            timeout: Duration::from_secs(30),
5688        }
5689    }
5690}
5691
5692#[derive(Clone, Debug, Deserialize)]
5693pub struct WorkflowDescription {
5694    pub workflow_id: Option<String>,
5695    pub run_id: Option<String>,
5696    pub workflow_type: Option<String>,
5697    pub status: Option<String>,
5698    #[serde(default)]
5699    pub closed_reason: Option<String>,
5700    #[serde(default)]
5701    pub error: Option<String>,
5702    #[serde(default)]
5703    pub failure: Option<Value>,
5704    #[serde(default)]
5705    pub exception: Option<Value>,
5706    #[serde(default)]
5707    pub failures: Vec<Value>,
5708    #[serde(default)]
5709    pub output: Option<Value>,
5710    #[serde(default)]
5711    pub output_envelope: Option<Value>,
5712    #[serde(skip)]
5713    pub output_avro_value: Option<AvroValue>,
5714    #[serde(flatten)]
5715    pub raw: HashMap<String, Value>,
5716}
5717
5718/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5719#[derive(Clone, Debug, Deserialize)]
5720pub struct WorkflowStreamDescription {
5721    pub stream_name: String,
5722    pub status: String,
5723    pub last_offset: i64,
5724    pub total_items: u64,
5725    pub pending_items: u64,
5726    #[serde(default)]
5727    pub opened_at: Option<String>,
5728    #[serde(default)]
5729    pub last_appended_at: Option<String>,
5730    #[serde(default)]
5731    pub closed_at: Option<String>,
5732    #[serde(default)]
5733    pub error_reason: Option<String>,
5734    #[serde(default)]
5735    pub retention_seconds: Option<u64>,
5736    #[serde(flatten)]
5737    pub raw: HashMap<String, Value>,
5738}
5739
5740impl WorkflowStreamDescription {
5741    pub fn is_terminal(&self) -> bool {
5742        matches!(self.status.as_str(), "closed" | "errored")
5743    }
5744}
5745
5746/// One item for direct or replay-safe append.
5747#[derive(Clone, Debug, Default)]
5748pub struct WorkflowStreamAppendItem {
5749    pub payload_envelope: Option<Value>,
5750    pub payload_reference: Option<String>,
5751    pub item_type: Option<String>,
5752    pub content_type: Option<String>,
5753    pub idempotency_key: Option<String>,
5754}
5755
5756impl WorkflowStreamAppendItem {
5757    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5758    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5759        let value = AvroValue::from_serialize(&payload)?;
5760        Ok(Self {
5761            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5762            ..Self::default()
5763        })
5764    }
5765
5766    /// Preserve an external payload URI as an opaque service-contract reference.
5767    pub fn from_reference(reference: impl Into<String>) -> Self {
5768        Self {
5769            payload_reference: Some(reference.into()),
5770            ..Self::default()
5771        }
5772    }
5773
5774    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5775        self.item_type = Some(item_type.into());
5776        self
5777    }
5778
5779    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5780        self.content_type = Some(content_type.into());
5781        self
5782    }
5783
5784    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5785        self.idempotency_key = Some(idempotency_key.into());
5786        self
5787    }
5788
5789    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5790        let mut item = serde_json::Map::new();
5791        if let Some(payload) = &self.payload_envelope {
5792            item.insert("payload".to_string(), payload.clone());
5793            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5794        }
5795        if let Some(reference) = &self.payload_reference {
5796            item.insert("payload_reference".to_string(), json!(reference));
5797        }
5798        if let Some(item_type) = &self.item_type {
5799            item.insert("item_type".to_string(), json!(item_type));
5800        }
5801        if let Some(content_type) = &self.content_type {
5802            item.insert("content_type".to_string(), json!(content_type));
5803        }
5804        if let Some(key) = derived_idempotency_key
5805            .as_ref()
5806            .or(self.idempotency_key.as_ref())
5807        {
5808            item.insert("idempotency_key".to_string(), json!(key));
5809        }
5810        Value::Object(item)
5811    }
5812}
5813
5814/// One durable item at its stable zero-based offset.
5815#[derive(Clone, Debug)]
5816pub struct WorkflowStreamItem {
5817    pub offset: u64,
5818    pub payload: Option<Value>,
5819    pub payload_envelope: Option<Value>,
5820    pub payload_reference: Option<String>,
5821    pub payload_codec: Option<String>,
5822    pub idempotency_key: Option<String>,
5823    pub item_type: Option<String>,
5824    pub content_type: Option<String>,
5825    pub origin: Option<String>,
5826    pub origin_reference: Option<String>,
5827    pub emitted_at: Option<String>,
5828    pub raw: Value,
5829}
5830
5831/// One bounded at-least-once subscription page.
5832#[derive(Clone, Debug)]
5833pub struct WorkflowStreamPage {
5834    pub stream: WorkflowStreamDescription,
5835    pub items: Vec<WorkflowStreamItem>,
5836    pub next_offset: u64,
5837    pub terminal: bool,
5838}
5839
5840/// Durable acceptance and deduplication outcome for an append request.
5841#[derive(Clone, Debug)]
5842pub struct WorkflowStreamAppendResult {
5843    pub stream: WorkflowStreamDescription,
5844    pub accepted_offsets: Vec<u64>,
5845    pub accepted: u64,
5846    pub deduped: u64,
5847}
5848
5849#[derive(Deserialize)]
5850struct WorkflowStreamListResponse {
5851    #[serde(default)]
5852    streams: Vec<WorkflowStreamDescription>,
5853}
5854
5855#[derive(Deserialize)]
5856struct WorkflowStreamDescriptionResponse {
5857    stream: WorkflowStreamDescription,
5858}
5859
5860#[derive(Deserialize)]
5861struct WorkflowStreamPageResponse {
5862    stream: WorkflowStreamDescription,
5863    #[serde(default)]
5864    items: Vec<Value>,
5865    next_offset: u64,
5866    terminal: bool,
5867}
5868
5869#[derive(Deserialize)]
5870struct WorkflowStreamAppendResponse {
5871    stream: WorkflowStreamDescription,
5872    #[serde(default)]
5873    accepted_offsets: Vec<u64>,
5874    accepted: u64,
5875    deduped: u64,
5876}
5877
5878impl WorkflowDescription {
5879    pub fn is_completed(&self) -> bool {
5880        matches!(self.status.as_deref(), Some("completed" | "Completed"))
5881    }
5882
5883    pub fn is_terminal(&self) -> bool {
5884        matches!(
5885            self.status.as_deref(),
5886            Some(
5887                "completed"
5888                    | "Completed"
5889                    | "failed"
5890                    | "Failed"
5891                    | "cancelled"
5892                    | "Cancelled"
5893                    | "terminated"
5894                    | "Terminated"
5895                    | "timed_out"
5896                    | "TimedOut",
5897            )
5898        )
5899    }
5900
5901    fn decode_payloads(&mut self) -> Result<()> {
5902        if let Some(envelope) = &self.output_envelope {
5903            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
5904            self.output = Some(value.clone().into_json()?);
5905            self.output_avro_value = Some(value);
5906        }
5907
5908        Ok(())
5909    }
5910
5911    fn raw_value(&self) -> Value {
5912        let mut data = self.raw.clone();
5913        data.insert(
5914            "workflow_id".to_string(),
5915            self.workflow_id
5916                .clone()
5917                .map(Value::String)
5918                .unwrap_or(Value::Null),
5919        );
5920        data.insert(
5921            "run_id".to_string(),
5922            self.run_id
5923                .clone()
5924                .map(Value::String)
5925                .unwrap_or(Value::Null),
5926        );
5927        data.insert(
5928            "workflow_type".to_string(),
5929            self.workflow_type
5930                .clone()
5931                .map(Value::String)
5932                .unwrap_or(Value::Null),
5933        );
5934        data.insert(
5935            "status".to_string(),
5936            self.status
5937                .clone()
5938                .map(Value::String)
5939                .unwrap_or(Value::Null),
5940        );
5941        data.insert(
5942            "closed_reason".to_string(),
5943            self.closed_reason
5944                .clone()
5945                .map(Value::String)
5946                .unwrap_or(Value::Null),
5947        );
5948        if let Some(failure) = &self.failure {
5949            data.insert("failure".to_string(), failure.clone());
5950        }
5951        if let Some(exception) = &self.exception {
5952            data.insert("exception".to_string(), exception.clone());
5953        }
5954        Value::Object(data.into_iter().collect())
5955    }
5956}
5957
5958fn workflow_terminal_outcome(
5959    description: &WorkflowDescription,
5960    workflow_id: &str,
5961    run_id: Option<&str>,
5962) -> WorkflowTerminalOutcome {
5963    let terminal_kind = description
5964        .closed_reason
5965        .as_deref()
5966        .or(description.status.as_deref())
5967        .unwrap_or("failed")
5968        .to_ascii_lowercase();
5969    let kind = match terminal_kind.as_str() {
5970        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
5971        "terminated" => WorkflowTerminalKind::Terminated,
5972        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
5973        _ => WorkflowTerminalKind::Failed,
5974    };
5975    let default_reason = match kind {
5976        WorkflowTerminalKind::Failed => "workflow_failed",
5977        WorkflowTerminalKind::Cancelled => "cancelled",
5978        WorkflowTerminalKind::Terminated => "terminated",
5979        WorkflowTerminalKind::TimedOut => "timed_out",
5980    };
5981    let failure = description
5982        .failure
5983        .as_ref()
5984        .filter(|value| value.is_object());
5985    let nested_failure = failure
5986        .and_then(|value| value.get("failures"))
5987        .and_then(Value::as_array)
5988        .and_then(|failures| failures.last())
5989        .or_else(|| description.failures.last());
5990    let exception = description
5991        .exception
5992        .clone()
5993        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
5994        .or_else(|| {
5995            nested_failure
5996                .and_then(|value| value.get("exception_payload"))
5997                .cloned()
5998        });
5999    let string_field = |name: &str| {
6000        failure
6001            .and_then(|value| value.get(name))
6002            .and_then(Value::as_str)
6003            .or_else(|| {
6004                nested_failure
6005                    .and_then(|value| value.get(name))
6006                    .and_then(Value::as_str)
6007            })
6008            .map(str::to_string)
6009    };
6010    let exception_field = |name: &str| {
6011        exception
6012            .as_ref()
6013            .and_then(|value| value.get(name))
6014            .and_then(Value::as_str)
6015            .map(str::to_string)
6016    };
6017    let message = description
6018        .error
6019        .clone()
6020        .or_else(|| string_field("message"))
6021        .or_else(|| exception_field("message"));
6022    let reason = description
6023        .raw
6024        .get("reason")
6025        .and_then(Value::as_str)
6026        .map(str::to_string)
6027        .or_else(|| {
6028            failure
6029                .and_then(|value| value.get("reason"))
6030                .and_then(Value::as_str)
6031                .map(str::to_string)
6032        })
6033        .or_else(|| description.closed_reason.clone())
6034        .unwrap_or_else(|| default_reason.to_string());
6035    let failure_id = string_field("failure_id").or_else(|| {
6036        nested_failure
6037            .and_then(|value| value.get("id"))
6038            .and_then(Value::as_str)
6039            .map(str::to_string)
6040    });
6041
6042    WorkflowTerminalOutcome {
6043        kind,
6044        workflow_id: description
6045            .workflow_id
6046            .clone()
6047            .unwrap_or_else(|| workflow_id.to_string()),
6048        run_id: description
6049            .run_id
6050            .clone()
6051            .or_else(|| run_id.map(str::to_string)),
6052        reason,
6053        failure_category: string_field("failure_category")
6054            .or_else(|| Some(default_reason.to_string())),
6055        failure_id,
6056        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6057        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6058        non_retryable: failure
6059            .and_then(|value| value.get("non_retryable"))
6060            .and_then(Value::as_bool)
6061            .or_else(|| {
6062                nested_failure
6063                    .and_then(|value| value.get("non_retryable"))
6064                    .and_then(Value::as_bool)
6065            }),
6066        message,
6067        exception,
6068        raw: description.raw_value(),
6069    }
6070}
6071
6072#[derive(Clone, Debug, Deserialize)]
6073pub struct RegisterWorkerResponse {
6074    pub worker_id: String,
6075    pub registered: bool,
6076    #[serde(default)]
6077    pub heartbeat_interval_seconds: Option<u64>,
6078    #[serde(default)]
6079    pub protocol_version: Option<String>,
6080    #[serde(default)]
6081    pub server_capabilities: Option<Value>,
6082}
6083
6084/// Result of gracefully removing a worker-plane registration.
6085#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6086pub struct WorkerDeregistrationEnvelope {
6087    pub worker_id: String,
6088    pub outcome: String,
6089    pub recovered_workflow_task_count: u64,
6090}
6091
6092#[derive(Clone, Debug, Deserialize)]
6093pub struct PollWorkflowTaskResponse {
6094    #[serde(default)]
6095    pub task: Option<WorkflowTask>,
6096    #[serde(default)]
6097    pub poll_status: Option<String>,
6098    #[serde(default)]
6099    pub reason: Option<String>,
6100    #[serde(default)]
6101    pub protocol_version: Option<String>,
6102    #[serde(default)]
6103    pub server_capabilities: Option<Value>,
6104}
6105
6106impl PollWorkflowTaskResponse {
6107    /// Classify this response without parsing server display text.
6108    pub fn outcome(&self) -> WorkerPollOutcome {
6109        worker_poll_outcome(
6110            self.task.is_some(),
6111            self.poll_status.as_deref(),
6112            self.reason.as_deref(),
6113        )
6114    }
6115}
6116
6117fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6118    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6119        return false;
6120    };
6121    let supported = capabilities
6122        .get("workflow_memo_updates")
6123        .and_then(Value::as_object)
6124        .and_then(|memo| memo.get("supported"))
6125        .and_then(Value::as_bool)
6126        == Some(true);
6127    let command_advertised = capabilities
6128        .get("supported_workflow_task_commands")
6129        .and_then(Value::as_array)
6130        .is_some_and(|commands| {
6131            commands
6132                .iter()
6133                .any(|command| command.as_str() == Some("upsert_memo"))
6134        });
6135    supported && command_advertised
6136}
6137
6138fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6139    commands
6140        .iter()
6141        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6142}
6143
6144#[derive(Clone, Debug, Deserialize)]
6145pub struct PollActivityTaskResponse {
6146    #[serde(default)]
6147    pub task: Option<ActivityTask>,
6148    #[serde(default)]
6149    pub poll_status: Option<String>,
6150    #[serde(default)]
6151    pub reason: Option<String>,
6152}
6153
6154impl PollActivityTaskResponse {
6155    /// Classify this response without parsing server display text.
6156    pub fn outcome(&self) -> WorkerPollOutcome {
6157        worker_poll_outcome(
6158            self.task.is_some(),
6159            self.poll_status.as_deref(),
6160            self.reason.as_deref(),
6161        )
6162    }
6163}
6164
6165#[derive(Clone, Debug, Deserialize)]
6166pub struct PollQueryTaskResponse {
6167    #[serde(default)]
6168    pub task: Option<QueryTask>,
6169    #[serde(default)]
6170    pub poll_status: Option<String>,
6171    #[serde(default)]
6172    pub reason: Option<String>,
6173}
6174
6175impl PollQueryTaskResponse {
6176    /// Classify this response without parsing server display text.
6177    pub fn outcome(&self) -> WorkerPollOutcome {
6178        worker_poll_outcome(
6179            self.task.is_some(),
6180            self.poll_status.as_deref(),
6181            self.reason.as_deref(),
6182        )
6183    }
6184}
6185
6186/// Stable classification for worker poll responses.
6187#[derive(Clone, Debug, PartialEq, Eq)]
6188pub enum WorkerPollOutcome {
6189    /// A task was leased and is available on the response.
6190    Task,
6191    /// No task was leased, but the worker should continue polling.
6192    Idle {
6193        poll_status: Option<String>,
6194        reason: Option<String>,
6195    },
6196    /// The server asked this worker to stop claiming new work.
6197    Stop {
6198        poll_status: Option<String>,
6199        reason: Option<String>,
6200    },
6201}
6202
6203impl WorkerPollOutcome {
6204    pub fn should_stop(&self) -> bool {
6205        matches!(self, Self::Stop { .. })
6206    }
6207}
6208
6209fn worker_poll_outcome(
6210    has_task: bool,
6211    poll_status: Option<&str>,
6212    reason: Option<&str>,
6213) -> WorkerPollOutcome {
6214    if worker_poll_is_stop(poll_status, reason) {
6215        return WorkerPollOutcome::Stop {
6216            poll_status: poll_status.map(str::to_string),
6217            reason: reason.map(str::to_string),
6218        };
6219    }
6220
6221    if has_task {
6222        WorkerPollOutcome::Task
6223    } else {
6224        WorkerPollOutcome::Idle {
6225            poll_status: poll_status.map(str::to_string),
6226            reason: reason.map(str::to_string),
6227        }
6228    }
6229}
6230
6231/// An ephemeral server-routed query task.
6232#[derive(Clone, Debug, Deserialize)]
6233pub struct QueryTask {
6234    pub query_task_id: String,
6235    #[serde(default = "default_workflow_task_attempt")]
6236    pub query_task_attempt: u64,
6237    #[serde(default)]
6238    pub lease_owner: Option<String>,
6239    #[serde(default)]
6240    pub workflow_id: Option<String>,
6241    #[serde(default)]
6242    pub run_id: Option<String>,
6243    pub workflow_type: String,
6244    pub query_name: String,
6245    #[serde(
6246        default = "missing_task_payload_codec",
6247        deserialize_with = "deserialize_task_payload_codec"
6248    )]
6249    pub payload_codec: String,
6250    #[serde(default)]
6251    pub workflow_arguments: Option<Value>,
6252    #[serde(default)]
6253    pub query_arguments: Option<Value>,
6254    #[serde(default)]
6255    pub history_events: Vec<HistoryEvent>,
6256    #[serde(default)]
6257    pub history_export: Option<Value>,
6258    #[serde(default)]
6259    pub run_status: Option<String>,
6260}
6261
6262#[derive(Clone, Debug, Deserialize)]
6263pub struct WorkflowTask {
6264    pub task_id: String,
6265    #[serde(default)]
6266    pub workflow_command_id: Option<String>,
6267    #[serde(default)]
6268    pub workflow_id: Option<String>,
6269    #[serde(default)]
6270    pub run_id: Option<String>,
6271    pub workflow_type: String,
6272    #[serde(default)]
6273    pub cancel_requested: bool,
6274    #[serde(
6275        default = "missing_task_payload_codec",
6276        deserialize_with = "deserialize_task_payload_codec"
6277    )]
6278    pub payload_codec: String,
6279    #[serde(default)]
6280    pub arguments: Option<Value>,
6281    #[serde(default)]
6282    pub history_events: Vec<HistoryEvent>,
6283    #[serde(default)]
6284    pub total_history_events: Option<u64>,
6285    #[serde(default)]
6286    pub history_size_bytes: Option<u64>,
6287    #[serde(default)]
6288    pub continue_as_new_recommended: Option<bool>,
6289    #[serde(default)]
6290    pub history_budget_pressure: Option<String>,
6291    #[serde(default)]
6292    pub next_history_page_token: Option<String>,
6293    #[serde(default = "default_workflow_task_attempt")]
6294    pub workflow_task_attempt: u64,
6295    #[serde(default)]
6296    pub workflow_signal_id: Option<String>,
6297    #[serde(default)]
6298    pub signal_name: Option<String>,
6299    #[serde(default)]
6300    pub signal_arguments: Option<Value>,
6301    #[serde(default)]
6302    pub workflow_update_id: Option<String>,
6303    #[serde(default)]
6304    pub update_name: Option<String>,
6305    #[serde(default)]
6306    pub lease_owner: Option<String>,
6307}
6308
6309impl WorkflowTask {
6310    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6311        self.history_events.extend(page.history_events);
6312
6313        if page.total_history_events.is_some() {
6314            self.total_history_events = page.total_history_events;
6315        }
6316
6317        self.next_history_page_token = page
6318            .next_history_page_token
6319            .filter(|token| !token.is_empty());
6320    }
6321}
6322
6323#[derive(Clone, Debug, Deserialize)]
6324struct WorkflowTaskHistoryPage {
6325    #[serde(default)]
6326    history_events: Vec<HistoryEvent>,
6327    #[serde(default)]
6328    total_history_events: Option<u64>,
6329    #[serde(default)]
6330    next_history_page_token: Option<String>,
6331}
6332
6333#[derive(Clone, Debug, Deserialize)]
6334pub struct ActivityTask {
6335    pub task_id: String,
6336    #[serde(default)]
6337    pub activity_attempt_id: Option<String>,
6338    #[serde(default)]
6339    pub attempt_id: Option<String>,
6340    pub activity_type: String,
6341    #[serde(
6342        default = "missing_task_payload_codec",
6343        deserialize_with = "deserialize_task_payload_codec"
6344    )]
6345    pub payload_codec: String,
6346    #[serde(default)]
6347    pub arguments: Option<Value>,
6348    #[serde(default = "default_attempt_number")]
6349    pub attempt_number: u64,
6350    #[serde(default)]
6351    pub lease_owner: Option<String>,
6352}
6353
6354#[derive(Clone, Debug, Serialize, Deserialize)]
6355pub struct HistoryEvent {
6356    #[serde(alias = "type")]
6357    pub event_type: String,
6358    #[serde(default)]
6359    pub payload: Value,
6360    #[serde(flatten)]
6361    pub raw: HashMap<String, Value>,
6362}
6363
6364/// One decoded signal in the committed workflow-history snapshot.
6365#[derive(Clone, Debug, PartialEq)]
6366pub struct QuerySignal {
6367    pub id: Option<String>,
6368    pub name: String,
6369    pub arguments: Vec<Value>,
6370    avro_arguments: Vec<AvroValue>,
6371    pub workflow_sequence: Option<u64>,
6372}
6373
6374impl QuerySignal {
6375    /// Lossless fixed Avro Value arguments for this committed signal.
6376    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6377        &self.avro_arguments
6378    }
6379}
6380
6381/// Immutable state supplied to a registered query handler.
6382///
6383/// This context intentionally exposes no activity, signal-wait, or command
6384/// APIs. Query handlers inspect committed history and return a value; query
6385/// completion does not append an event or advance deterministic execution.
6386#[derive(Clone, Debug)]
6387pub struct QueryContext {
6388    pub workflow_id: Option<String>,
6389    pub run_id: Option<String>,
6390    pub workflow_type: String,
6391    pub run_status: Option<String>,
6392    workflow_input: Value,
6393    workflow_input_avro_value: AvroValue,
6394    history_events: Arc<Vec<HistoryEvent>>,
6395    signal_events: Arc<Vec<QuerySignal>>,
6396}
6397
6398impl QueryContext {
6399    /// The normalized argument list used to start the workflow.
6400    pub fn workflow_input(&self) -> &Value {
6401        &self.workflow_input
6402    }
6403
6404    /// The lossless fixed Avro Value argument list used to start the workflow.
6405    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6406        &self.workflow_input_avro_value
6407    }
6408
6409    /// The immutable committed history used for this query snapshot.
6410    pub fn history_events(&self) -> &[HistoryEvent] {
6411        self.history_events.as_slice()
6412    }
6413
6414    /// All decoded signals in committed workflow order.
6415    pub fn signal_events(&self) -> &[QuerySignal] {
6416        self.signal_events.as_slice()
6417    }
6418
6419    /// Decoded argument lists for each committed signal with `signal_name`.
6420    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6421        self.signal_events
6422            .iter()
6423            .filter(|signal| signal.name == signal_name)
6424            .map(|signal| signal.arguments.clone())
6425            .collect()
6426    }
6427
6428    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6429    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6430        self.signal_events
6431            .iter()
6432            .filter(|signal| signal.name == signal_name)
6433            .map(|signal| signal.avro_arguments.clone())
6434            .collect()
6435    }
6436}
6437
6438#[derive(Clone, Debug, Deserialize)]
6439pub struct ActivityHeartbeatResponse {
6440    #[serde(default)]
6441    pub cancel_requested: bool,
6442    #[serde(default)]
6443    pub heartbeat_recorded: bool,
6444    #[serde(default)]
6445    pub can_continue: Option<bool>,
6446    #[serde(default)]
6447    pub reason: Option<String>,
6448    #[serde(default)]
6449    pub run_closed_reason: Option<String>,
6450    #[serde(default)]
6451    pub run_closed_at: Option<String>,
6452    #[serde(default)]
6453    pub lease_expires_at: Option<String>,
6454    #[serde(default)]
6455    pub last_heartbeat_at: Option<String>,
6456}
6457
6458impl ActivityHeartbeatResponse {
6459    /// Whether the activity should stop instead of attempting completion.
6460    pub fn should_stop(&self) -> bool {
6461        self.cancel_requested || self.can_continue == Some(false)
6462    }
6463}
6464
6465fn missing_task_payload_codec() -> String {
6466    MISSING_TASK_PAYLOAD_CODEC.to_string()
6467}
6468
6469fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6470where
6471    D: Deserializer<'de>,
6472{
6473    Ok(match Value::deserialize(deserializer)? {
6474        Value::String(codec) => codec,
6475        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6476        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6477    })
6478}
6479
6480fn default_workflow_task_attempt() -> u64 {
6481    1
6482}
6483
6484fn default_attempt_number() -> u64 {
6485    1
6486}
6487
6488type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6489type WorkflowHandler = Arc<dyn Fn(WorkflowContext, AvroValue) -> WorkflowFuture + Send + Sync>;
6490type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6491type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6492type ReplayedWorkflowHandler =
6493    Arc<dyn Fn(WorkflowContext, AvroValue) -> ReplayedWorkflowInvocation + Send + Sync>;
6494type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6495type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6496type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6497type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6498type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6499type ReplayedQueryHandler = Arc<
6500    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6501        + Send
6502        + Sync,
6503>;
6504type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6505
6506struct ReplayedWorkflowInvocation {
6507    future: WorkflowFuture,
6508    snapshot: WorkflowStateSnapshot,
6509}
6510
6511#[derive(Clone)]
6512struct RegisteredWorkflow {
6513    execute: WorkflowHandler,
6514    replay: Option<ReplayedWorkflowHandler>,
6515    state_type: Option<TypeId>,
6516    definition_fingerprint: Option<String>,
6517}
6518
6519fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
6520    names
6521        .iter()
6522        .map(|name| {
6523            json!({
6524                "name": name,
6525                "parameters": [{
6526                    "name": "args",
6527                    "position": 0,
6528                    "required": false,
6529                    "variadic": true,
6530                    "type": null,
6531                    "allows_null": true,
6532                    "default_available": false,
6533                    "default": null,
6534                }],
6535            })
6536        })
6537        .collect()
6538}
6539
6540#[derive(Debug)]
6541struct WorkflowTaskDecision {
6542    commands: Vec<Value>,
6543    message_stream_cursors: Vec<Value>,
6544    message_stream_waits: Vec<Value>,
6545    cancellation_delivery: Option<CancellationDelivery>,
6546    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6547    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6548}
6549
6550enum PreparedWorkflowTask {
6551    Decision(WorkflowTaskDecision),
6552    Execution {
6553        task: WorkflowTask,
6554        context: WorkflowContext,
6555        future: WorkflowFuture,
6556    },
6557}
6558
6559impl WorkflowTaskDecision {
6560    fn without_message_streams(commands: Vec<Value>) -> Self {
6561        Self {
6562            commands,
6563            message_stream_cursors: Vec::new(),
6564            message_stream_waits: Vec::new(),
6565            cancellation_delivery: None,
6566            cancellation_scope_opening: None,
6567            cancellation_scope_delivery: None,
6568        }
6569    }
6570}
6571
6572#[derive(Clone)]
6573enum RegisteredQuery {
6574    Snapshot(QueryHandler),
6575    Replayed {
6576        state_type: TypeId,
6577        handler: ReplayedQueryHandler,
6578    },
6579}
6580
6581#[derive(Clone, Debug)]
6582pub struct WorkerHeartbeatObservation {
6583    pub worker_id: String,
6584    pub task_queue: String,
6585    pub acknowledged_at_unix_millis: u64,
6586    pub acknowledgement: Value,
6587}
6588
6589/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6590///
6591/// Expected empty long polls and explicit Server capacity backpressure are
6592/// normal worker states. Capacity backpressure honors the advertised retry
6593/// delay without consuming this retry budget. Other transport failures,
6594/// retryable HTTP 408/429 responses, and server errors are retried with capped
6595/// exponential backoff. Authentication, protocol, codec, and handler failures
6596/// are never retried by the worker.
6597/// Explicit storage admission pauses also preserve the already-serialized worker
6598/// request without consuming this budget or rerunning its handler. The delay is
6599/// capped by `max_backoff`, and shutdown interrupts storage waits.
6600/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6601/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6602/// and `max_retries = 0` disables ordinary retries in either mode.
6603#[derive(Clone, Copy, Debug)]
6604pub struct WorkerRetryPolicy {
6605    /// Number of retries after the initial request fails.
6606    pub max_retries: usize,
6607    /// Delay before the first retry.
6608    pub initial_backoff: Duration,
6609    /// Maximum delay between retries.
6610    pub max_backoff: Duration,
6611}
6612
6613impl Default for WorkerRetryPolicy {
6614    fn default() -> Self {
6615        Self {
6616            max_retries: 5,
6617            initial_backoff: Duration::from_millis(100),
6618            max_backoff: Duration::from_secs(5),
6619        }
6620    }
6621}
6622
6623#[derive(Clone, Debug)]
6624struct WorkerStorageAdmission {
6625    policy: WorkerRetryPolicy,
6626    stop: Arc<AtomicBool>,
6627}
6628
6629struct StopWorkerOnDrop(Arc<AtomicBool>);
6630
6631impl Drop for StopWorkerOnDrop {
6632    fn drop(&mut self) {
6633        self.0.store(true, Ordering::SeqCst);
6634    }
6635}
6636
6637async fn wait_for_worker_stop(stop: &AtomicBool) {
6638    while !stop.load(Ordering::SeqCst) {
6639        tokio::time::sleep(Duration::from_millis(100)).await;
6640    }
6641}
6642
6643#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6644enum ManagedPollOutcome {
6645    Idle,
6646    Handled,
6647    Stop,
6648}
6649
6650#[derive(Clone)]
6651pub struct Worker {
6652    client: Client,
6653    worker_id: String,
6654    task_queue: String,
6655    workflows: HashMap<String, RegisteredWorkflow>,
6656    activities: HashMap<String, ActivityHandler>,
6657    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6658    signals: HashMap<String, Vec<String>>,
6659    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6660    registration_definitions:
6661        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
6662    registration_error: Option<DuplicateRegistrationError>,
6663    max_concurrent_workflow_tasks: usize,
6664    max_concurrent_activity_tasks: usize,
6665    poll_timeout: Duration,
6666    heartbeat_interval: Duration,
6667    retry_policy: WorkerRetryPolicy,
6668    recover_transient_outages: bool,
6669    run_stop: Option<Arc<AtomicBool>>,
6670    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6671    cooperative_cancellation_enabled: bool,
6672    allow_cancellation_scope_authoring: bool,
6673    allow_cancellation_scope_delivery: bool,
6674    cooperative_registration_confirmed: Arc<AtomicBool>,
6675    local_registration_confirmed: Arc<AtomicBool>,
6676    session_registration_confirmed: Arc<AtomicBool>,
6677    sticky_registration_confirmed: Arc<AtomicBool>,
6678    resource_capabilities: Vec<String>,
6679    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6680}
6681
6682impl Worker {
6683    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6684        Self {
6685            client,
6686            worker_id: default_worker_id(),
6687            task_queue: task_queue.into(),
6688            workflows: HashMap::new(),
6689            activities: HashMap::new(),
6690            queries: HashMap::new(),
6691            signals: HashMap::new(),
6692            updates: HashMap::new(),
6693            registration_definitions: HashMap::new(),
6694            registration_error: None,
6695            max_concurrent_workflow_tasks: 10,
6696            max_concurrent_activity_tasks: 10,
6697            poll_timeout: Duration::from_secs(30),
6698            heartbeat_interval: Duration::from_secs(60),
6699            retry_policy: WorkerRetryPolicy::default(),
6700            recover_transient_outages: false,
6701            run_stop: None,
6702            heartbeat_observer: None,
6703            cooperative_cancellation_enabled: false,
6704            allow_cancellation_scope_authoring: false,
6705            allow_cancellation_scope_delivery: false,
6706            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6707            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6708            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6709            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
6710            resource_capabilities: Vec::new(),
6711            sessions: Arc::new(Mutex::new(HashMap::new())),
6712        }
6713    }
6714
6715    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6716        self.worker_id = worker_id.into();
6717        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6718        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6719        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6720        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
6721        self.client.reset_sticky_cache();
6722        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6723        self
6724    }
6725
6726    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6727        self.poll_timeout = timeout;
6728        self
6729    }
6730
6731    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6732        self.heartbeat_interval = interval;
6733        self
6734    }
6735
6736    /// Explicitly enable inline local activities in this workflow worker.
6737    ///
6738    /// The worker advertises the capability to Server only when enabled.
6739    /// These callbacks must yield to Tokio and have idempotent side effects.
6740    /// Cooperative prepared local supervision is a separate capability.
6741    pub fn local_activities(mut self, enabled: bool) -> Self {
6742        self.client.local_activities_enabled = enabled;
6743        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6744        self
6745    }
6746
6747    /// Opt in to separate cooperative workflow cancellation requests.
6748    ///
6749    /// Registration requires the Server to acknowledge this exact worker,
6750    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6751    /// processing uses canonical delivery and activity ownership fences.
6752    /// Existing terminal cancel and terminate operations remain terminal.
6753    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
6754    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6755    /// and [`Worker::run_until`] register automatically.
6756    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6757        self.cooperative_cancellation_enabled = enabled;
6758        self.client.cooperative_worker_protocol = enabled;
6759        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6760        self
6761    }
6762
6763    /// Enable candidate scope authoring without advertising scoped execution.
6764    #[doc(hidden)]
6765    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6766        self.allow_cancellation_scope_authoring = enabled;
6767        self
6768    }
6769
6770    /// Enable the candidate scoped call consumer with canonical authoring.
6771    #[doc(hidden)]
6772    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6773        self.allow_cancellation_scope_delivery = enabled;
6774        self
6775    }
6776
6777    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6778    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6779        self.retry_policy = policy;
6780        self
6781    }
6782
6783    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6784    ///
6785    /// Retries preserve the poll request identity and use capped exponential
6786    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6787    /// An in-flight poll is allowed to finish so leased work is not discarded.
6788    /// Authentication, protocol, codec, handler and task settlement failures
6789    /// remain errors. Registration and deregistration are not retried here.
6790    ///
6791    /// The default is disabled, preserving the bounded retry contract.
6792    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6793    /// even when this option is enabled.
6794    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6795        self.recover_transient_outages = enabled;
6796        self
6797    }
6798
6799    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6800    where
6801        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6802    {
6803        self.heartbeat_observer = Some(Arc::new(observer));
6804        self
6805    }
6806
6807    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6808        self.max_concurrent_workflow_tasks = count.max(1);
6809        self
6810    }
6811
6812    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6813        self.max_concurrent_activity_tasks = count.max(1);
6814        self
6815    }
6816
6817    /// Validate local handler admission without making a Server request.
6818    ///
6819    /// Registration methods retain their existing signatures. A duplicate keeps
6820    /// the original handler and makes this Worker invalid, including its clones.
6821    /// `register`, `run`, `run_until` and `run_once` enforce this check before
6822    /// any network request. Build a new Worker to correct an invalid configuration.
6823    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
6824        match &self.registration_error {
6825            Some(error) => Err(error.clone()),
6826            None => Ok(()),
6827        }
6828    }
6829
6830    #[track_caller]
6831    fn admit_registration<F>(
6832        &mut self,
6833        handler_kind: RegistrationKind,
6834        workflow_type: Option<&str>,
6835        handler_name: &str,
6836        method: &'static str,
6837    ) -> bool {
6838        let location = std::panic::Location::caller();
6839        let definition = HandlerRegistration {
6840            method,
6841            handler_type: type_name::<F>(),
6842            file: location.file(),
6843            line: location.line(),
6844            column: location.column(),
6845        };
6846        let key = (
6847            handler_kind,
6848            workflow_type.map(str::to_owned),
6849            handler_name.to_owned(),
6850        );
6851        if let Some(first_definition) = self.registration_definitions.get(&key) {
6852            if self.registration_error.is_none() {
6853                self.registration_error = Some(DuplicateRegistrationError {
6854                    handler_kind,
6855                    workflow_type: key.1.clone(),
6856                    handler_name: key.2.clone(),
6857                    first_definition: first_definition.clone(),
6858                    second_definition: definition,
6859                });
6860            }
6861            return false;
6862        }
6863        self.registration_definitions.insert(key, definition);
6864        true
6865    }
6866
6867    /// Register a workflow handler.
6868    ///
6869    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6870    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6871    /// while acquiring or decoding a worker task remain worker-operation
6872    /// failures and do not get converted into workflow outcomes.
6873    #[track_caller]
6874    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6875    where
6876        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6877        Fut: Future<Output = Result<Value>> + Send + 'static,
6878    {
6879        let workflow_type = workflow_type.into();
6880        if !self.admit_registration::<F>(
6881            RegistrationKind::Workflow,
6882            None,
6883            &workflow_type,
6884            "register_workflow",
6885        ) {
6886            return;
6887        }
6888        let handler = Arc::new(handler);
6889        self.workflows.insert(
6890            workflow_type,
6891            RegisteredWorkflow {
6892                execute: Arc::new(move |ctx, input| {
6893                    let handler = Arc::clone(&handler);
6894                    Box::pin(async move {
6895                        let result = handler(ctx, input.into_json()?).await?;
6896                        AvroValue::from_serialize(&result)
6897                    })
6898                }),
6899                replay: None,
6900                state_type: None,
6901                definition_fingerprint: None,
6902            },
6903        );
6904    }
6905
6906    /// Register a workflow with one Serde request value and a Serde result.
6907    ///
6908    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
6909    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
6910    /// workflow-specific schema. A task must contain zero arguments for a unit
6911    /// request or exactly one argument for every other request type.
6912    ///
6913    /// See the runnable
6914    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
6915    /// for typed workflow and activity contracts with retry and timeout policy.
6916    #[track_caller]
6917    pub fn register_typed_workflow<I, O, F, Fut>(
6918        &mut self,
6919        workflow_type: impl Into<String>,
6920        handler: F,
6921    ) where
6922        I: DeserializeOwned + Send + 'static,
6923        O: Serialize + Send + 'static,
6924        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
6925        Fut: Future<Output = Result<O>> + Send + 'static,
6926    {
6927        let workflow_type = workflow_type.into();
6928        if !self.admit_registration::<F>(
6929            RegistrationKind::Workflow,
6930            None,
6931            &workflow_type,
6932            "register_typed_workflow",
6933        ) {
6934            return;
6935        }
6936        let handler_name = workflow_type.clone();
6937        let handler = Arc::new(handler);
6938        self.workflows.insert(
6939            workflow_type,
6940            RegisteredWorkflow {
6941                execute: Arc::new(move |ctx, input| {
6942                    let handler = Arc::clone(&handler);
6943                    let handler_name = handler_name.clone();
6944                    Box::pin(async move {
6945                        let input =
6946                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6947                        let result = handler(ctx, input).await?;
6948                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6949                    })
6950                }),
6951                replay: None,
6952                state_type: None,
6953                definition_fingerprint: None,
6954            },
6955        );
6956    }
6957
6958    /// Register a workflow on the lossless fixed Avro Value surface.
6959    #[track_caller]
6960    pub fn register_workflow_avro_value<F, Fut>(
6961        &mut self,
6962        workflow_type: impl Into<String>,
6963        handler: F,
6964    ) where
6965        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
6966        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6967    {
6968        let workflow_type = workflow_type.into();
6969        if !self.admit_registration::<F>(
6970            RegistrationKind::Workflow,
6971            None,
6972            &workflow_type,
6973            "register_workflow_avro_value",
6974        ) {
6975            return;
6976        }
6977        self.workflows.insert(
6978            workflow_type,
6979            RegisteredWorkflow {
6980                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
6981                replay: None,
6982                state_type: None,
6983                definition_fingerprint: None,
6984            },
6985        );
6986    }
6987
6988    /// Register a workflow whose typed instance state can be reconstructed for queries.
6989    ///
6990    /// `state_factory` creates a fresh instance for every normal workflow task and
6991    /// query replay. The workflow handler is the single source of truth for state
6992    /// transitions: it updates [`WorkflowInstance`] after activities and signals
6993    /// resolve. Query replay runs this same handler over committed history and
6994    /// discards any commands it would emit.
6995    #[track_caller]
6996    pub fn register_replayed_workflow<S, Factory, F, Fut>(
6997        &mut self,
6998        workflow_type: impl Into<String>,
6999        state_factory: Factory,
7000        handler: F,
7001    ) where
7002        S: Clone + Send + Sync + 'static,
7003        Factory: Fn() -> S + Send + Sync + 'static,
7004        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7005        Fut: Future<Output = Result<Value>> + Send + 'static,
7006    {
7007        let workflow_type = workflow_type.into();
7008        if !self.admit_registration::<F>(
7009            RegistrationKind::Workflow,
7010            None,
7011            &workflow_type,
7012            "register_replayed_workflow",
7013        ) {
7014            return;
7015        }
7016        let state_factory = Arc::new(state_factory);
7017        let handler = Arc::new(handler);
7018
7019        let execute_factory = Arc::clone(&state_factory);
7020        let execute_handler = Arc::clone(&handler);
7021        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7022            let state = WorkflowInstance::new(execute_factory());
7023            let handler = Arc::clone(&execute_handler);
7024            Box::pin(async move {
7025                let result = handler(ctx, input.into_json()?, state).await?;
7026                AvroValue::from_serialize(&result)
7027            }) as WorkflowFuture
7028        });
7029
7030        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7031            let state = WorkflowInstance::new(state_factory());
7032            let snapshot_state = state.clone();
7033            let snapshot: WorkflowStateSnapshot =
7034                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7035            let replay_handler = Arc::clone(&handler);
7036            let future = async move {
7037                let result = replay_handler(ctx, input.into_json()?, state).await?;
7038                AvroValue::from_serialize(&result)
7039            };
7040            ReplayedWorkflowInvocation {
7041                future: Box::pin(future),
7042                snapshot,
7043            }
7044        });
7045
7046        self.workflows.insert(
7047            workflow_type,
7048            RegisteredWorkflow {
7049                execute,
7050                replay: Some(replay),
7051                state_type: Some(TypeId::of::<S>()),
7052                definition_fingerprint: None,
7053            },
7054        );
7055    }
7056
7057    /// Register a replayable workflow with one Serde request value and result.
7058    ///
7059    /// Normal task execution and instance-state query replay both decode and
7060    /// encode through the fixed Avro Value codec. The state factory and handler
7061    /// otherwise follow [`Worker::register_replayed_workflow`].
7062    #[track_caller]
7063    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7064        &mut self,
7065        workflow_type: impl Into<String>,
7066        state_factory: Factory,
7067        handler: F,
7068    ) where
7069        I: DeserializeOwned + Send + 'static,
7070        O: Serialize + Send + 'static,
7071        S: Clone + Send + Sync + 'static,
7072        Factory: Fn() -> S + Send + Sync + 'static,
7073        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7074        Fut: Future<Output = Result<O>> + Send + 'static,
7075    {
7076        let workflow_type = workflow_type.into();
7077        if !self.admit_registration::<F>(
7078            RegistrationKind::Workflow,
7079            None,
7080            &workflow_type,
7081            "register_typed_replayed_workflow",
7082        ) {
7083            return;
7084        }
7085        let state_factory = Arc::new(state_factory);
7086        let handler = Arc::new(handler);
7087
7088        let execute_name = workflow_type.clone();
7089        let execute_factory = Arc::clone(&state_factory);
7090        let execute_handler = Arc::clone(&handler);
7091        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7092            let state = WorkflowInstance::new(execute_factory());
7093            let handler = Arc::clone(&execute_handler);
7094            let handler_name = execute_name.clone();
7095            Box::pin(async move {
7096                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7097                let result = handler(ctx, input, state).await?;
7098                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7099            }) as WorkflowFuture
7100        });
7101
7102        let replay_name = workflow_type.clone();
7103        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7104            let state = WorkflowInstance::new(state_factory());
7105            let snapshot_state = state.clone();
7106            let snapshot: WorkflowStateSnapshot =
7107                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7108            let handler = Arc::clone(&handler);
7109            let handler_name = replay_name.clone();
7110            let future = async move {
7111                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7112                let result = handler(ctx, input, state).await?;
7113                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7114            };
7115            ReplayedWorkflowInvocation {
7116                future: Box::pin(future),
7117                snapshot,
7118            }
7119        });
7120
7121        self.workflows.insert(
7122            workflow_type,
7123            RegisteredWorkflow {
7124                execute,
7125                replay: Some(replay),
7126                state_type: Some(TypeId::of::<S>()),
7127                definition_fingerprint: None,
7128            },
7129        );
7130    }
7131
7132    /// Declare the signal names consumed by a registered workflow.
7133    ///
7134    /// Call this after registering the workflow and before starting the worker.
7135    /// Names read through `wait_signal` or `signals` need a declaration for
7136    /// Server command admission. Arguments remain arbitrary positional values,
7137    /// including lossless Avro values. This replaces the previous declaration;
7138    /// an empty slice declares no signals. Names are sorted and deduplicated.
7139    /// Existing runs retain the declarations captured when they started.
7140    pub fn declare_workflow_signals(
7141        &mut self,
7142        workflow_type: &str,
7143        signal_names: &[&str],
7144    ) -> Result<()> {
7145        if !self.workflows.contains_key(workflow_type) {
7146            return Err(Error::Codec(format!(
7147                "workflow type {workflow_type:?} is not registered"
7148            )));
7149        }
7150        if signal_names
7151            .iter()
7152            .any(|name| name.is_empty() || *name != name.trim())
7153        {
7154            return Err(Error::Codec(
7155                "signal names must be non-empty and have no surrounding whitespace".into(),
7156            ));
7157        }
7158        let mut names = signal_names
7159            .iter()
7160            .map(|name| (*name).to_string())
7161            .collect::<Vec<_>>();
7162        names.sort();
7163        names.dedup();
7164        self.signals.insert(workflow_type.to_string(), names);
7165        Ok(())
7166    }
7167
7168    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7169    ///
7170    /// Supply `include_str!` values for the workflow body and every helper whose
7171    /// behavior can affect replay. Register the workflow once, then set its
7172    /// identity before starting the worker. Duplicate registrations are invalid. The server
7173    /// rejects reusing a worker ID when its prior fingerprint disappears.
7174    /// Workflows without source identity remain runnable but cannot be safely redriven.
7175    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7176    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7177    pub fn set_workflow_definition_sources(
7178        &mut self,
7179        workflow_type: &str,
7180        sources: &[&str],
7181    ) -> Result<()> {
7182        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7183            return Err(Error::Codec(
7184                "workflow definition sources must be non-empty".to_string(),
7185            ));
7186        }
7187        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7188            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7189        })?;
7190        let mut hasher = Sha256::new();
7191        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7192        hasher.update((workflow_type.len() as u64).to_be_bytes());
7193        hasher.update(workflow_type.as_bytes());
7194        for source in sources {
7195            hasher.update((source.len() as u64).to_be_bytes());
7196            hasher.update(source.as_bytes());
7197        }
7198        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7199        Ok(())
7200    }
7201
7202    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7203    #[track_caller]
7204    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7205        &mut self,
7206        workflow_type: impl Into<String>,
7207        state_factory: Factory,
7208        handler: F,
7209    ) where
7210        S: Clone + Send + Sync + 'static,
7211        Factory: Fn() -> S + Send + Sync + 'static,
7212        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7213        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7214    {
7215        let workflow_type = workflow_type.into();
7216        if !self.admit_registration::<F>(
7217            RegistrationKind::Workflow,
7218            None,
7219            &workflow_type,
7220            "register_replayed_workflow_avro_value",
7221        ) {
7222            return;
7223        }
7224        let state_factory = Arc::new(state_factory);
7225        let handler = Arc::new(handler);
7226
7227        let execute_factory = Arc::clone(&state_factory);
7228        let execute_handler = Arc::clone(&handler);
7229        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7230            let state = WorkflowInstance::new(execute_factory());
7231            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
7232        });
7233
7234        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7235            let state = WorkflowInstance::new(state_factory());
7236            let snapshot_state = state.clone();
7237            let snapshot: WorkflowStateSnapshot =
7238                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7239            ReplayedWorkflowInvocation {
7240                future: Box::pin(handler(ctx, input, state)),
7241                snapshot,
7242            }
7243        });
7244
7245        self.workflows.insert(
7246            workflow_type,
7247            RegisteredWorkflow {
7248                execute,
7249                replay: Some(replay),
7250                state_type: Some(TypeId::of::<S>()),
7251                definition_fingerprint: None,
7252            },
7253        );
7254    }
7255
7256    #[track_caller]
7257    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7258    where
7259        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7260        Fut: Future<Output = Result<Value>> + Send + 'static,
7261    {
7262        let activity_type = activity_type.into();
7263        if !self.admit_registration::<F>(
7264            RegistrationKind::Activity,
7265            None,
7266            &activity_type,
7267            "register_activity",
7268        ) {
7269            return;
7270        }
7271        let handler = Arc::new(handler);
7272        self.activities.insert(
7273            activity_type,
7274            Arc::new(move |ctx, args| {
7275                let handler = Arc::clone(&handler);
7276                Box::pin(async move {
7277                    let result = handler(ctx, args.into_json()?).await?;
7278                    AvroValue::from_serialize(&result)
7279                })
7280            }),
7281        );
7282    }
7283
7284    /// Register an activity with one Serde request value and a Serde result.
7285    ///
7286    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7287    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7288    /// with the activity name and Rust type.
7289    #[track_caller]
7290    pub fn register_typed_activity<I, O, F, Fut>(
7291        &mut self,
7292        activity_type: impl Into<String>,
7293        handler: F,
7294    ) where
7295        I: DeserializeOwned + Send + 'static,
7296        O: Serialize + Send + 'static,
7297        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
7298        Fut: Future<Output = Result<O>> + Send + 'static,
7299    {
7300        let activity_type = activity_type.into();
7301        if !self.admit_registration::<F>(
7302            RegistrationKind::Activity,
7303            None,
7304            &activity_type,
7305            "register_typed_activity",
7306        ) {
7307            return;
7308        }
7309        let handler_name = activity_type.clone();
7310        let handler = Arc::new(handler);
7311        self.activities.insert(
7312            activity_type,
7313            Arc::new(move |ctx, input| {
7314                let handler = Arc::clone(&handler);
7315                let handler_name = handler_name.clone();
7316                Box::pin(async move {
7317                    let input =
7318                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
7319                    let result = handler(ctx, input).await?;
7320                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
7321                })
7322            }),
7323        );
7324    }
7325
7326    /// Register an activity on the lossless fixed Avro Value surface.
7327    #[track_caller]
7328    pub fn register_activity_avro_value<F, Fut>(
7329        &mut self,
7330        activity_type: impl Into<String>,
7331        handler: F,
7332    ) where
7333        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
7334        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7335    {
7336        let activity_type = activity_type.into();
7337        if !self.admit_registration::<F>(
7338            RegistrationKind::Activity,
7339            None,
7340            &activity_type,
7341            "register_activity_avro_value",
7342        ) {
7343            return;
7344        }
7345        self.activities.insert(
7346            activity_type,
7347            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7348        );
7349    }
7350
7351    /// Register a named, read-only query handler for a workflow type.
7352    ///
7353    /// The workflow type must also be registered with [`Worker::register_workflow`]
7354    /// before the worker runs. The handler receives only an immutable committed
7355    /// state snapshot and normalized query arguments.
7356    #[track_caller]
7357    pub fn register_query<F, Fut>(
7358        &mut self,
7359        workflow_type: impl Into<String>,
7360        query_name: impl Into<String>,
7361        handler: F,
7362    ) where
7363        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7364        Fut: Future<Output = Result<Value>> + Send + 'static,
7365    {
7366        let workflow_type = workflow_type.into();
7367        let query_name = query_name.into();
7368        if !self.admit_registration::<F>(
7369            RegistrationKind::Query,
7370            Some(&workflow_type),
7371            &query_name,
7372            "register_query",
7373        ) {
7374            return;
7375        }
7376        let handler = Arc::new(handler);
7377        self.queries.entry(workflow_type).or_default().insert(
7378            query_name,
7379            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
7380                let handler = Arc::clone(&handler);
7381                Box::pin(async move {
7382                    let result = handler(ctx, args.into_json()?).await?;
7383                    AvroValue::from_serialize(&result)
7384                })
7385            })),
7386        );
7387    }
7388
7389    /// Register a query handler on the lossless fixed Avro Value surface.
7390    #[track_caller]
7391    pub fn register_query_avro_value<F, Fut>(
7392        &mut self,
7393        workflow_type: impl Into<String>,
7394        query_name: impl Into<String>,
7395        handler: F,
7396    ) where
7397        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7398        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7399    {
7400        let workflow_type = workflow_type.into();
7401        let query_name = query_name.into();
7402        if !self.admit_registration::<F>(
7403            RegistrationKind::Query,
7404            Some(&workflow_type),
7405            &query_name,
7406            "register_query_avro_value",
7407        ) {
7408            return;
7409        }
7410        self.queries.entry(workflow_type).or_default().insert(
7411            query_name,
7412            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
7413        );
7414    }
7415
7416    /// Register a named query against deterministically replayed instance state.
7417    ///
7418    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
7419    /// same state type `S`. The handler receives an immutable, detached state
7420    /// clone, so successful and failed queries cannot affect workflow execution
7421    /// or the state reconstructed by a later query.
7422    #[track_caller]
7423    pub fn register_replayed_query<S, F, Fut>(
7424        &mut self,
7425        workflow_type: impl Into<String>,
7426        query_name: impl Into<String>,
7427        handler: F,
7428    ) where
7429        S: Clone + Send + Sync + 'static,
7430        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
7431        Fut: Future<Output = Result<Value>> + Send + 'static,
7432    {
7433        let workflow_type = workflow_type.into();
7434        let query_name = query_name.into();
7435        if !self.admit_registration::<F>(
7436            RegistrationKind::Query,
7437            Some(&workflow_type),
7438            &query_name,
7439            "register_replayed_query",
7440        ) {
7441            return;
7442        }
7443        let handler = Arc::new(handler);
7444        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7445            let state = state.downcast::<S>().map_err(|_| {
7446                "registered query state type does not match the replayed workflow state".to_string()
7447            })?;
7448            let handler = Arc::clone(&handler);
7449            Ok(Box::pin(async move {
7450                let result = handler(ctx, state, args.into_json()?).await?;
7451                AvroValue::from_serialize(&result)
7452            }))
7453        });
7454
7455        self.queries.entry(workflow_type).or_default().insert(
7456            query_name,
7457            RegisteredQuery::Replayed {
7458                state_type: TypeId::of::<S>(),
7459                handler: erased_handler,
7460            },
7461        );
7462    }
7463
7464    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7465    #[track_caller]
7466    pub fn register_replayed_query_avro_value<S, F, Fut>(
7467        &mut self,
7468        workflow_type: impl Into<String>,
7469        query_name: impl Into<String>,
7470        handler: F,
7471    ) where
7472        S: Clone + Send + Sync + 'static,
7473        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7474        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7475    {
7476        let workflow_type = workflow_type.into();
7477        let query_name = query_name.into();
7478        if !self.admit_registration::<F>(
7479            RegistrationKind::Query,
7480            Some(&workflow_type),
7481            &query_name,
7482            "register_replayed_query_avro_value",
7483        ) {
7484            return;
7485        }
7486        let handler = Arc::new(handler);
7487        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7488            let state = state.downcast::<S>().map_err(|_| {
7489                "registered query state type does not match the replayed workflow state".to_string()
7490            })?;
7491            Ok(Box::pin(handler(ctx, state, args)))
7492        });
7493
7494        self.queries.entry(workflow_type).or_default().insert(
7495            query_name,
7496            RegisteredQuery::Replayed {
7497                state_type: TypeId::of::<S>(),
7498                handler: erased_handler,
7499            },
7500        );
7501    }
7502
7503    /// Register a synchronous workflow update handler.
7504    #[track_caller]
7505    pub fn register_update<F, Fut>(
7506        &mut self,
7507        workflow_type: impl Into<String>,
7508        update_name: impl Into<String>,
7509        handler: F,
7510    ) where
7511        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7512        Fut: Future<Output = Result<Value>> + Send + 'static,
7513    {
7514        let workflow_type = workflow_type.into();
7515        let update_name = update_name.into();
7516        if !self.admit_registration::<F>(
7517            RegistrationKind::Update,
7518            Some(&workflow_type),
7519            &update_name,
7520            "register_update",
7521        ) {
7522            return;
7523        }
7524        let handler = Arc::new(handler);
7525        self.updates.entry(workflow_type).or_default().insert(
7526            update_name,
7527            Arc::new(move |ctx, args| {
7528                let handler = Arc::clone(&handler);
7529                Box::pin(async move {
7530                    let result = handler(ctx, args.into_json()?).await?;
7531                    AvroValue::from_serialize(&result)
7532                })
7533            }),
7534        );
7535    }
7536
7537    /// Register an update handler on the lossless fixed Avro Value surface.
7538    #[track_caller]
7539    pub fn register_update_avro_value<F, Fut>(
7540        &mut self,
7541        workflow_type: impl Into<String>,
7542        update_name: impl Into<String>,
7543        handler: F,
7544    ) where
7545        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7546        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7547    {
7548        let workflow_type = workflow_type.into();
7549        let update_name = update_name.into();
7550        if !self.admit_registration::<F>(
7551            RegistrationKind::Update,
7552            Some(&workflow_type),
7553            &update_name,
7554            "register_update_avro_value",
7555        ) {
7556            return;
7557        }
7558        self.updates.entry(workflow_type).or_default().insert(
7559            update_name,
7560            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7561        );
7562    }
7563
7564    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7565        self.validate_registration()?;
7566        self.sticky_registration_confirmed
7567            .store(false, Ordering::SeqCst);
7568        self.session_registration_confirmed
7569            .store(false, Ordering::SeqCst);
7570        for capability in &self.resource_capabilities {
7571            worker_session::validate_resource_capability(capability)?;
7572        }
7573        self.local_registration_confirmed
7574            .store(false, Ordering::SeqCst);
7575        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7576            return Err(Error::CooperativeCancellationUnavailable(
7577                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7578            ));
7579        }
7580        let mut command_contracts = serde_json::Map::new();
7581        for workflow_type in self.workflows.keys() {
7582            let mut queries = self
7583                .queries
7584                .get(workflow_type)
7585                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7586                .unwrap_or_default();
7587            queries.sort();
7588            let mut updates = self
7589                .updates
7590                .get(workflow_type)
7591                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7592                .unwrap_or_default();
7593            updates.sort();
7594            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
7595            command_contracts.insert(
7596                workflow_type.clone(),
7597                json!({
7598                    "queries": queries,
7599                    "query_contracts": argument_vector_contracts(&queries),
7600                    "signals": signals,
7601                    "signal_contracts": argument_vector_contracts(&signals),
7602                    "updates": updates,
7603                    "update_contracts": argument_vector_contracts(&updates),
7604                    "update_validators": [],
7605                }),
7606            );
7607        }
7608
7609        self.cooperative_registration_confirmed
7610            .store(false, Ordering::SeqCst);
7611        let response = self
7612            .client
7613            .register_worker_with_definition_fingerprints(
7614                &self.worker_id,
7615                &self.task_queue,
7616                self.workflows.keys().cloned().collect(),
7617                self.activities.keys().cloned().collect(),
7618                self.max_concurrent_workflow_tasks,
7619                self.max_concurrent_activity_tasks,
7620                [
7621                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7622                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7623                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7624                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7625                    self.client
7626                        .local_activities_enabled
7627                        .then(|| "local_activities".to_string()),
7628                    self.client
7629                        .worker_sessions_enabled
7630                        .then(|| "worker_sessions".to_string()),
7631                    self.client
7632                        .sticky_cache
7633                        .is_some()
7634                        .then(|| "sticky_execution".to_string()),
7635                    self.cooperative_cancellation_enabled
7636                        .then(|| "cooperative_cancellation".to_string()),
7637                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7638                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7639                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7640                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7641                ]
7642                .into_iter()
7643                .flatten()
7644                .chain(self.resource_capabilities.iter().cloned())
7645                .collect(),
7646                Value::Object(command_contracts),
7647                Some(
7648                    self.workflows
7649                        .iter()
7650                        .filter_map(|(workflow_type, workflow)| {
7651                            workflow
7652                                .definition_fingerprint
7653                                .as_ref()
7654                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7655                        })
7656                        .collect(),
7657                ),
7658            )
7659            .await?;
7660        if self.cooperative_cancellation_enabled && response.registered {
7661            self.cooperative_registration_confirmed
7662                .store(true, Ordering::SeqCst);
7663        }
7664        if self.client.local_activities_enabled && response.registered {
7665            self.local_registration_confirmed
7666                .store(true, Ordering::SeqCst);
7667        }
7668        if self.client.worker_sessions_enabled && response.registered {
7669            self.session_registration_confirmed
7670                .store(true, Ordering::SeqCst);
7671        }
7672        if self.client.sticky_cache.is_some() && response.registered {
7673            self.sticky_registration_confirmed
7674                .store(true, Ordering::SeqCst);
7675        }
7676        Ok(response)
7677    }
7678
7679    /// Run until shutdown or a terminal worker error occurs.
7680    ///
7681    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7682    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7683    /// authentication, protocol, and other non-retryable failures are returned.
7684    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7685    /// poll and heartbeat outages beyond the ordinary retry budget.
7686    pub async fn run(&self) -> Result<()> {
7687        self.run_until(std::future::pending::<()>()).await
7688    }
7689
7690    /// Run until `shutdown` resolves or a terminal worker error occurs.
7691    ///
7692    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7693    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7694    where
7695        F: Future<Output = ()>,
7696    {
7697        let _clear_cache_on_drop =
7698            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
7699        let stop = Arc::new(AtomicBool::new(false));
7700        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7701        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7702        worker.run_stop = Some(Arc::clone(&stop));
7703        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7704        tokio::pin!(run);
7705        tokio::pin!(shutdown);
7706        tokio::select! {
7707            result = &mut run => result,
7708            _ = &mut shutdown => {
7709                stop.store(true, Ordering::SeqCst);
7710                run.await
7711            }
7712        }
7713    }
7714
7715    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7716        let mut worker = self.clone();
7717        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7718            policy: self.retry_policy,
7719            stop,
7720        });
7721        worker
7722    }
7723
7724    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7725        let registration = self.register().await?;
7726        if !registration.registered {
7727            return Err(Error::WorkerLoop(format!(
7728                "worker registration for {:?} was not accepted",
7729                self.worker_id
7730            )));
7731        }
7732        let registered_worker_id = registration.worker_id.clone();
7733        let primary = self.run_registered_until(stop, registration).await;
7734        let primary = match (primary, self.close_worker_sessions().await) {
7735            (Ok(()), result) => result,
7736            (Err(error), Ok(())) => Err(error),
7737            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7738                primary: Box::new(primary),
7739                deregistration: Box::new(close),
7740            }),
7741        };
7742        self.session_registration_confirmed
7743            .store(false, Ordering::SeqCst);
7744        self.cooperative_registration_confirmed
7745            .store(false, Ordering::SeqCst);
7746        self.local_registration_confirmed
7747            .store(false, Ordering::SeqCst);
7748        let deregistration = self
7749            .client
7750            .deregister_worker_registration(&registered_worker_id)
7751            .await;
7752        self.sticky_registration_confirmed
7753            .store(false, Ordering::SeqCst);
7754        self.client.clear_sticky_cache()?;
7755
7756        match (primary, deregistration) {
7757            (Ok(()), Ok(_)) => Ok(()),
7758            (Ok(()), Err(deregistration)) => Err(deregistration),
7759            (Err(primary), Ok(_)) => Err(primary),
7760            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7761                primary: Box::new(primary),
7762                deregistration: Box::new(deregistration),
7763            }),
7764        }
7765    }
7766
7767    async fn run_registered_until(
7768        &self,
7769        stop: Arc<AtomicBool>,
7770        registration: RegisterWorkerResponse,
7771    ) -> Result<()> {
7772        let heartbeat_interval = Duration::from_secs(
7773            registration
7774                .heartbeat_interval_seconds
7775                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7776        );
7777        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7778        // from the completion of the preceding attempt, including its bounded
7779        // retries. A fixed-epoch interval can leave an already-due tick queued
7780        // while an acknowledgement is slow, producing a catch-up heartbeat as
7781        // soon as that request completes.
7782        let heartbeat = tokio::time::sleep(Duration::ZERO);
7783        tokio::pin!(heartbeat);
7784        // Poll responses may already have leased server-side work by the time
7785        // they become ready, so each poller owns its responses through
7786        // completion or failure instead of racing raw polls in this select.
7787        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7788            let worker = self.clone();
7789            let stop = Arc::clone(&stop);
7790            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7791        });
7792        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7793            let worker = self.clone();
7794            let stop = Arc::clone(&stop);
7795            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7796        });
7797        let mut query_poller = (!self.queries.is_empty()).then(|| {
7798            let worker = self.clone();
7799            let stop = Arc::clone(&stop);
7800            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7801        });
7802
7803        loop {
7804            tokio::select! {
7805                _ = wait_for_worker_stop(&stop) => {
7806                    stop.store(true, Ordering::SeqCst);
7807                    break;
7808                }
7809                _ = &mut heartbeat => {
7810                    let result = self.retry_worker_operation(|| {
7811                        self.client.heartbeat_worker_with_sessions(
7812                            &self.worker_id,
7813                            self.max_concurrent_workflow_tasks,
7814                            self.max_concurrent_activity_tasks,
7815                            self.client.worker_sessions_enabled.then(|| self.session_available()),
7816                        )
7817                    }).await;
7818                    heartbeat
7819                        .as_mut()
7820                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7821                    match result {
7822                        Ok(Some(acknowledgement)) => {
7823                            if let Some(observer) = &self.heartbeat_observer {
7824                                observer(&WorkerHeartbeatObservation {
7825                                    worker_id: self.worker_id.clone(),
7826                                    task_queue: self.task_queue.clone(),
7827                                    acknowledged_at_unix_millis: SystemTime::now()
7828                                        .duration_since(UNIX_EPOCH)
7829                                        .unwrap_or_default()
7830                                        .as_millis()
7831                                        .min(u64::MAX as u128)
7832                                        as u64,
7833                                    acknowledgement,
7834                                });
7835                            }
7836                        }
7837                        Ok(None) => break,
7838                        Err(error) => {
7839                            stop.store(true, Ordering::SeqCst);
7840                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7841                            return Err(error);
7842                        }
7843                    }
7844                }
7845                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
7846                    workflow_poller = None;
7847                    let stopped_by_server = stop.load(Ordering::SeqCst);
7848                    stop.store(true, Ordering::SeqCst);
7849                    let poller_result = optional_poller_result("workflow", result);
7850                    let join_result =
7851                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7852                    poller_result?;
7853                    join_result?;
7854                    if stopped_by_server {
7855                        return Ok(());
7856                    }
7857                    return Err(Error::WorkerLoop(
7858                        "workflow poller stopped unexpectedly".to_string(),
7859                    ));
7860                }
7861                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
7862                    activity_poller = None;
7863                    let stopped_by_server = stop.load(Ordering::SeqCst);
7864                    stop.store(true, Ordering::SeqCst);
7865                    let poller_result = optional_poller_result("activity", result);
7866                    let join_result =
7867                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7868                    poller_result?;
7869                    join_result?;
7870                    if stopped_by_server {
7871                        return Ok(());
7872                    }
7873                    return Err(Error::WorkerLoop(
7874                        "activity poller stopped unexpectedly".to_string(),
7875                    ));
7876                }
7877                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
7878                    query_poller = None;
7879                    let stopped_by_server = stop.load(Ordering::SeqCst);
7880                    stop.store(true, Ordering::SeqCst);
7881                    let poller_result = optional_poller_result("query", result);
7882                    let join_result =
7883                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7884                    poller_result?;
7885                    join_result?;
7886                    if stopped_by_server {
7887                        return Ok(());
7888                    }
7889                    return Err(Error::WorkerLoop(
7890                        "query poller stopped unexpectedly".to_string(),
7891                    ));
7892                }
7893            }
7894        }
7895
7896        join_pollers(
7897            workflow_poller.take(),
7898            activity_poller.take(),
7899            query_poller.take(),
7900        )
7901        .await
7902    }
7903
7904    /// Poll and settle at most one task from each enabled task family.
7905    ///
7906    /// A workflow may reach its server-enforced run deadline while this worker
7907    /// holds a task. When the completion endpoint authoritatively rejects that
7908    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
7909    /// terminal `run_status=failed`, the workflow tick is considered settled:
7910    /// the late command was not recorded and cannot replace the terminal run.
7911    /// Every other completion rejection remains an error. This worker-level
7912    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
7913    /// only bounds how long a client waits for a result.
7914    ///
7915    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
7916    /// the original [`Error::Http`] status and response body.
7917    pub async fn run_once(&self) -> Result<usize> {
7918        self.validate_registration()?;
7919        if self.client.worker_sessions_enabled {
7920            self.require_session_registration()?;
7921        }
7922        if self.cooperative_cancellation_enabled
7923            && !self
7924                .cooperative_registration_confirmed
7925                .load(Ordering::SeqCst)
7926        {
7927            return Err(Error::CooperativeCancellationUnavailable(
7928                "register this cooperative worker before polling tasks".into(),
7929            ));
7930        }
7931        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
7932        let mut handled = 0;
7933        match worker.poll_workflow_once().await? {
7934            ManagedPollOutcome::Handled => handled += 1,
7935            ManagedPollOutcome::Stop => return Ok(handled),
7936            ManagedPollOutcome::Idle => {}
7937        }
7938        match worker.poll_activity_once().await? {
7939            ManagedPollOutcome::Handled => handled += 1,
7940            ManagedPollOutcome::Stop => return Ok(handled),
7941            ManagedPollOutcome::Idle => {}
7942        }
7943        if !self.queries.is_empty() {
7944            match worker.poll_query_once().await? {
7945                ManagedPollOutcome::Handled => handled += 1,
7946                ManagedPollOutcome::Stop => return Ok(handled),
7947                ManagedPollOutcome::Idle => {}
7948            }
7949        }
7950        Ok(handled)
7951    }
7952
7953    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
7954        if self.client.sticky_cache.is_some()
7955            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
7956        {
7957            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
7958        }
7959        if self.client.local_activities_enabled
7960            && !self.local_registration_confirmed.load(Ordering::SeqCst)
7961        {
7962            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
7963        }
7964        if self.cooperative_cancellation_enabled {
7965            return self.poll_cooperative_workflow_once().await;
7966        }
7967        let poll_request_id = unique_request_id("rust-workflow-poll");
7968        let response = self
7969            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
7970            .await;
7971        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
7972            return Ok(ManagedPollOutcome::Idle);
7973        };
7974        if response.outcome().should_stop() {
7975            return Ok(ManagedPollOutcome::Stop);
7976        }
7977        let memo_updates_supported =
7978            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
7979        let Some(task) = response.task else {
7980            return Ok(ManagedPollOutcome::Idle);
7981        };
7982
7983        let task_id = task.task_id.clone();
7984        let attempt = task.workflow_task_attempt;
7985        let run_id = task.run_id.clone();
7986        let lease_owner = task
7987            .lease_owner
7988            .clone()
7989            .unwrap_or_else(|| self.worker_id.clone());
7990
7991        let decision = match self.execute_workflow_with_local_activities(task).await {
7992            Ok(Some(decision)) => Ok(decision),
7993            Ok(None) => return Ok(ManagedPollOutcome::Handled),
7994            Err(error) => Err(error),
7995        };
7996        self.settle_workflow_task_decision(
7997            &task_id,
7998            &lease_owner,
7999            attempt,
8000            run_id.as_deref(),
8001            decision,
8002            memo_updates_supported,
8003            snapshot,
8004        )
8005        .await
8006    }
8007
8008    #[allow(clippy::too_many_arguments)]
8009    async fn settle_workflow_task_decision(
8010        &self,
8011        task_id: &str,
8012        lease_owner: &str,
8013        attempt: u64,
8014        run_id: Option<&str>,
8015        decision: Result<WorkflowTaskDecision>,
8016        memo_updates_supported: bool,
8017        snapshot: Option<sticky_worker::StickySnapshot>,
8018    ) -> Result<ManagedPollOutcome> {
8019        match decision {
8020            Ok(decision)
8021                if decision.cancellation_delivery.is_some()
8022                    || decision.cancellation_scope_delivery.is_some()
8023                    || decision.cancellation_scope_opening.is_some() =>
8024            {
8025                return Err(Error::CooperativeCancellationUnavailable(
8026                    "worker cancellation delivery has not been negotiated".into(),
8027                ));
8028            }
8029            Ok(decision)
8030                if commands_use_workflow_memo_updates(&decision.commands)
8031                    && !memo_updates_supported =>
8032            {
8033                self.client
8034                    .fail_workflow_task(
8035                        task_id,
8036                        lease_owner,
8037                        attempt,
8038                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8039                    )
8040                    .await?;
8041            }
8042            Ok(decision) if decision.commands.is_empty() => {
8043                // A replay can consume a recorded pending durable command
8044                // without producing a new command. The standalone protocol
8045                // acknowledges that state through the typed waiting outcome;
8046                // an empty completion is rejected by servers that require at
8047                // least one executable command.
8048                self.client
8049                    .fail_workflow_task_with_type(
8050                        task_id,
8051                        lease_owner,
8052                        attempt,
8053                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8054                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8055                    )
8056                    .await?;
8057            }
8058            Ok(decision) => {
8059                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8060                let completion = self
8061                    .client
8062                    .complete_workflow_task_with_message_streams(
8063                        task_id,
8064                        lease_owner,
8065                        attempt,
8066                        decision.commands,
8067                        decision.message_stream_cursors,
8068                        decision.message_stream_waits,
8069                        sticky_claim,
8070                    )
8071                    .await;
8072                if let Err(error) = completion {
8073                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8074                    if !workflow_task_completion_is_terminal_timeout(
8075                        &error, task_id, attempt, run_id,
8076                    ) {
8077                        return Err(error);
8078                    }
8079                }
8080            }
8081            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8082            Err(error) => {
8083                self.discard_sticky_snapshot(snapshot.as_ref())?;
8084                self.client
8085                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8086                    .await?;
8087            }
8088        }
8089
8090        Ok(ManagedPollOutcome::Handled)
8091    }
8092
8093    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8094        while !stop.load(Ordering::SeqCst) {
8095            match self.poll_workflow_once().await {
8096                Ok(ManagedPollOutcome::Stop) => {
8097                    stop.store(true, Ordering::SeqCst);
8098                    break;
8099                }
8100                Err(error) => {
8101                    stop.store(true, Ordering::SeqCst);
8102                    return Err(error);
8103                }
8104                _ => {}
8105            }
8106        }
8107
8108        Ok(())
8109    }
8110
8111    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
8112        if self.client.worker_sessions_enabled {
8113            self.require_session_registration()?;
8114        }
8115        if self.cooperative_cancellation_enabled {
8116            return self.poll_cooperative_activity_once().await;
8117        }
8118        let poll_request_id = unique_request_id("rust-activity-poll");
8119        let response = self
8120            .retry_worker_operation(|| {
8121                self.client.poll_activity_task_response_with_request_id(
8122                    &self.worker_id,
8123                    &self.task_queue,
8124                    self.poll_timeout,
8125                    &poll_request_id,
8126                    0,
8127                )
8128            })
8129            .await;
8130        let Some(response) = self.settle_worker_poll_response(response).await? else {
8131            return Ok(ManagedPollOutcome::Idle);
8132        };
8133        if response.outcome().should_stop() {
8134            return Ok(ManagedPollOutcome::Stop);
8135        }
8136        let Some(task) = response.task else {
8137            return Ok(ManagedPollOutcome::Idle);
8138        };
8139
8140        let session = self.track_session_task(task.worker_session.as_ref())?;
8141        let task = task.task;
8142
8143        let task_id = task.task_id.clone();
8144        let attempt_id = task
8145            .activity_attempt_id
8146            .clone()
8147            .or(task.attempt_id.clone())
8148            .unwrap_or_default();
8149        let lease_owner = task
8150            .lease_owner
8151            .clone()
8152            .unwrap_or_else(|| self.worker_id.clone());
8153        let codec = task.payload_codec.clone();
8154        let result = self.execute_session_activity_task(task, session).await;
8155        match result {
8156            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
8157            Ok(value) => {
8158                let completion = self
8159                    .client
8160                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
8161                    .await;
8162                if let Err(error) = completion {
8163                    if !activity_task_rejection_is_final(&error) {
8164                        return Err(error);
8165                    }
8166                }
8167            }
8168            Err(error) => {
8169                let failure = self
8170                    .client
8171                    .fail_activity_task(
8172                        &task_id,
8173                        &attempt_id,
8174                        &lease_owner,
8175                        error.to_string(),
8176                        false,
8177                    )
8178                    .await;
8179                if let Err(error) = failure {
8180                    if !activity_task_rejection_is_final(&error) {
8181                        return Err(error);
8182                    }
8183                }
8184            }
8185        }
8186
8187        Ok(ManagedPollOutcome::Handled)
8188    }
8189
8190    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8191        // Each lane retains its leased response through callback settlement.
8192        // A bounded independent activity must not occupy the cleanup lane too.
8193        // Preserve the existing serial loop unless cooperation is enabled.
8194        let lane_count = if self.cooperative_cancellation_enabled {
8195            self.max_concurrent_activity_tasks
8196        } else {
8197            1
8198        };
8199        let mut lanes = FuturesUnordered::new();
8200        for _ in 0..lane_count {
8201            let worker = self.clone();
8202            let stop = Arc::clone(&stop);
8203            lanes.push(async move {
8204                while !stop.load(Ordering::SeqCst) {
8205                    match worker.poll_activity_once().await {
8206                        Ok(ManagedPollOutcome::Stop) => {
8207                            stop.store(true, Ordering::SeqCst);
8208                            break;
8209                        }
8210                        Err(error) => {
8211                            stop.store(true, Ordering::SeqCst);
8212                            return Err(error);
8213                        }
8214                        _ => {}
8215                    }
8216                }
8217                Ok(())
8218            });
8219        }
8220        // Join every lane before deregistration, including after one fails.
8221        let mut first_error = None;
8222        while let Some(result) = lanes.next().await {
8223            if let Err(error) = result {
8224                first_error.get_or_insert(error);
8225            }
8226        }
8227        first_error.map_or(Ok(()), Err)
8228    }
8229
8230    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
8231        let poll_request_id = unique_request_id("rust-query-poll");
8232        let response = self
8233            .retry_worker_operation(|| {
8234                self.client.poll_query_task_response_with_request_id(
8235                    &self.worker_id,
8236                    &self.task_queue,
8237                    self.poll_timeout,
8238                    &poll_request_id,
8239                    0,
8240                )
8241            })
8242            .await;
8243        let Some(response) = self.settle_worker_poll_response(response).await? else {
8244            return Ok(ManagedPollOutcome::Idle);
8245        };
8246        if response.outcome().should_stop() {
8247            return Ok(ManagedPollOutcome::Stop);
8248        }
8249        let Some(task) = response.task else {
8250            return Ok(ManagedPollOutcome::Idle);
8251        };
8252
8253        let query_task_id = task.query_task_id.clone();
8254        let attempt = task.query_task_attempt;
8255        let lease_owner = task
8256            .lease_owner
8257            .clone()
8258            .unwrap_or_else(|| self.worker_id.clone());
8259        let codec = task.payload_codec.clone();
8260
8261        match self.execute_query_task(task).await {
8262            Ok(value) => {
8263                let result_envelope = match encode_typed_envelope(&value, &codec) {
8264                    Ok(result_envelope) => result_envelope,
8265                    Err(error) => {
8266                        let failure = self
8267                            .client
8268                            .fail_query_task(
8269                                &query_task_id,
8270                                &lease_owner,
8271                                attempt,
8272                                error.to_string(),
8273                                "query_result_encode_failed",
8274                                "QueryResultEncodeFailed",
8275                            )
8276                            .await;
8277                        if let Err(error) = failure {
8278                            if !query_task_rejection_is_final(&error) {
8279                                return Err(error);
8280                            }
8281                        }
8282                        return Ok(ManagedPollOutcome::Handled);
8283                    }
8284                };
8285
8286                if let Err(error) = self
8287                    .client
8288                    .complete_query_task_with_envelope(
8289                        &query_task_id,
8290                        &lease_owner,
8291                        attempt,
8292                        value.clone().into_json()?,
8293                        result_envelope,
8294                    )
8295                    .await
8296                {
8297                    if !query_task_rejection_is_final(&error) {
8298                        return Err(error);
8299                    }
8300                }
8301            }
8302            Err(failure) => {
8303                let result = self
8304                    .client
8305                    .fail_query_task(
8306                        &query_task_id,
8307                        &lease_owner,
8308                        attempt,
8309                        failure.message,
8310                        failure.reason,
8311                        failure.failure_type,
8312                    )
8313                    .await;
8314                if let Err(error) = result {
8315                    if !query_task_rejection_is_final(&error) {
8316                        return Err(error);
8317                    }
8318                }
8319            }
8320        }
8321
8322        Ok(ManagedPollOutcome::Handled)
8323    }
8324
8325    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8326        while !stop.load(Ordering::SeqCst) {
8327            match self.poll_query_once().await {
8328                Ok(ManagedPollOutcome::Stop) => {
8329                    stop.store(true, Ordering::SeqCst);
8330                    break;
8331                }
8332                Err(error) => {
8333                    stop.store(true, Ordering::SeqCst);
8334                    return Err(error);
8335                }
8336                _ => {}
8337            }
8338        }
8339
8340        Ok(())
8341    }
8342
8343    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
8344    where
8345        F: FnMut() -> Fut,
8346        Fut: Future<Output = Result<T>>,
8347    {
8348        let mut retries = 0;
8349
8350        loop {
8351            if self
8352                .run_stop
8353                .as_ref()
8354                .is_some_and(|stop| stop.load(Ordering::SeqCst))
8355            {
8356                return Ok(None);
8357            }
8358            match operation().await {
8359                Err(error)
8360                    if workflow_hydration::stopped(&error)
8361                        && self
8362                            .run_stop
8363                            .as_ref()
8364                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
8365                {
8366                    return Ok(None);
8367                }
8368                Err(error)
8369                    if worker_operation_is_retryable(&error)
8370                        && (retries < self.retry_policy.max_retries
8371                            || (self.recover_transient_outages
8372                                && self.run_stop.is_some()
8373                                && self.retry_policy.max_retries > 0)) =>
8374                {
8375                    retries = retries.saturating_add(1);
8376                    let delay = worker_retry_delay(self.retry_policy, retries)
8377                        .max(Duration::from_millis(1));
8378                    if let Some(stop) = &self.run_stop {
8379                        tokio::select! {
8380                            _ = tokio::time::sleep(delay) => {}
8381                            _ = wait_for_worker_stop(stop) => return Ok(None),
8382                        }
8383                    } else {
8384                        tokio::time::sleep(delay).await;
8385                    }
8386                }
8387                result => return result.map(Some),
8388            }
8389        }
8390    }
8391
8392    async fn settle_worker_poll_response<T>(
8393        &self,
8394        response: Result<Option<T>>,
8395    ) -> Result<Option<T>> {
8396        match response {
8397            Ok(response) => Ok(response),
8398            Err(error) => {
8399                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
8400                    return Err(error);
8401                };
8402                let minimum_delay = self
8403                    .retry_policy
8404                    .initial_backoff
8405                    .max(Duration::from_millis(1));
8406                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
8407                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
8408                Ok(None)
8409            }
8410        }
8411    }
8412
8413    async fn execute_query_task(
8414        &self,
8415        mut task: QueryTask,
8416    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8417        validate_query_task_payloads(&task).map_err(|error| {
8418            QueryTaskExecutionFailure::new(
8419                "query_payload_decode_failed",
8420                error.to_string(),
8421                "QueryPayloadDecodeFailed",
8422            )
8423        })?;
8424
8425        if !self.workflows.contains_key(&task.workflow_type) {
8426            return Err(QueryTaskExecutionFailure::new(
8427                "query_workflow_type_not_registered",
8428                format!("no workflow registered for type {:?}", task.workflow_type),
8429                "WorkflowTypeNotRegistered",
8430            ));
8431        }
8432
8433        let Some(handlers) = self.queries.get(&task.workflow_type) else {
8434            return Err(QueryTaskExecutionFailure::new(
8435                "query_handler_unavailable",
8436                format!(
8437                    "query handlers are unavailable for workflow type {:?}",
8438                    task.workflow_type
8439                ),
8440                "QueryHandlerUnavailable",
8441            ));
8442        };
8443        let Some(query) = handlers.get(&task.query_name) else {
8444            return Err(QueryTaskExecutionFailure::new(
8445                "rejected_unknown_query",
8446                format!("unknown query {:?}", task.query_name),
8447                "QueryFailed",
8448            ));
8449        };
8450
8451        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
8452            .map_err(|error| {
8453            QueryTaskExecutionFailure::new(
8454                "query_payload_decode_failed",
8455                format!("cannot decode query arguments: {error}"),
8456                "QueryPayloadDecodeFailed",
8457            )
8458        })?;
8459        let workflow_input_typed =
8460            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
8461                .map_err(|error| {
8462                    QueryTaskExecutionFailure::new(
8463                        "query_workflow_state_unavailable",
8464                        format!("cannot decode workflow start input: {error}"),
8465                        "QueryWorkflowStateUnavailable",
8466                    )
8467                })?;
8468        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
8469            QueryTaskExecutionFailure::new(
8470                "query_workflow_state_unavailable",
8471                format!("cannot project workflow start input: {error}"),
8472                "QueryWorkflowStateUnavailable",
8473            )
8474        })?;
8475        hydrate_query_history_from_export(&mut task).map_err(|error| {
8476            QueryTaskExecutionFailure::new(
8477                "query_workflow_state_unavailable",
8478                format!("cannot restore query history snapshot: {error}"),
8479                "QueryWorkflowStateUnavailable",
8480            )
8481        })?;
8482        enrich_query_history_from_export(&mut task).map_err(|error| {
8483            QueryTaskExecutionFailure::new(
8484                "query_workflow_state_unavailable",
8485                format!("cannot restore compact query history payloads: {error}"),
8486                "QueryWorkflowStateUnavailable",
8487            )
8488        })?;
8489        let signal_events = query_signal_events(&task).map_err(|error| {
8490            QueryTaskExecutionFailure::new(
8491                "query_workflow_state_unavailable",
8492                format!("cannot decode committed workflow signals: {error}"),
8493                "QueryWorkflowStateUnavailable",
8494            )
8495        })?;
8496        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8497        let context = QueryContext {
8498            workflow_id: task.workflow_id,
8499            run_id: task.run_id,
8500            workflow_type: task.workflow_type.clone(),
8501            run_status: task.run_status,
8502            workflow_input,
8503            workflow_input_avro_value: workflow_input_typed.clone(),
8504            history_events: Arc::clone(&history_events),
8505            signal_events: Arc::new(signal_events),
8506        };
8507
8508        let future = match query {
8509            RegisteredQuery::Snapshot(handler) => handler(context, args),
8510            RegisteredQuery::Replayed {
8511                state_type,
8512                handler,
8513            } => {
8514                let workflow = self
8515                    .workflows
8516                    .get(&task.workflow_type)
8517                    .expect("workflow registration was checked above");
8518                if workflow.state_type != Some(*state_type) {
8519                    return Err(QueryTaskExecutionFailure::new(
8520                        "query_workflow_state_unavailable",
8521                        "replayed query state type does not match its workflow registration",
8522                        "QueryWorkflowStateUnavailable",
8523                    ));
8524                }
8525                let replay = workflow.replay.as_ref().ok_or_else(|| {
8526                    QueryTaskExecutionFailure::new(
8527                        "query_workflow_state_unavailable",
8528                        format!(
8529                            "workflow type {:?} is not registered for instance-state replay",
8530                            task.workflow_type
8531                        ),
8532                        "QueryWorkflowStateUnavailable",
8533                    )
8534                })?;
8535                let workflow_state = Arc::new(Mutex::new(
8536                    WorkflowState::new_with_identity(
8537                        history_events.as_ref().clone(),
8538                        context.workflow_id.clone(),
8539                        context.run_id.clone(),
8540                        self.task_queue.clone(),
8541                        task.payload_codec,
8542                        None,
8543                    )
8544                    .map_err(|error| {
8545                        QueryTaskExecutionFailure::new(
8546                            "query_workflow_state_unavailable",
8547                            format!("workflow replay failed before query: {error}"),
8548                            "QueryWorkflowStateUnavailable",
8549                        )
8550                    })?,
8551                ));
8552                let workflow_context = WorkflowContext {
8553                    state: workflow_state,
8554                    cancellation_scope_id: "root".into(),
8555                };
8556                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
8557                let mut cx = TaskContext::from_waker(noop_waker_ref());
8558                let outcome = {
8559                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8560                        .map_err(|error| {
8561                            QueryTaskExecutionFailure::new(
8562                                "query_workflow_state_unavailable",
8563                                error.to_string(),
8564                                "QueryWorkflowStateUnavailable",
8565                            )
8566                        })?;
8567                    invocation.future.as_mut().poll(&mut cx)
8568                };
8569                match outcome {
8570                    Poll::Ready(Ok(_)) => {
8571                        workflow_context
8572                            .ensure_history_consumed()
8573                            .map_err(|error| {
8574                                QueryTaskExecutionFailure::new(
8575                                    "query_workflow_state_unavailable",
8576                                    format!("workflow replay failed before query: {error}"),
8577                                    "QueryWorkflowStateUnavailable",
8578                                )
8579                            })?;
8580                    }
8581                    Poll::Ready(Err(error)) => {
8582                        return Err(QueryTaskExecutionFailure::new(
8583                            "query_workflow_state_unavailable",
8584                            format!("workflow replay failed before query: {error}"),
8585                            "QueryWorkflowStateUnavailable",
8586                        ));
8587                    }
8588                    Poll::Pending => {
8589                        let commands = workflow_context.take_commands().map_err(|error| {
8590                            QueryTaskExecutionFailure::new(
8591                                "query_workflow_state_unavailable",
8592                                format!("workflow replay failed before query: {error}"),
8593                                "QueryWorkflowStateUnavailable",
8594                            )
8595                        })?;
8596                        if commands.is_empty()
8597                            && !workflow_context
8598                                .matched_recorded_pending()
8599                                .map_err(|error| {
8600                                    QueryTaskExecutionFailure::new(
8601                                        "query_workflow_state_unavailable",
8602                                        format!("workflow replay failed before query: {error}"),
8603                                        "QueryWorkflowStateUnavailable",
8604                                    )
8605                                })?
8606                        {
8607                            return Err(QueryTaskExecutionFailure::new(
8608                                "query_workflow_state_unavailable",
8609                                "workflow replay yielded without a durable command",
8610                                "QueryWorkflowStateUnavailable",
8611                            ));
8612                        }
8613                    }
8614                }
8615                let state = (invocation.snapshot)().map_err(|error| {
8616                    QueryTaskExecutionFailure::new(
8617                        "query_workflow_state_unavailable",
8618                        format!("cannot snapshot replayed workflow state: {error}"),
8619                        "QueryWorkflowStateUnavailable",
8620                    )
8621                })?;
8622                handler(context, state, args).map_err(|message| {
8623                    QueryTaskExecutionFailure::new(
8624                        "query_workflow_state_unavailable",
8625                        message,
8626                        "QueryWorkflowStateUnavailable",
8627                    )
8628                })?
8629            }
8630        };
8631
8632        future.await.map_err(|error| {
8633            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8634        })
8635    }
8636
8637    #[cfg(test)]
8638    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8639        Ok(self.execute_workflow_task_decision(task)?.commands)
8640    }
8641
8642    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8643        self.execute_workflow_task_decision_with_cancellation(task, None)
8644    }
8645
8646    fn execute_workflow_task_decision_with_cancellation(
8647        &self,
8648        task: WorkflowTask,
8649        observation: Option<&CancellationRequest>,
8650    ) -> Result<WorkflowTaskDecision> {
8651        match self.prepare_workflow_task_execution(task, observation)? {
8652            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8653            PreparedWorkflowTask::Execution {
8654                task,
8655                context,
8656                mut future,
8657            } => {
8658                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8659                self.finish_workflow_task_execution(&task, &context, outcome)
8660            }
8661        }
8662    }
8663
8664    fn prepare_workflow_task_execution(
8665        &self,
8666        task: WorkflowTask,
8667        observation: Option<&CancellationRequest>,
8668    ) -> Result<PreparedWorkflowTask> {
8669        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8670            && !self.cooperative_cancellation_enabled
8671        {
8672            return Err(Error::CancellationScopeExecutionUnavailable);
8673        }
8674        validate_workflow_task_payloads(&task)?;
8675        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8676            &task.history_events,
8677            self.allow_cancellation_scope_authoring,
8678            self.allow_cancellation_scope_delivery,
8679        )?;
8680        let cancellation_history = if let Some(observation) = observation {
8681            observation.validate_observation()?;
8682            cooperative_cancellation::cancellation_claim(&task)?;
8683            let canonical = CancellationHistory::from_events(
8684                &task.history_events,
8685                task.run_id.as_deref().unwrap_or_default(),
8686                Some(observation),
8687            )?;
8688            if canonical.request_index >= task.history_events.len() {
8689                return Err(Error::InvalidCooperativeCancellation(
8690                    "workflow replay requires the observed canonical request".into(),
8691                ));
8692            }
8693            Some(canonical)
8694        } else {
8695            None
8696        };
8697        if let Some(update_id) = task
8698            .workflow_update_id
8699            .as_deref()
8700            .filter(|update_id| !update_id.is_empty())
8701        {
8702            if self.allow_cancellation_scope_delivery {
8703                return Err(Error::CancellationScopeExecutionUnavailable);
8704            }
8705            CancellationHistory::from_events(
8706                &task.history_events,
8707                task.run_id.as_deref().unwrap_or_default(),
8708                None,
8709            )?;
8710            return self
8711                .execute_update_task(&task, update_id)
8712                .map(WorkflowTaskDecision::without_message_streams)
8713                .map(PreparedWorkflowTask::Decision);
8714        }
8715
8716        let workflow = self
8717            .workflows
8718            .get(&task.workflow_type)
8719            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
8720        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8721        let resume_signal = decode_resume_signal(&task)?;
8722        let history_budget = WorkflowHistoryBudget {
8723            event_count: task
8724                .total_history_events
8725                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
8726            size_bytes: task.history_size_bytes,
8727            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
8728            pressure: task.history_budget_pressure.clone(),
8729        };
8730        let workflow_command_identity = task
8731            .workflow_command_id
8732            .clone()
8733            .filter(|identity| !identity.is_empty())
8734            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
8735            .unwrap_or_default();
8736        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
8737            task.history_events.clone(),
8738            task.workflow_id.clone(),
8739            task.run_id.clone(),
8740            self.task_queue.clone(),
8741            task.payload_codec.clone(),
8742            resume_signal,
8743            self.allow_cancellation_scope_authoring,
8744            self.allow_cancellation_scope_delivery,
8745        )?;
8746        workflow_state.history_budget = history_budget;
8747        workflow_state.workflow_command_identity = workflow_command_identity;
8748        if let Some(canonical) = cancellation_history {
8749            workflow_state.cancellation_history = canonical;
8750            workflow_state.cancellation_delivery_enabled = true;
8751        }
8752        if workflow_state.cancellation_history.request.is_none() {
8753            workflow_state.cancel_requested = task.cancel_requested;
8754        }
8755        let state = Arc::new(Mutex::new(workflow_state));
8756        let ctx = WorkflowContext {
8757            state,
8758            cancellation_scope_id: "root".into(),
8759        };
8760        let future = (workflow.execute)(ctx.clone(), input);
8761        Ok(PreparedWorkflowTask::Execution {
8762            task,
8763            context: ctx,
8764            future,
8765        })
8766    }
8767
8768    fn poll_workflow_future(
8769        ctx: &WorkflowContext,
8770        future: &mut WorkflowFuture,
8771    ) -> Result<Poll<Result<AvroValue>>> {
8772        let mut cx = TaskContext::from_waker(noop_waker_ref());
8773        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
8774        Ok(future.as_mut().poll(&mut cx))
8775    }
8776
8777    fn finish_workflow_task_execution(
8778        &self,
8779        task: &WorkflowTask,
8780        ctx: &WorkflowContext,
8781        outcome: Poll<Result<AvroValue>>,
8782    ) -> Result<WorkflowTaskDecision> {
8783        if !ctx
8784            .state
8785            .lock()
8786            .map_err(|_| Error::WorkflowStatePoisoned)?
8787            .local_activity_requests
8788            .is_empty()
8789        {
8790            return Err(Error::CooperativeCancellationUnavailable(
8791                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
8792            ));
8793        }
8794        let awaiting_canonical_boundary = {
8795            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8796            state.cancellation_delivery_intent.is_some()
8797                || state.cancellation_scope_opening.is_some()
8798                || state
8799                    .scope_delivery
8800                    .as_ref()
8801                    .is_some_and(|replay| replay.intent.is_some())
8802        };
8803        if awaiting_canonical_boundary {
8804            // A private delivery intent never becomes an application error.
8805            // Even a custom future which ignores a pending durable call cannot
8806            // publish terminal commands before canonical delivery and replay.
8807            if let Poll::Ready(Err(error)) = outcome {
8808                if workflow_task_integrity_error(&error) {
8809                    return Err(error);
8810                }
8811            }
8812            return self.message_stream_decision(&ctx, ctx.take_commands()?);
8813        }
8814
8815        match outcome {
8816            Poll::Ready(Ok(result)) => {
8817                ctx.ensure_history_consumed()?;
8818                let result = encode_typed_envelope(&result, &task.payload_codec)?;
8819                let mut commands = ctx.take_commands()?;
8820                commands.push(json!({
8821                    "type": "complete_workflow",
8822                    "result": result
8823                }));
8824                self.message_stream_decision(&ctx, commands)
8825            }
8826            Poll::Ready(Err(error)) => {
8827                if let Error::ContinueAsNew(request) = error {
8828                    let mut commands = ctx.take_commands()?;
8829                    if let Some(command) = ctx.continue_as_new_command(request)? {
8830                        commands.push(command);
8831                    }
8832                    ctx.ensure_history_consumed()?;
8833                    return self.message_stream_decision(&ctx, commands);
8834                }
8835                if workflow_task_integrity_error(&error) {
8836                    // Replay and protocol failures describe the workflow-task
8837                    // decision itself. Preserve their specific failure reason
8838                    // instead of replacing it with the derivative fact that
8839                    // recorded commands remain unconsumed.
8840                    return Err(error);
8841                }
8842                // A handler error must not hide a committed durable command that
8843                // upgraded workflow code no longer consumes.
8844                ctx.ensure_history_consumed()?;
8845                let mut commands = ctx.take_commands()?;
8846                commands.push(workflow_failure_command(
8847                    &error,
8848                    recorded_activity_failure_boundary(&ctx, &error),
8849                ));
8850                self.message_stream_decision(&ctx, commands)
8851            }
8852            Poll::Pending => {
8853                let commands = ctx.take_commands()?;
8854                if commands.is_empty() && !ctx.matched_recorded_pending()? {
8855                    Err(Error::WorkflowYieldedWithoutCommand)
8856                } else {
8857                    self.message_stream_decision(&ctx, commands)
8858                }
8859            }
8860        }
8861    }
8862
8863    fn message_stream_decision(
8864        &self,
8865        ctx: &WorkflowContext,
8866        commands: Vec<Value>,
8867    ) -> Result<WorkflowTaskDecision> {
8868        if !self.cooperative_cancellation_enabled
8869            && commands.iter().any(|command| {
8870                command["type"] == "schedule_activity"
8871                    && command.get("cancellation_policy").is_some()
8872            })
8873        {
8874            return Err(Error::CooperativeCancellationUnavailable(format!(
8875                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8876                self.worker_id,
8877            )));
8878        }
8879        if !self.cooperative_cancellation_enabled
8880            && commands.iter().any(|command| {
8881                command["type"] == "start_child_workflow"
8882                    && (command["parent_close_policy"] == "request_cancellation"
8883                        || matches!(
8884                            command["cancellation_policy"].as_str(),
8885                            Some("try_cancel" | "wait_cancellation_completed")
8886                        ))
8887            })
8888        {
8889            return Err(Error::CooperativeCancellationUnavailable(format!(
8890                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8891                self.worker_id,
8892            )));
8893        }
8894        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
8895        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8896        let scope_delivery = state
8897            .scope_delivery
8898            .as_ref()
8899            .and_then(|replay| replay.intent.clone());
8900        if scope_delivery
8901            .as_ref()
8902            .is_some_and(|intent| commands.len() != intent.command_count)
8903        {
8904            return Err(invalid_recorded_history(
8905                "cancellation_scope_pending_call_escaped",
8906                scope_delivery.as_ref().unwrap().boundary.sequence,
8907                "commands preceding the pending scoped call",
8908                "commands after suspension",
8909                "workflow cannot publish beyond an uncommitted scope delivery",
8910            ));
8911        }
8912        if let Some(opening) = &state.cancellation_scope_opening {
8913            if commands.len() != opening.command_count {
8914                return Err(invalid_recorded_history(
8915                    "cancellation_scope_pending_call_escaped",
8916                    opening.sequence,
8917                    "commands before original scope opening",
8918                    "commands after suspended opening",
8919                    "workflow cannot publish beyond an uncommitted scope opening",
8920                ));
8921            }
8922        }
8923        if state.cancellation_delivery_intent.is_some()
8924            && commands.len() != state.cancellation_delivery_command_count
8925        {
8926            return Err(invalid_recorded_history(
8927                "cooperative_cancellation_pending_call_escaped",
8928                state
8929                    .cancellation_delivery_intent
8930                    .as_ref()
8931                    .expect("pending delivery")
8932                    .sequence,
8933                "only commands preceding the pending cancellation call",
8934                "commands authored after a suspended call",
8935                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
8936            ));
8937        }
8938        Ok(WorkflowTaskDecision {
8939            commands,
8940            message_stream_cursors,
8941            message_stream_waits,
8942            cancellation_delivery: state.cancellation_delivery_intent.clone(),
8943            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
8944            cancellation_scope_delivery: scope_delivery,
8945        })
8946    }
8947
8948    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
8949        if !self.workflows.contains_key(&task.workflow_type) {
8950            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
8951        }
8952
8953        let accepted = task.history_events.iter().rev().find_map(|event| {
8954            (event.event_type == "UpdateAccepted"
8955                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
8956            .then_some(&event.payload)
8957        });
8958        let update_name = accepted
8959            .and_then(|payload| payload.get("update_name"))
8960            .and_then(Value::as_str)
8961            .or(task.update_name.as_deref())
8962            .unwrap_or_default();
8963        let Some(handler) = self
8964            .updates
8965            .get(&task.workflow_type)
8966            .and_then(|handlers| handlers.get(update_name))
8967        else {
8968            return Ok(vec![json!({
8969                "type": "fail_update",
8970                "update_id": update_id,
8971                "message": format!(
8972                    "no update handler is registered for {}.{update_name}",
8973                    task.workflow_type
8974                ),
8975                "exception_type": "UnknownUpdate",
8976                "non_retryable": true,
8977            })]);
8978        };
8979        let arguments = accepted
8980            .and_then(|payload| payload.get("arguments"))
8981            .or(task.arguments.as_ref());
8982        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
8983        let workflow_input_avro_value =
8984            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8985        let workflow_input = workflow_input_avro_value.clone().into_json()?;
8986        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
8987        let context = QueryContext {
8988            workflow_id: task.workflow_id.clone(),
8989            run_id: task.run_id.clone(),
8990            workflow_type: task.workflow_type.clone(),
8991            run_status: Some("running".to_string()),
8992            workflow_input,
8993            workflow_input_avro_value,
8994            history_events: Arc::new(task.history_events.clone()),
8995            signal_events: Arc::new(signal_events),
8996        };
8997        let mut future = handler(context, arguments);
8998        let mut cx = TaskContext::from_waker(noop_waker_ref());
8999
9000        match future.as_mut().poll(&mut cx) {
9001            Poll::Ready(Ok(result)) => Ok(vec![json!({
9002                "type": "complete_update",
9003                "update_id": update_id,
9004                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9005            })]),
9006            Poll::Ready(Err(error)) => Ok(vec![json!({
9007                "type": "fail_update",
9008                "update_id": update_id,
9009                "message": error.to_string(),
9010                "exception_type": "UpdateFailed",
9011                "non_retryable": true,
9012            })]),
9013            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9014        }
9015    }
9016
9017    #[cfg(test)]
9018    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9019        self.execute_session_activity_task(task, None).await
9020    }
9021
9022    async fn execute_session_activity_task(
9023        &self,
9024        task: ActivityTask,
9025        worker_session: Option<WorkerSession>,
9026    ) -> Result<AvroValue> {
9027        validate_activity_task_payloads(&task)?;
9028        if worker_session.is_some() {
9029            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
9030                || task
9031                    .activity_attempt_id
9032                    .as_deref()
9033                    .or(task.attempt_id.as_deref())
9034                    .is_none_or(str::is_empty)
9035                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
9036            {
9037                return Err(Error::ActivityExecutionAbandoned(
9038                    "session activity requires this worker's exact immutable claim".into(),
9039                ));
9040            }
9041        }
9042
9043        let handler = self
9044            .activities
9045            .get(&task.activity_type)
9046            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
9047        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9048        let attempt_id = task
9049            .activity_attempt_id
9050            .clone()
9051            .or(task.attempt_id.clone())
9052            .unwrap_or_default();
9053        let lease_owner = task
9054            .lease_owner
9055            .clone()
9056            .unwrap_or_else(|| self.worker_id.clone());
9057        let session = worker_session.clone();
9058        let ctx = ActivityContext {
9059            client: self.client.clone(),
9060            task_id: task.task_id,
9061            activity_attempt_id: attempt_id,
9062            lease_owner,
9063            activity_type: task.activity_type,
9064            attempt_number: task.attempt_number,
9065            task_queue: self.task_queue.clone(),
9066            worker_id: self.worker_id.clone(),
9067            claim_guard: None,
9068            local_heartbeats: None,
9069            worker_session,
9070        };
9071
9072        let callback = handler(ctx, args);
9073        if let Some(session) = session {
9074            tokio::select! {
9075                biased;
9076                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
9077                result = callback => if session.active() { result } else {
9078                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
9079                },
9080            }
9081        } else {
9082            callback.await
9083        }
9084    }
9085}
9086
9087fn poller_result(
9088    kind: &str,
9089    result: std::result::Result<Result<()>, tokio::task::JoinError>,
9090) -> Result<()> {
9091    match result {
9092        Ok(result) => result,
9093        Err(error) => Err(Error::WorkerLoop(format!(
9094            "{kind} poller join error: {error}"
9095        ))),
9096    }
9097}
9098
9099fn optional_poller_result(
9100    kind: &str,
9101    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
9102) -> Result<()> {
9103    match result {
9104        Some(result) => poller_result(kind, result),
9105        None => Ok(()),
9106    }
9107}
9108
9109async fn join_pollers(
9110    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9111    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9112    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9113) -> Result<()> {
9114    let mut first_error = None;
9115
9116    if let Some(handle) = workflow_poller {
9117        if let Err(error) = poller_result("workflow", handle.await) {
9118            first_error.get_or_insert(error);
9119        }
9120    }
9121
9122    if let Some(handle) = activity_poller {
9123        if let Err(error) = poller_result("activity", handle.await) {
9124            first_error.get_or_insert(error);
9125        }
9126    }
9127
9128    if let Some(handle) = query_poller {
9129        if let Err(error) = poller_result("query", handle.await) {
9130            first_error.get_or_insert(error);
9131        }
9132    }
9133
9134    if let Some(error) = first_error {
9135        Err(error)
9136    } else {
9137        Ok(())
9138    }
9139}
9140
9141fn default_worker_id() -> String {
9142    let millis = SystemTime::now()
9143        .duration_since(UNIX_EPOCH)
9144        .unwrap_or_default()
9145        .as_millis();
9146    format!("rust-worker-{}-{millis}", std::process::id())
9147}
9148
9149fn percent_encode_path_segment(segment: &str) -> String {
9150    const HEX: &[u8; 16] = b"0123456789ABCDEF";
9151    let mut encoded = String::with_capacity(segment.len());
9152
9153    for byte in segment.bytes() {
9154        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
9155            encoded.push(char::from(byte));
9156        } else {
9157            encoded.push('%');
9158            encoded.push(char::from(HEX[(byte >> 4) as usize]));
9159            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
9160        }
9161    }
9162
9163    encoded
9164}
9165
9166fn unique_request_id(prefix: &str) -> String {
9167    let nanos = SystemTime::now()
9168        .duration_since(UNIX_EPOCH)
9169        .unwrap_or_default()
9170        .as_nanos();
9171    format!("{prefix}-{}-{nanos}", std::process::id())
9172}
9173
9174#[derive(Debug)]
9175struct QueryTaskExecutionFailure {
9176    reason: String,
9177    message: String,
9178    failure_type: String,
9179}
9180
9181impl QueryTaskExecutionFailure {
9182    fn new(
9183        reason: impl Into<String>,
9184        message: impl Into<String>,
9185        failure_type: impl Into<String>,
9186    ) -> Self {
9187        Self {
9188            reason: reason.into(),
9189            message: message.into(),
9190            failure_type: failure_type.into(),
9191        }
9192    }
9193}
9194
9195/// Typed local state owned by one deterministic workflow invocation.
9196///
9197/// Use [`WorkflowInstance::update`] for the same state transitions during
9198/// ordinary execution and replay. A replayed query receives a detached
9199/// immutable `Arc<S>` rather than this mutation-capable handle.
9200#[derive(Clone, Debug)]
9201pub struct WorkflowInstance<S> {
9202    state: Arc<Mutex<S>>,
9203}
9204
9205impl<S> WorkflowInstance<S> {
9206    fn new(state: S) -> Self {
9207        Self {
9208            state: Arc::new(Mutex::new(state)),
9209        }
9210    }
9211
9212    /// Read the current workflow-instance state without changing it.
9213    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
9214        let state = self
9215            .state
9216            .lock()
9217            .map_err(|_| Error::WorkflowStatePoisoned)?;
9218        Ok(reader(&state))
9219    }
9220
9221    /// Apply one deterministic workflow-instance state transition.
9222    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
9223        let mut state = self
9224            .state
9225            .lock()
9226            .map_err(|_| Error::WorkflowStatePoisoned)?;
9227        Ok(transition(&mut state))
9228    }
9229}
9230
9231impl<S: Clone> WorkflowInstance<S> {
9232    fn snapshot(&self) -> Result<S> {
9233        self.read(Clone::clone)
9234    }
9235}
9236
9237#[derive(Clone, Debug, PartialEq)]
9238pub struct MessageStreamMessage {
9239    pub stream_name: String,
9240    pub message_id: String,
9241    pub position: u64,
9242    pub arguments: Vec<AvroValue>,
9243}
9244
9245#[derive(Clone, Debug)]
9246pub struct MessageStream {
9247    ctx: WorkflowContext,
9248    name: String,
9249}
9250
9251impl MessageStream {
9252    /// Wait for one message, then return a bounded currently-available batch.
9253    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
9254        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
9255            return Err(Error::Codec(format!(
9256                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
9257            )));
9258        }
9259        loop {
9260            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
9261                return Ok(batch);
9262            }
9263
9264            self.ctx.record_message_stream_wait(&self.name)?;
9265            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
9266            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
9267            self.ctx.buffer_message_stream_delivery(arguments)?;
9268            if let Some(sequence) = replay_wait_sequence {
9269                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
9270            }
9271        }
9272    }
9273
9274    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
9275        self.receive(1)
9276            .await?
9277            .into_iter()
9278            .next()
9279            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
9280    }
9281}
9282
9283#[derive(Clone, Debug)]
9284pub struct WorkflowContext {
9285    state: Arc<Mutex<WorkflowState>>,
9286    cancellation_scope_id: String,
9287}
9288
9289fn valid_memo_key(key: &str) -> bool {
9290    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
9291
9292    !key.is_empty()
9293        && key.len() <= 64
9294        && (numeric_candidate.is_empty()
9295            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
9296        && key
9297            .bytes()
9298            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
9299}
9300
9301fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
9302    BASE64
9303        .decode(encode_avro_value(value)?.blob)
9304        .map(|bytes| bytes.len())
9305        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
9306}
9307
9308fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
9309    let AvroValue::Map(entries) = value else {
9310        return Err(Error::InvalidMemoUpdate(
9311            "entries must serialize to an Avro string-keyed map".to_string(),
9312        ));
9313    };
9314    if require_entries && entries.is_empty() {
9315        return Err(Error::InvalidMemoUpdate(
9316            "at least one entry is required".to_string(),
9317        ));
9318    }
9319    if entries.len() > MAX_MEMO_ENTRIES {
9320        return Err(Error::InvalidMemoUpdate(format!(
9321            "at most {MAX_MEMO_ENTRIES} entries are allowed"
9322        )));
9323    }
9324
9325    for (key, value) in &entries {
9326        if !valid_memo_key(&key) {
9327            return Err(Error::InvalidMemoUpdate(
9328                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
9329            ));
9330        }
9331        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
9332            return Err(Error::InvalidMemoUpdate(format!(
9333                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
9334            )));
9335        }
9336    }
9337
9338    let value = AvroValue::Map(entries);
9339    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
9340        return Err(Error::InvalidMemoUpdate(format!(
9341            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
9342        )));
9343    }
9344    Ok(value)
9345}
9346
9347fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
9348    let object = envelope.as_object().ok_or_else(|| {
9349        Error::InvalidMemoUpdate(
9350            "history field must use the public {codec, blob} payload envelope".to_string(),
9351        )
9352    })?;
9353    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
9354        return Err(Error::InvalidMemoUpdate(
9355            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
9356        ));
9357    }
9358
9359    canonical_memo_entries(
9360        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
9361        require_entries,
9362    )
9363}
9364
9365impl WorkflowContext {
9366    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
9367        let name = name.into();
9368        if name.is_empty()
9369            || name.len() > 128
9370            || !name.bytes().all(|byte| {
9371                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
9372            })
9373        {
9374            return Err(Error::Codec(
9375                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
9376                    .to_string(),
9377            ));
9378        }
9379        Ok(MessageStream {
9380            ctx: self.clone(),
9381            name,
9382        })
9383    }
9384
9385    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
9386        let mut state = self
9387            .state
9388            .lock()
9389            .map_err(|_| Error::WorkflowStatePoisoned)?;
9390        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9391        state
9392            .message_stream_waits
9393            .insert(name.to_string(), position);
9394        Ok(())
9395    }
9396
9397    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
9398        let mut state = self
9399            .state
9400            .lock()
9401            .map_err(|_| Error::WorkflowStatePoisoned)?;
9402        let cursor = state
9403            .message_stream_cursors
9404            .get(&message.stream_name)
9405            .copied()
9406            .unwrap_or(0);
9407        if message.position <= cursor {
9408            return Ok(());
9409        }
9410        let pending = state
9411            .message_stream_messages
9412            .entry(message.stream_name.clone())
9413            .or_default();
9414        if pending.iter().any(|candidate| {
9415            candidate.position == message.position || candidate.message_id == message.message_id
9416        }) {
9417            return Ok(());
9418        }
9419        pending.push(message);
9420        pending.sort_by_key(|candidate| candidate.position);
9421        Ok(())
9422    }
9423
9424    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
9425        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
9426            match delivery {
9427                MessageStreamDelivery::Message(message) => {
9428                    let stream_name = message.stream_name.clone();
9429                    self.buffer_message_stream(message)?;
9430                    return Ok(Some(stream_name));
9431                }
9432                MessageStreamDelivery::Cursor {
9433                    stream_name,
9434                    through_position,
9435                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
9436            }
9437        }
9438        Ok(None)
9439    }
9440
9441    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
9442        let state = self
9443            .state
9444            .lock()
9445            .map_err(|_| Error::WorkflowStatePoisoned)?;
9446        Ok(match state.recorded_commands.get(state.command_cursor) {
9447            Some(RecordedCommand::SignalWait {
9448                sequence,
9449                signal_name,
9450                ..
9451            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
9452            _ => None,
9453        })
9454    }
9455
9456    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
9457        let (history, payload_codec) = {
9458            let state = self
9459                .state
9460                .lock()
9461                .map_err(|_| Error::WorkflowStatePoisoned)?;
9462            (
9463                Arc::clone(&state.history_events),
9464                state.payload_codec.clone(),
9465            )
9466        };
9467
9468        let Some(opened_index) = history.iter().position(|event| {
9469            event.event_type == "SignalWaitOpened"
9470                && durable_event_sequence(event) == Some(wait_sequence)
9471                && event.payload.get("signal_name").and_then(Value::as_str)
9472                    == Some(MESSAGE_STREAM_SIGNAL)
9473        }) else {
9474            return Ok(());
9475        };
9476        let boundary_index = history
9477            .iter()
9478            .enumerate()
9479            .skip(opened_index + 1)
9480            .find_map(|(index, event)| {
9481                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
9482                    && is_authored_command_open_event(event))
9483                .then_some(index)
9484            })
9485            .unwrap_or(history.len());
9486
9487        for event in history[opened_index + 1..boundary_index]
9488            .iter()
9489            .filter(|event| {
9490                event.event_type == "SignalReceived"
9491                    && event.payload.get("signal_name").and_then(Value::as_str)
9492                        == Some(MESSAGE_STREAM_SIGNAL)
9493            })
9494        {
9495            let arguments = decode_signal_event_arguments(event, &payload_codec)?
9496                .into_iter()
9497                .map(AvroValue::into_json)
9498                .collect::<Result<Vec<_>>>()?;
9499            self.buffer_message_stream_delivery(arguments)?;
9500        }
9501        Ok(())
9502    }
9503
9504    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9505        let mut state = self
9506            .state
9507            .lock()
9508            .map_err(|_| Error::WorkflowStatePoisoned)?;
9509        let cursor = state
9510            .message_stream_cursors
9511            .entry(name.to_string())
9512            .or_default();
9513        *cursor = (*cursor).max(through_position);
9514        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9515            pending.retain(|message| message.position > through_position);
9516        }
9517        Ok(())
9518    }
9519
9520    fn take_message_stream_batch(
9521        &self,
9522        name: &str,
9523        max_items: usize,
9524    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9525        let mut state = self
9526            .state
9527            .lock()
9528            .map_err(|_| Error::WorkflowStatePoisoned)?;
9529        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9530        let pending = state
9531            .message_stream_messages
9532            .entry(name.to_string())
9533            .or_default();
9534        let count = contiguous_message_stream_count(pending, cursor, max_items);
9535        if count == 0 {
9536            return Ok(None);
9537        }
9538        let batch = pending.drain(..count).collect::<Vec<_>>();
9539        let position = batch.last().map(|message| message.position).unwrap_or(0);
9540        state
9541            .message_stream_cursors
9542            .insert(name.to_string(), position);
9543        state.message_stream_waits.remove(name);
9544        Ok(Some(batch))
9545    }
9546
9547    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9548        let state = self
9549            .state
9550            .lock()
9551            .map_err(|_| Error::WorkflowStatePoisoned)?;
9552        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9553        cursors.sort_by_key(|(name, _)| *name);
9554        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9555        waits.sort_by_key(|(name, _)| *name);
9556        Ok((
9557            cursors
9558                .into_iter()
9559                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9560                .collect(),
9561            waits
9562                .into_iter()
9563                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9564                .collect(),
9565        ))
9566    }
9567    /// Identity of the parent workflow currently being replayed.
9568    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9569        let state = self
9570            .state
9571            .lock()
9572            .map_err(|_| Error::WorkflowStatePoisoned)?;
9573        Ok(WorkflowIdentity {
9574            workflow_id: state.workflow_id.clone(),
9575            run_id: state.run_id.clone(),
9576        })
9577    }
9578
9579    /// Return the server-published history budget for this workflow task.
9580    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9581        let state = self
9582            .state
9583            .lock()
9584            .map_err(|_| Error::WorkflowStatePoisoned)?;
9585        Ok(state.history_budget.clone())
9586    }
9587
9588    /// Continue this workflow instance as a fresh run with replacement arguments.
9589    ///
9590    /// Return this value directly from the workflow handler. The worker converts
9591    /// it to the terminal protocol command only after replay has consumed every
9592    /// recorded durable command.
9593    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9594        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9595    }
9596
9597    /// Continue as new with optional workflow-type and task-queue overrides.
9598    pub fn continue_as_new_with_options<T: Serialize>(
9599        &self,
9600        options: ContinueAsNewOptions,
9601        args: T,
9602    ) -> Result<Value> {
9603        options.validate()?;
9604        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9605            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9606            options,
9607        }))
9608    }
9609
9610    pub fn activity<T: Serialize>(
9611        &self,
9612        activity_type: impl Into<String>,
9613        args: T,
9614    ) -> ActivityCall {
9615        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9616    }
9617
9618    pub fn activity_on_queue<T, Q>(
9619        &self,
9620        activity_type: impl Into<String>,
9621        task_queue: Option<Q>,
9622        args: T,
9623    ) -> ActivityCall
9624    where
9625        T: Serialize,
9626        Q: Into<String>,
9627    {
9628        let mut options = ActivityOptions::new();
9629        options.task_queue = task_queue.map(Into::into);
9630        self.activity_with_options(activity_type, options, args)
9631    }
9632
9633    /// Schedule one durable activity with retry, routing, and timeout options.
9634    ///
9635    /// Options are validated before the command is emitted. Once the command is
9636    /// recorded, replay consumes the same activity lifecycle at this command
9637    /// position and never emits a duplicate schedule.
9638    ///
9639    /// ```no_run
9640    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9641    /// # use std::time::Duration;
9642    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9643    /// let result = ctx
9644    ///     .activity_with_options(
9645    ///         "charge-card",
9646    ///         ActivityOptions::new()
9647    ///             .task_queue("payments")
9648    ///             .retry_policy(
9649    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9650    ///                     Duration::from_secs(1),
9651    ///                     2,
9652    ///                     Some(Duration::from_secs(30)),
9653    ///                 ),
9654    ///             )
9655    ///             .start_to_close_timeout(Duration::from_secs(60))
9656    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9657    ///             .heartbeat_timeout(Duration::from_secs(15)),
9658    ///         json!([{"order_id": "order-42"}]),
9659    ///     )
9660    ///     .await;
9661    /// match result {
9662    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9663    ///         "reason": failure.reason,
9664    ///         "timeout_kind": failure.timeout_kind,
9665    ///     })),
9666    ///     other => other,
9667    /// }
9668    /// # }
9669    /// ```
9670    pub fn activity_with_options<T: Serialize>(
9671        &self,
9672        activity_type: impl Into<String>,
9673        options: ActivityOptions,
9674        args: T,
9675    ) -> ActivityCall {
9676        ActivityCall {
9677            ctx: self.clone(),
9678            activity_type: activity_type.into(),
9679            options,
9680            worker_session: None,
9681            args: Some(AvroValue::from_serialize(&args)),
9682            scheduled: false,
9683            local: false,
9684            local_result: None,
9685            parallel_group_path: Vec::new(),
9686        }
9687    }
9688
9689    pub async fn activity_avro_value<T: Serialize>(
9690        &self,
9691        activity_type: impl Into<String>,
9692        args: T,
9693    ) -> Result<AvroValue> {
9694        let mut call = self.activity(activity_type, args);
9695        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9696    }
9697
9698    pub async fn activity_avro_value_with_options<T: Serialize>(
9699        &self,
9700        activity_type: impl Into<String>,
9701        options: ActivityOptions,
9702        args: T,
9703    ) -> Result<AvroValue> {
9704        let mut call = self.activity_with_options(activity_type, options, args);
9705        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9706    }
9707
9708    /// Schedule an activity with a Serde request and decode its Serde result.
9709    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
9710    where
9711        I: Serialize,
9712        O: DeserializeOwned,
9713    {
9714        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
9715            .await
9716    }
9717
9718    /// Schedule an activity with options and decode its result into `O`.
9719    ///
9720    /// Both directions use the fixed Avro Value codec. In particular, this
9721    /// method does not deserialize the JSON-safe inspection projection returned
9722    /// by the dynamic [`ActivityCall`] future.
9723    pub async fn activity_typed_with_options<I, O>(
9724        &self,
9725        activity_type: impl Into<String>,
9726        options: ActivityOptions,
9727        args: I,
9728    ) -> Result<O>
9729    where
9730        I: Serialize,
9731        O: DeserializeOwned,
9732    {
9733        let activity_type = activity_type.into();
9734        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
9735            handler_type_error::<I>(
9736                HandlerKind::Activity,
9737                &activity_type,
9738                HandlerValueKind::Input,
9739                error.to_string(),
9740            )
9741        });
9742        let mut call = ActivityCall {
9743            ctx: self.clone(),
9744            activity_type: activity_type.clone(),
9745            options,
9746            worker_session: None,
9747            args: Some(encoded),
9748            scheduled: false,
9749            local: false,
9750            local_result: None,
9751            parallel_group_path: Vec::new(),
9752        };
9753        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
9754        decode_handler_result(result, HandlerKind::Activity, &activity_type)
9755    }
9756
9757    /// Schedule and join a deterministic activity/child/timer group.
9758    ///
9759    /// Nested groups retain their input shape. Every durable leaf is scheduled
9760    /// before this future yields, results are assembled by declaration order,
9761    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
9762    /// declaration path, stable group metadata, and completed siblings.
9763    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9764        ParallelCall::new(self.clone(), operations)
9765    }
9766
9767    /// Alias for [`WorkflowContext::parallel`].
9768    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9769        self.parallel(operations)
9770    }
9771
9772    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
9773    pub async fn parallel_avro_value(
9774        &self,
9775        operations: Vec<ParallelOperation>,
9776    ) -> Result<Vec<ParallelAvroResult>> {
9777        let mut call = self.parallel(operations);
9778        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9779    }
9780
9781    /// Start every durable operation and resume from the one winner persisted
9782    /// by Server. Non-winning operations continue and remain addressable.
9783    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
9784        let operations = operations
9785            .into_iter()
9786            .enumerate()
9787            .map(|(index, operation)| (SelectionKey::Index(index), operation))
9788            .collect();
9789        SelectCall::new(self.clone(), operations)
9790    }
9791
9792    /// Named-key variant of [`WorkflowContext::select`].
9793    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
9794    where
9795        K: Into<SelectionKey>,
9796    {
9797        SelectCall::new(
9798            self.clone(),
9799            operations
9800                .into_iter()
9801                .map(|(key, operation)| (key.into(), operation))
9802                .collect(),
9803        )
9804    }
9805
9806    /// Create a workflow-local deterministic compensation registry.
9807    pub fn saga(&self) -> Saga {
9808        Saga::new(self.clone())
9809    }
9810
9811    /// Whether cancellation has reached this replay's authored boundary.
9812    ///
9813    /// Server's current `/cancel` route is terminal and does not set this flag.
9814    /// A canonical service request remains pending until its committed delivery
9815    /// is consumed. Request observation alone does not authorize an exception.
9816    pub fn is_cancellation_requested(&self) -> Result<bool> {
9817        let state = self
9818            .state
9819            .lock()
9820            .map_err(|_| Error::WorkflowStatePoisoned)?;
9821        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9822            return Ok(state
9823                .scope_delivery
9824                .as_ref()
9825                .unwrap()
9826                .contexts
9827                .contains_key(&self.cancellation_scope_id));
9828        }
9829        Ok(state.cancel_requested
9830            || state
9831                .scope_delivery
9832                .as_ref()
9833                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
9834    }
9835
9836    /// Raise a typed cooperative cancellation at an author-controlled point.
9837    ///
9838    /// Passing this result to [`Saga::finish`] compensates already registered
9839    /// forward steps before the cancellation remains the initiating outcome.
9840    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
9841        let mut state = self
9842            .state
9843            .lock()
9844            .map_err(|_| Error::WorkflowStatePoisoned)?;
9845        if state.cancellation_shield_depth == 0 {
9846            if let Some(replay) = &state.scope_delivery {
9847                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
9848                    let delivered = replay
9849                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
9850                        .ok_or_else(|| {
9851                            Error::InvalidCooperativeCancellation(
9852                                "scoped request lacks its consumed original delivery".into(),
9853                            )
9854                        })?;
9855                    return Err(Error::CancellationScopeRequested(
9856                        CancellationScopeRequested {
9857                            context: context
9858                                .clone()
9859                                .with_replay(Some(Arc::downgrade(&self.state))),
9860                            delivery: delivered.boundary.clone(),
9861                        },
9862                    ));
9863                }
9864            }
9865        }
9866        if state.cancel_requested && state.cancellation_shield_depth == 0 {
9867            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9868                return Ok(());
9869            }
9870            return Err(state.cancellation_error());
9871        }
9872        Ok(())
9873    }
9874
9875    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9876        SignalCall {
9877            ctx: self.clone(),
9878            signal_name: signal_name.into(),
9879            runtime_reserved_allowed: false,
9880            opened_wait: false,
9881            matched_pending: false,
9882            parallel_group_path: Vec::new(),
9883        }
9884    }
9885
9886    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9887        SignalCall {
9888            ctx: self.clone(),
9889            signal_name: signal_name.into(),
9890            runtime_reserved_allowed: true,
9891            opened_wait: false,
9892            matched_pending: false,
9893            parallel_group_path: Vec::new(),
9894        }
9895    }
9896
9897    pub async fn wait_signal_avro_value(
9898        &self,
9899        signal_name: impl Into<String>,
9900    ) -> Result<Vec<AvroValue>> {
9901        let mut call = self.wait_signal(signal_name);
9902        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9903    }
9904
9905    /// Return every committed signal argument list with the given name.
9906    ///
9907    /// This history-backed view is deterministic and is intended for
9908    /// condition predicates that must be re-evaluated after a signal while the
9909    /// workflow is blocked on [`WorkflowContext::wait_condition`].
9910    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
9911        self.signals_avro_value(signal_name)?
9912            .into_iter()
9913            .map(|arguments| {
9914                arguments
9915                    .into_iter()
9916                    .map(AvroValue::into_json)
9917                    .collect::<Result<Vec<_>>>()
9918            })
9919            .collect()
9920    }
9921
9922    /// Lossless fixed Avro Value view of committed signals with the given name.
9923    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9924        let state = self
9925            .state
9926            .lock()
9927            .map_err(|_| Error::WorkflowStatePoisoned)?;
9928        state
9929            .history_events
9930            .iter()
9931            .filter(|event| {
9932                event.event_type == "SignalReceived"
9933                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
9934            })
9935            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
9936            .collect()
9937    }
9938
9939    /// Return every committed update argument list with the given name.
9940    ///
9941    /// Accepted and applied records for the same update ID are de-duplicated.
9942    /// A Server task created after an update therefore replays the workflow and
9943    /// re-evaluates an open condition without application polling.
9944    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
9945        self.updates_avro_value(update_name)?
9946            .into_iter()
9947            .map(|arguments| {
9948                arguments
9949                    .into_iter()
9950                    .map(AvroValue::into_json)
9951                    .collect::<Result<Vec<_>>>()
9952            })
9953            .collect()
9954    }
9955
9956    /// Lossless fixed Avro Value view of committed updates with the given name.
9957    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9958        let state = self
9959            .state
9960            .lock()
9961            .map_err(|_| Error::WorkflowStatePoisoned)?;
9962        let mut seen = Vec::new();
9963        let mut updates = Vec::new();
9964        for event in state.history_events.iter() {
9965            if !matches!(
9966                event.event_type.as_str(),
9967                "UpdateAccepted" | "UpdateApplied"
9968            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
9969                || event.payload.get("arguments").is_none()
9970            {
9971                continue;
9972            }
9973            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
9974                if seen.iter().any(|recorded| recorded == update_id) {
9975                    continue;
9976                }
9977                seen.push(update_id.to_string());
9978            }
9979            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
9980        }
9981        Ok(updates)
9982    }
9983
9984    /// Wait for a deterministic predicate to become true or for its durable
9985    /// timeout to elapse.
9986    ///
9987    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
9988    /// predicate tokens automatically change the recorded definition
9989    /// fingerprint. Direct callers must provide an equally stable identity in
9990    /// [`ConditionWaitOptions`].
9991    pub fn wait_condition<F>(
9992        &self,
9993        options: ConditionWaitOptions,
9994        predicate: F,
9995    ) -> ConditionWaitCall
9996    where
9997        F: Fn() -> Result<bool> + Send + 'static,
9998    {
9999        ConditionWaitCall {
10000            ctx: self.clone(),
10001            options,
10002            predicate: Box::new(predicate),
10003            occurrence_id: None,
10004            opened_wait: false,
10005            parallel_group_path: Vec::new(),
10006        }
10007    }
10008
10009    /// Wait for server-backed durable time without blocking the worker executor.
10010    ///
10011    /// Polling this future emits one `start_timer` command and yields. The
10012    /// server records the deadline, so neither worker nor server restarts reset
10013    /// the wait. Replay resolves the future only from a `TimerScheduled` and
10014    /// `TimerFired` pair at the same position in the shared durable-command
10015    /// stream, with matching sequence, timer identity, and delay. Sub-second
10016    /// durations round up because protocol deadlines use whole seconds.
10017    ///
10018    /// ```no_run
10019    /// # use durable_workflow::{json, Client, Worker};
10020    /// # use std::time::Duration;
10021    /// # fn configure(client: Client) {
10022    /// let mut worker = Worker::new(client, "rust-workers");
10023    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
10024    ///     ctx.sleep(Duration::from_secs(5)).await?;
10025    ///     Ok(json!({"status": "timer fired"}))
10026    /// });
10027    /// # }
10028    /// ```
10029    pub fn sleep(&self, duration: Duration) -> TimerCall {
10030        let delay_seconds = duration
10031            .as_secs()
10032            .checked_add(u64::from(duration.subsec_nanos() > 0));
10033        TimerCall {
10034            ctx: self.clone(),
10035            delay_seconds,
10036            scheduled: false,
10037            matched_pending: false,
10038            parallel_group_path: Vec::new(),
10039        }
10040    }
10041
10042    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
10043    pub fn start_timer(&self, duration: Duration) -> TimerCall {
10044        self.sleep(duration)
10045    }
10046
10047    /// Evaluate a non-deterministic callback once and durably record its typed value.
10048    ///
10049    /// On replay the callback is not invoked: the value is decoded from the
10050    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
10051    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
10052    /// small values that must remain fixed for the lifetime of a workflow run.
10053    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
10054    where
10055        T: Serialize + DeserializeOwned,
10056        F: FnOnce() -> T,
10057    {
10058        {
10059            let mut state = self
10060                .state
10061                .lock()
10062                .map_err(|_| Error::WorkflowStatePoisoned)?;
10063            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10064                return match recorded {
10065                    RecordedCommand::SideEffect { sequence, value } => {
10066                        state.command_cursor += 1;
10067                        value.deserialize().map_err(|error| {
10068                            Error::NonDeterministicReplay(ReplayFailure::new(
10069                                "side_effect_type_mismatch",
10070                                Some(sequence),
10071                                Some(std::any::type_name::<T>().to_string()),
10072                                Some(error.to_string()),
10073                                "recorded side-effect value is incompatible with the requested Rust type",
10074                            ))
10075                        })
10076                    }
10077                    other => Err(command_mismatch(&other, "side effect")),
10078                };
10079            }
10080        }
10081
10082        let value = callback();
10083        let avro_value = AvroValue::from_serialize(&value)?;
10084        let mut state = self
10085            .state
10086            .lock()
10087            .map_err(|_| Error::WorkflowStatePoisoned)?;
10088        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
10089        state.commands.push(json!({
10090            "type": "record_side_effect",
10091            "result": result,
10092        }));
10093        Ok(value)
10094    }
10095
10096    /// Record or replay a lossless fixed Avro Value side effect.
10097    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
10098    where
10099        F: FnOnce() -> AvroValue,
10100    {
10101        {
10102            let mut state = self
10103                .state
10104                .lock()
10105                .map_err(|_| Error::WorkflowStatePoisoned)?;
10106            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10107                return match recorded {
10108                    RecordedCommand::SideEffect { value, .. } => {
10109                        state.command_cursor += 1;
10110                        Ok(value)
10111                    }
10112                    other => Err(command_mismatch(&other, "side effect")),
10113                };
10114            }
10115        }
10116
10117        let value = callback();
10118        let mut state = self
10119            .state
10120            .lock()
10121            .map_err(|_| Error::WorkflowStatePoisoned)?;
10122        let result = encode_typed_envelope(&value, &state.payload_codec)?;
10123        state.commands.push(json!({
10124            "type": "record_side_effect",
10125            "result": result,
10126        }));
10127        Ok(value)
10128    }
10129
10130    /// Append output items at a deterministic workflow command boundary.
10131    ///
10132    /// Stable idempotency keys are derived from the server-provided durable
10133    /// workflow command identity, command ordinal, and item index. Replay
10134    /// consumes the recorded side effect and never emits another append.
10135    pub fn append_workflow_stream(
10136        &self,
10137        stream_name: impl Into<String>,
10138        items: &[WorkflowStreamAppendItem],
10139        max_pending_items: Option<u64>,
10140    ) -> Result<()> {
10141        if items.is_empty() {
10142            return Err(Error::Codec(
10143                "workflow_stream_items_empty: append requires at least one item".to_string(),
10144            ));
10145        }
10146        if max_pending_items == Some(0) {
10147            return Err(Error::Codec(
10148                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
10149                    .to_string(),
10150            ));
10151        }
10152        let stream_name = stream_name.into();
10153        if stream_name.is_empty() {
10154            return Err(Error::Codec(
10155                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10156            ));
10157        }
10158
10159        let mut state = self
10160            .state
10161            .lock()
10162            .map_err(|_| Error::WorkflowStatePoisoned)?;
10163        let command_ordinal = state.workflow_stream_command_counter;
10164        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10165            state.workflow_stream_command_counter += 1;
10166            return match recorded {
10167                RecordedCommand::SideEffect { .. } => {
10168                    state.command_cursor += 1;
10169                    Ok(())
10170                }
10171                other => Err(command_mismatch(&other, "workflow stream append")),
10172            };
10173        }
10174
10175        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10176        state.workflow_stream_command_counter += 1;
10177        let wire_items = items
10178            .iter()
10179            .enumerate()
10180            .map(|(item_index, item)| {
10181                item.wire_value(Some(format!(
10182                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
10183                )))
10184            })
10185            .collect::<Vec<_>>();
10186        let mut directive = json!({
10187            "operation": "append",
10188            "stream_name": stream_name,
10189            "command_identity": identity,
10190            "command_ordinal": command_ordinal,
10191            "items": wire_items,
10192        });
10193        if let Some(max_pending_items) = max_pending_items {
10194            directive["max_pending_items"] = json!(max_pending_items);
10195        }
10196        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10197        state.commands.push(json!({
10198            "type": "record_side_effect",
10199            "result": result,
10200            "workflow_stream": directive,
10201        }));
10202        Ok(())
10203    }
10204
10205    /// Close a run-scoped output stream at a deterministic command boundary.
10206    pub fn close_workflow_stream(
10207        &self,
10208        stream_name: impl Into<String>,
10209        retention_seconds: Option<u64>,
10210    ) -> Result<()> {
10211        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
10212    }
10213
10214    /// Mark a run-scoped output stream errored at a deterministic command boundary.
10215    pub fn error_workflow_stream(
10216        &self,
10217        stream_name: impl Into<String>,
10218        error_reason: impl Into<String>,
10219        retention_seconds: Option<u64>,
10220    ) -> Result<()> {
10221        let error_reason = error_reason.into();
10222        if error_reason.is_empty() {
10223            return Err(Error::Codec(
10224                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
10225            ));
10226        }
10227        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
10228    }
10229
10230    fn finish_workflow_stream(
10231        &self,
10232        stream_name: String,
10233        error_reason: Option<String>,
10234        retention_seconds: Option<u64>,
10235    ) -> Result<()> {
10236        if stream_name.is_empty() {
10237            return Err(Error::Codec(
10238                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10239            ));
10240        }
10241        if retention_seconds == Some(0) {
10242            return Err(Error::Codec(
10243                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
10244            ));
10245        }
10246        let mut state = self
10247            .state
10248            .lock()
10249            .map_err(|_| Error::WorkflowStatePoisoned)?;
10250        let command_ordinal = state.workflow_stream_command_counter;
10251        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10252            state.workflow_stream_command_counter += 1;
10253            return match recorded {
10254                RecordedCommand::SideEffect { .. } => {
10255                    state.command_cursor += 1;
10256                    Ok(())
10257                }
10258                other => Err(command_mismatch(&other, "workflow stream close")),
10259            };
10260        }
10261        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10262        state.workflow_stream_command_counter += 1;
10263        let mut directive = json!({
10264            "operation": if error_reason.is_some() { "error" } else { "close" },
10265            "stream_name": stream_name,
10266            "command_identity": identity,
10267            "command_ordinal": command_ordinal,
10268        });
10269        if let Some(error_reason) = error_reason {
10270            directive["error_reason"] = json!(error_reason);
10271        }
10272        if let Some(retention_seconds) = retention_seconds {
10273            directive["retention_seconds"] = json!(retention_seconds);
10274        }
10275        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10276        state.commands.push(json!({
10277            "type": "record_side_effect",
10278            "result": result,
10279            "workflow_stream": directive,
10280        }));
10281        Ok(())
10282    }
10283
10284    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
10285        let identity = state.workflow_command_identity.as_str();
10286        if identity.is_empty() {
10287            return Err(Error::MissingWorkflowCommandIdentity);
10288        }
10289        Ok(identity)
10290    }
10291
10292    /// Validate, emit, or replay a typed workflow search-attribute update.
10293    ///
10294    /// The command is non-blocking within a workflow decision, but its
10295    /// `SearchAttributesUpserted` event occupies the same deterministic command
10296    /// stream as activities, timers, conditions, and other durable operations.
10297    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
10298        update.validate()?;
10299        let (attributes, attribute_types) = update.into_wire_parts();
10300        let mut state = self
10301            .state
10302            .lock()
10303            .map_err(|_| Error::WorkflowStatePoisoned)?;
10304
10305        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10306            return match recorded {
10307                RecordedCommand::SearchAttributes {
10308                    sequence,
10309                    attributes: recorded_attributes,
10310                    attribute_types: recorded_attribute_types,
10311                } => {
10312                    if recorded_attributes != attributes {
10313                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10314                            "search_attribute_value_mismatch",
10315                            Some(sequence),
10316                            Some(recorded_attributes.to_string()),
10317                            Some(attributes.to_string()),
10318                            "search-attribute values differ from the recorded durable command",
10319                        )));
10320                    }
10321                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
10322                        if recorded_types != attribute_types {
10323                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10324                                "search_attribute_type_mismatch",
10325                                Some(sequence),
10326                                Some(json!(recorded_types).to_string()),
10327                                Some(json!(attribute_types).to_string()),
10328                                "search-attribute declared types differ from the recorded durable command",
10329                            )));
10330                        }
10331                    }
10332                    state.command_cursor += 1;
10333                    Ok(())
10334                }
10335                other => Err(command_mismatch(&other, "search-attribute update")),
10336            };
10337        }
10338
10339        let mut command = serde_json::Map::from_iter([
10340            ("type".to_string(), json!("upsert_search_attributes")),
10341            ("attributes".to_string(), attributes),
10342        ]);
10343        if !attribute_types.is_empty() {
10344            command.insert("attribute_types".to_string(), json!(attribute_types));
10345        }
10346        state.commands.push(Value::Object(command));
10347        Ok(())
10348    }
10349
10350    /// Record a UUIDv4 once and return the same UUID on every replay.
10351    pub fn uuid_v4(&self) -> Result<Uuid> {
10352        self.side_effect(Uuid::new_v4)
10353    }
10354
10355    /// Select the newest supported version for a change, or replay the version
10356    /// already committed for that stable change ID.
10357    ///
10358    /// An unmarked old history that reached its next durable operation, or
10359    /// already completed, selects `-1` when that version is supported. This
10360    /// leaves the original operation available and writes no additional marker.
10361    /// Consistent markers written by older workers retain their original ordered
10362    /// positions. Repeated calls consume a matching marker at the current cursor.
10363    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
10364    pub fn get_version(
10365        &self,
10366        change_id: impl Into<String>,
10367        min_supported: i32,
10368        max_supported: i32,
10369    ) -> Result<i32> {
10370        let change_id = change_id.into();
10371        if change_id.trim().is_empty() {
10372            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10373                "version_change_id_invalid",
10374                None,
10375                Some("non-empty change ID".to_string()),
10376                Some(change_id),
10377                "version markers require a stable non-empty change ID",
10378            )));
10379        }
10380        if min_supported > max_supported {
10381            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10382                "version_range_invalid",
10383                None,
10384                Some("min_supported <= max_supported".to_string()),
10385                Some(format!("{min_supported}..={max_supported}")),
10386                "version marker supported range is invalid",
10387            )));
10388        }
10389
10390        let mut state = self
10391            .state
10392            .lock()
10393            .map_err(|_| Error::WorkflowStatePoisoned)?;
10394        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
10395            if let Some(RecordedCommand::VersionMarker {
10396                sequence: alias_sequence,
10397                change_id: alias_change_id,
10398                version: alias_version,
10399            }) = state.recorded_commands.get(state.command_cursor)
10400            {
10401                if alias_change_id == &change_id {
10402                    if *alias_version != version {
10403                        return Err(invalid_recorded_history(
10404                            "version_marker_conflict",
10405                            *alias_sequence,
10406                            &format!("selected version {version} for change ID {change_id:?}"),
10407                            &format!("recorded version {alias_version}"),
10408                            "recorded marker conflicts with the decision already selected during replay",
10409                        ));
10410                    }
10411                    ensure_version_supported(
10412                        &change_id,
10413                        version,
10414                        min_supported,
10415                        max_supported,
10416                        *alias_sequence,
10417                    )?;
10418                    // Older workers could record the same decision again. Keep
10419                    // each physical boundary without skipping intervening work.
10420                    state.command_cursor += 1;
10421                    return Ok(version);
10422                }
10423            }
10424            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
10425            return Ok(version);
10426        }
10427
10428        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10429            return match recorded {
10430                RecordedCommand::VersionMarker {
10431                    sequence,
10432                    change_id: recorded_change_id,
10433                    version,
10434                    ..
10435                } => {
10436                    if recorded_change_id != change_id {
10437                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10438                            "version_change_id_mismatch",
10439                            Some(sequence),
10440                            Some(recorded_change_id),
10441                            Some(change_id),
10442                            "recorded version marker change ID differs from current workflow code",
10443                        )));
10444                    }
10445                    ensure_version_supported(
10446                        &change_id,
10447                        version,
10448                        min_supported,
10449                        max_supported,
10450                        sequence,
10451                    )?;
10452                    state.command_cursor += 1;
10453                    state.version_markers.insert(change_id, (version, sequence));
10454                    Ok(version)
10455                }
10456                other => {
10457                    let version = -1;
10458                    let sequence = other.sequence();
10459                    ensure_version_supported(
10460                        &change_id,
10461                        version,
10462                        min_supported,
10463                        max_supported,
10464                        sequence,
10465                    )?;
10466                    // The existing operation proves this patch site was reached
10467                    // before its marker existed. Keep its original cursor.
10468                    state.version_markers.insert(change_id, (version, sequence));
10469                    Ok(version)
10470                }
10471            };
10472        }
10473
10474        if state
10475            .history_events
10476            .iter()
10477            .any(|event| event.event_type == "WorkflowCompleted")
10478        {
10479            let version = -1;
10480            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
10481            state.version_markers.insert(change_id, (version, 0));
10482            return Ok(version);
10483        }
10484
10485        let version = max_supported;
10486        state.commands.push(json!({
10487            "type": "record_version_marker",
10488            "change_id": change_id,
10489            "version": version,
10490            "min_supported": min_supported,
10491            "max_supported": max_supported,
10492        }));
10493        // Sequence numbers are assigned by the server. Zero identifies a marker
10494        // selected in this uncommitted decision batch for duplicate-call checks.
10495        state.version_markers.insert(change_id, (version, 0));
10496        Ok(version)
10497    }
10498
10499    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
10500    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
10501        Ok(self.get_version(change_id, -1, 1)? == 1)
10502    }
10503
10504    /// Keep a patch marker in history after the legacy branch has been removed.
10505    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
10506        self.get_version(change_id, -1, 1).map(|_| ())
10507    }
10508
10509    /// Merge non-indexed workflow memo metadata through durable history.
10510    ///
10511    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
10512    /// public Avro payload envelope consumed by Server and Cloud runtimes.
10513    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
10514        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
10515        let mut state = self
10516            .state
10517            .lock()
10518            .map_err(|_| Error::WorkflowStatePoisoned)?;
10519
10520        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10521            return match recorded {
10522                RecordedCommand::Memo {
10523                    sequence,
10524                    entries: recorded_entries,
10525                } => {
10526                    if recorded_entries != entries {
10527                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10528                            "memo_update_mismatch",
10529                            Some(sequence),
10530                            Some(format!("{recorded_entries:?}")),
10531                            Some(format!("{entries:?}")),
10532                            "recorded memo entries differ from the current workflow update",
10533                        )));
10534                    }
10535                    state.command_cursor += 1;
10536                    Ok(())
10537                }
10538                other => Err(command_mismatch(&other, "memo upsert")),
10539            };
10540        }
10541
10542        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
10543        state.commands.push(json!({
10544            "type": "upsert_memo",
10545            "entries": entries_envelope,
10546        }));
10547        Ok(())
10548    }
10549
10550    /// Start a named durable child on an explicit queue and await its result.
10551    ///
10552    /// The command is recorded in the parent's sequence-ordered durable command
10553    /// stream. Replay keeps a scheduled child pending without emitting another
10554    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
10555    /// values preserve the history payload codec and include both sides of the
10556    /// durable relationship; failures are returned as
10557    /// [`Error::ChildWorkflowFailed`].
10558    ///
10559    /// ```no_run
10560    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10561    /// # fn configure(client: Client) {
10562    /// let mut worker = Worker::new(client, "parent-workers");
10563    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10564    ///     let child = ctx
10565    ///         .start_child_workflow(
10566    ///             "fulfil-order",
10567    ///             ChildWorkflowOptions::new("fulfilment-workers")
10568    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10569    ///             json!([{"order_id": "order-42"}]),
10570    ///         )
10571    ///         .await?;
10572    ///     Ok(child.result)
10573    /// });
10574    /// # }
10575    /// ```
10576    pub fn start_child_workflow<T: Serialize>(
10577        &self,
10578        workflow_type: impl Into<String>,
10579        options: ChildWorkflowOptions,
10580        args: T,
10581    ) -> ChildWorkflowCall {
10582        ChildWorkflowCall {
10583            ctx: self.clone(),
10584            workflow_type: workflow_type.into(),
10585            options,
10586            args: Some(AvroValue::from_serialize(&args)),
10587            scheduled: false,
10588            matched_pending: false,
10589            parallel_group_path: Vec::new(),
10590        }
10591    }
10592
10593    pub async fn start_child_workflow_avro_value<T: Serialize>(
10594        &self,
10595        workflow_type: impl Into<String>,
10596        options: ChildWorkflowOptions,
10597        args: T,
10598    ) -> Result<ChildWorkflowAvroResult> {
10599        let mut call = self.start_child_workflow(workflow_type, options, args);
10600        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10601    }
10602
10603    fn take_commands(&self) -> Result<Vec<Value>> {
10604        let mut state = self
10605            .state
10606            .lock()
10607            .map_err(|_| Error::WorkflowStatePoisoned)?;
10608        Ok(std::mem::take(&mut state.commands))
10609    }
10610
10611    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10612        let mut state = self
10613            .state
10614            .lock()
10615            .map_err(|_| Error::WorkflowStatePoisoned)?;
10616
10617        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10618            return Err(command_mismatch(&recorded, "continue as new"));
10619        }
10620        if state.recorded_continue_as_new_sequence.is_some() {
10621            state.continue_as_new_consumed = true;
10622            return Ok(None);
10623        }
10624
10625        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10626        let mut command = serde_json::Map::from_iter([
10627            ("type".to_string(), json!("continue_as_new")),
10628            ("arguments".to_string(), arguments),
10629            ("queue".to_string(), json!(state.task_queue.clone())),
10630        ]);
10631        if let Some(workflow_type) = request.options.workflow_type {
10632            command.insert("workflow_type".to_string(), json!(workflow_type));
10633        }
10634        if let Some(task_queue) = request.options.task_queue {
10635            command.insert("queue".to_string(), json!(task_queue));
10636        }
10637        Ok(Some(Value::Object(command)))
10638    }
10639
10640    fn matched_recorded_pending(&self) -> Result<bool> {
10641        let state = self
10642            .state
10643            .lock()
10644            .map_err(|_| Error::WorkflowStatePoisoned)?;
10645        Ok(state.matched_recorded_pending)
10646    }
10647
10648    fn ensure_history_consumed(&self) -> Result<()> {
10649        let state = self
10650            .state
10651            .lock()
10652            .map_err(|_| Error::WorkflowStatePoisoned)?;
10653        if let Some(replay) = &state.scope_delivery {
10654            if let Some((&sequence, _)) = replay
10655                .canonical
10656                .deliveries
10657                .iter()
10658                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10659            {
10660                return Err(invalid_recorded_history(
10661                    "cancellation_scope_delivery_unconsumed",
10662                    sequence,
10663                    "original scoped delivery",
10664                    "workflow completion",
10665                    "workflow completed without consuming its committed scope delivery",
10666                ));
10667            }
10668        }
10669        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10670            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10671                "recorded_commands_unconsumed",
10672                Some(command.sequence()),
10673                Some(command.shape().to_string()),
10674                Some("workflow completion".to_string()),
10675                "workflow completed before consuming all recorded durable commands",
10676            )));
10677        }
10678        if let Some(delivery) = state
10679            .cancellation_history
10680            .delivery
10681            .as_ref()
10682            .filter(|_| !state.cancellation_consumed)
10683        {
10684            return Err(invalid_recorded_history(
10685                "cooperative_cancellation_unconsumed",
10686                delivery.sequence,
10687                "committed cancellation call",
10688                "workflow completion",
10689                "workflow completed without reaching its committed cancellation boundary",
10690            ));
10691        }
10692        if let Some(sequence) = state
10693            .recorded_continue_as_new_sequence
10694            .filter(|_| !state.continue_as_new_consumed)
10695        {
10696            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10697                "recorded_continue_as_new_unconsumed",
10698                Some(sequence),
10699                Some("continue as new".to_string()),
10700                Some("workflow completion".to_string()),
10701                "workflow completed without consuming its recorded continue-as-new transition",
10702            )));
10703        }
10704        Ok(())
10705    }
10706}
10707
10708fn contiguous_message_stream_count(
10709    pending: &[MessageStreamMessage],
10710    cursor: u64,
10711    max_items: usize,
10712) -> usize {
10713    pending
10714        .iter()
10715        .take(max_items)
10716        .enumerate()
10717        .take_while(|(offset, message)| {
10718            u64::try_from(*offset)
10719                .ok()
10720                .and_then(|offset| cursor.checked_add(offset + 1))
10721                == Some(message.position)
10722        })
10723        .count()
10724}
10725
10726fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
10727    matches!(
10728        event.event_type.as_str(),
10729        "ActivityScheduled"
10730            | "TimerScheduled"
10731            | "ChildWorkflowScheduled"
10732            | "SignalWaitOpened"
10733            | "ConditionWaitOpened"
10734            | "SearchAttributesUpserted"
10735            | "SideEffectRecorded"
10736            | "VersionMarkerRecorded"
10737            | "MemoUpserted"
10738            | "WorkflowContinuedAsNew"
10739    )
10740}
10741
10742#[derive(Debug)]
10743struct WorkflowState {
10744    workflow_id: Option<String>,
10745    run_id: Option<String>,
10746    task_queue: String,
10747    payload_codec: String,
10748    history_events: Arc<Vec<HistoryEvent>>,
10749    history_budget: WorkflowHistoryBudget,
10750    cancel_requested: bool,
10751    cancellation_history: CancellationHistory,
10752    cancellation_consumed: bool,
10753    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
10754    cancellation_shield_depth: u64,
10755    cancellation_delivery_enabled: bool,
10756    cancellation_delivery_intent: Option<CancellationDelivery>,
10757    cancellation_delivery_command_count: usize,
10758    allow_cancellation_scope_authoring: bool,
10759    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
10760    cancellation_scope_memberships: BTreeMap<u64, String>,
10761    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
10762    resume_signal: Option<ResumeSignal>,
10763    recorded_commands: Vec<RecordedCommand>,
10764    selection_markers: Vec<SelectionMarker>,
10765    selection_marker_cursor: usize,
10766    cancelled_selection_members: Vec<SelectionCancellation>,
10767    recorded_continue_as_new_sequence: Option<u64>,
10768    continue_as_new_consumed: bool,
10769    command_cursor: usize,
10770    condition_wait_occurrence_counter: u64,
10771    matched_recorded_pending: bool,
10772    version_markers: HashMap<String, (i32, u64)>,
10773    workflow_command_identity: String,
10774    workflow_stream_command_counter: u64,
10775    commands: Vec<Value>,
10776    local_activity_requests: Vec<local_activity::Request>,
10777    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
10778    message_stream_cursors: HashMap<String, u64>,
10779    message_stream_waits: HashMap<String, u64>,
10780}
10781
10782impl WorkflowState {
10783    #[cfg(test)]
10784    fn new(
10785        history: Vec<HistoryEvent>,
10786        task_queue: String,
10787        payload_codec: String,
10788        resume_signal: Option<ResumeSignal>,
10789    ) -> Result<Self> {
10790        Self::new_with_identity(
10791            history,
10792            None,
10793            None,
10794            task_queue,
10795            payload_codec,
10796            resume_signal,
10797        )
10798    }
10799
10800    fn new_with_identity(
10801        history: Vec<HistoryEvent>,
10802        workflow_id: Option<String>,
10803        run_id: Option<String>,
10804        task_queue: String,
10805        payload_codec: String,
10806        resume_signal: Option<ResumeSignal>,
10807    ) -> Result<Self> {
10808        Self::new_with_identity_and_scopes(
10809            history,
10810            workflow_id,
10811            run_id,
10812            task_queue,
10813            payload_codec,
10814            resume_signal,
10815            false,
10816        )
10817    }
10818
10819    fn new_with_identity_and_scopes(
10820        history: Vec<HistoryEvent>,
10821        workflow_id: Option<String>,
10822        run_id: Option<String>,
10823        task_queue: String,
10824        payload_codec: String,
10825        resume_signal: Option<ResumeSignal>,
10826        allow_cancellation_scope_authoring: bool,
10827    ) -> Result<Self> {
10828        Self::new_with_identity_and_scope_delivery(
10829            history,
10830            workflow_id,
10831            run_id,
10832            task_queue,
10833            payload_codec,
10834            resume_signal,
10835            allow_cancellation_scope_authoring,
10836            false,
10837        )
10838    }
10839
10840    fn new_with_identity_and_scope_delivery(
10841        history: Vec<HistoryEvent>,
10842        workflow_id: Option<String>,
10843        run_id: Option<String>,
10844        task_queue: String,
10845        payload_codec: String,
10846        resume_signal: Option<ResumeSignal>,
10847        allow_cancellation_scope_authoring: bool,
10848        allow_cancellation_scope_delivery: bool,
10849    ) -> Result<Self> {
10850        cooperative_cancellation::assert_cancellation_scope_replay_supported(
10851            &history,
10852            allow_cancellation_scope_authoring,
10853            allow_cancellation_scope_delivery,
10854        )?;
10855        let scopes = if allow_cancellation_scope_authoring {
10856            cancellation_scope::CancellationScopeHistory::read(
10857                &history,
10858                run_id.as_deref().unwrap_or_default(),
10859            )?
10860        } else {
10861            cancellation_scope::CancellationScopeHistory::default()
10862        };
10863        let cancellation_history = CancellationHistory::from_events(
10864            &history,
10865            run_id.as_deref().unwrap_or_default(),
10866            None,
10867        )?;
10868        if allow_cancellation_scope_authoring
10869            && cancellation_history.request.is_some()
10870            && !allow_cancellation_scope_delivery
10871        {
10872            return Err(Error::CancellationScopeExecutionUnavailable);
10873        }
10874        let scope_delivery = if allow_cancellation_scope_delivery {
10875            Some(cancellation_scope_replay::ScopeReplay::read(
10876                &history,
10877                &scopes,
10878                run_id.as_deref().unwrap_or_default(),
10879                workflow_id.as_deref().unwrap_or_default(),
10880            )?)
10881        } else {
10882            None
10883        };
10884        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
10885            &history,
10886            &payload_codec,
10887            WorkflowIdentity {
10888                workflow_id: workflow_id.clone(),
10889                run_id: run_id.clone(),
10890            },
10891        )?)?;
10892        for (sequence, opening) in &scopes.openings {
10893            if recorded_commands
10894                .iter()
10895                .any(|command| command.sequence() == *sequence)
10896            {
10897                return Err(invalid_recorded_history(
10898                    "invalid_cancellation_scope_history",
10899                    *sequence,
10900                    "distinct authored scope opening",
10901                    "operation collision",
10902                    "scope opening collides with a command",
10903                ));
10904            }
10905            recorded_commands.push(RecordedCommand::CancellationScope {
10906                sequence: *sequence,
10907                scope_id: opening.scope_id.clone(),
10908                parent_scope_id: opening.parent_scope_id.clone(),
10909                shield_parent: opening.shield_parent,
10910            });
10911        }
10912        recorded_commands.sort_by_key(RecordedCommand::sequence);
10913        if let Some(replay) = &scope_delivery {
10914            replay.bind_commands(&mut recorded_commands)?;
10915        }
10916        let selection_markers = recorded_selection_markers(&history)?;
10917        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
10918        let recorded_continue_as_new = history
10919            .iter()
10920            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
10921            .collect::<Vec<_>>();
10922        if recorded_continue_as_new.len() > 1 {
10923            return Err(invalid_recorded_history(
10924                "duplicate_continue_as_new_transition",
10925                recorded_continue_as_new
10926                    .last()
10927                    .and_then(|event| durable_event_sequence(event))
10928                    .unwrap_or(0),
10929                "one WorkflowContinuedAsNew event",
10930                &format!(
10931                    "{} WorkflowContinuedAsNew events",
10932                    recorded_continue_as_new.len()
10933                ),
10934                "workflow history records one continue-as-new transition more than once",
10935            ));
10936        }
10937        let recorded_continue_as_new_sequence = recorded_continue_as_new
10938            .first()
10939            .map(|event| {
10940                durable_event_sequence(event).ok_or_else(|| {
10941                    Error::NonDeterministicReplay(ReplayFailure::new(
10942                        "continue_as_new_sequence_missing",
10943                        None,
10944                        Some("recorded transition sequence".to_string()),
10945                        Some("missing sequence".to_string()),
10946                        "WorkflowContinuedAsNew history is missing its recorded sequence",
10947                    ))
10948                })
10949            })
10950            .transpose()?;
10951        let mut message_stream_cursors = HashMap::new();
10952        for event in &history {
10953            if !matches!(
10954                event.event_type.as_str(),
10955                "SignalReceived" | "SignalApplied"
10956            ) || event.payload.get("signal_name").and_then(Value::as_str)
10957                != Some(MESSAGE_STREAM_SIGNAL)
10958            {
10959                continue;
10960            }
10961            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
10962            if arguments.len() != 1 {
10963                continue;
10964            }
10965            let envelope = arguments[0].clone().into_json()?;
10966            let Some(envelope) = envelope.as_object() else {
10967                continue;
10968            };
10969            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
10970            {
10971                continue;
10972            }
10973            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
10974                continue;
10975            };
10976            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
10977            else {
10978                continue;
10979            };
10980            let cursor = message_stream_cursors
10981                .entry(stream_name.to_string())
10982                .or_insert(0);
10983            *cursor = (*cursor).max(through_position);
10984        }
10985        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
10986        let cancel_requested = history.iter().any(|event| {
10987            matches!(
10988                event.event_type.as_str(),
10989                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
10990            )
10991        });
10992        let cancellation_clock = cancellation_history
10993            .request
10994            .as_ref()
10995            .and_then(|request| request.context.as_ref())
10996            .map(|_| {
10997                cancellation_replay_clock::ReplayClock::new(
10998                    &history,
10999                    &recorded_commands,
11000                    cancellation_history.delivery_index,
11001                )
11002            })
11003            .or_else(|| {
11004                scope_delivery.as_ref().map(|_| {
11005                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
11006                })
11007            });
11008        Ok(Self {
11009            workflow_command_identity: String::new(),
11010            workflow_stream_command_counter: 0,
11011            workflow_id,
11012            run_id,
11013            task_queue,
11014            payload_codec,
11015            history_events: Arc::new(history),
11016            history_budget: WorkflowHistoryBudget {
11017                event_count,
11018                ..WorkflowHistoryBudget::default()
11019            },
11020            cancel_requested,
11021            cancellation_history,
11022            cancellation_consumed: false,
11023            cancellation_clock,
11024            cancellation_shield_depth: 0,
11025            cancellation_delivery_enabled: false,
11026            cancellation_delivery_intent: None,
11027            cancellation_delivery_command_count: 0,
11028            allow_cancellation_scope_authoring,
11029            cancellation_scope_opening: None,
11030            cancellation_scope_memberships: scopes.memberships,
11031            scope_delivery,
11032            resume_signal,
11033            recorded_commands,
11034            selection_markers,
11035            selection_marker_cursor: 0,
11036            cancelled_selection_members,
11037            recorded_continue_as_new_sequence,
11038            continue_as_new_consumed: false,
11039            command_cursor: 0,
11040            condition_wait_occurrence_counter: 0,
11041            matched_recorded_pending: false,
11042            version_markers: HashMap::new(),
11043            commands: Vec::new(),
11044            local_activity_requests: Vec::new(),
11045            message_stream_messages: HashMap::new(),
11046            message_stream_cursors,
11047            message_stream_waits: HashMap::new(),
11048        })
11049    }
11050}
11051
11052enum MessageStreamDelivery {
11053    Message(MessageStreamMessage),
11054    Cursor {
11055        stream_name: String,
11056        through_position: u64,
11057    },
11058}
11059
11060fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
11061    if arguments.len() != 1 {
11062        return Ok(None);
11063    }
11064    let envelope = arguments
11065        .into_iter()
11066        .next()
11067        .expect("one argument was checked");
11068    let Some(envelope) = envelope.as_object() else {
11069        return Ok(None);
11070    };
11071    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11072        return Ok(None);
11073    };
11074    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
11075        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11076        else {
11077            return Ok(None);
11078        };
11079        return Ok(Some(MessageStreamDelivery::Cursor {
11080            stream_name: stream_name.to_string(),
11081            through_position,
11082        }));
11083    }
11084    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
11085        return Ok(None);
11086    }
11087    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
11088        return Ok(None);
11089    };
11090    let Some(position) = envelope
11091        .get("position")
11092        .and_then(Value::as_u64)
11093        .filter(|value| *value > 0)
11094    else {
11095        return Ok(None);
11096    };
11097    let Some(payload_envelope) = envelope.get("payload_envelope") else {
11098        return Ok(None);
11099    };
11100    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
11101    else {
11102        return Ok(None);
11103    };
11104    let decoded = decode_avro_value(&payload_envelope)?;
11105    let AvroValue::Array(values) = decoded else {
11106        return Ok(None);
11107    };
11108    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
11109        stream_name: stream_name.to_string(),
11110        message_id: message_id.to_string(),
11111        position,
11112        arguments: values,
11113    })))
11114}
11115
11116#[derive(Clone, Debug)]
11117enum RecordedCommand {
11118    CancellationScope {
11119        sequence: u64,
11120        scope_id: String,
11121        parent_scope_id: String,
11122        shield_parent: bool,
11123    },
11124    CancellationGroup {
11125        sequence: u64,
11126        span: u64,
11127        original: Vec<RecordedCommand>,
11128    },
11129    CancellationBoundary {
11130        sequence: u64,
11131        call_kind: CancellationCallKind,
11132        original: Option<Box<RecordedCommand>>,
11133    },
11134    Activity {
11135        sequence: u64,
11136        activity_type: Option<String>,
11137        cancellation_policy: String,
11138        options: Option<RecordedActivityOptions>,
11139        outcome: Option<ActivityOutcome>,
11140        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11141    },
11142    Timer {
11143        sequence: u64,
11144        delay_seconds: u64,
11145        fired: bool,
11146        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11147    },
11148    ChildWorkflow {
11149        sequence: u64,
11150        workflow_type: Option<String>,
11151        policies: RecordedChildPolicies,
11152        outcome: Option<ChildWorkflowOutcome>,
11153        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11154    },
11155    SignalWait {
11156        sequence: u64,
11157        signal_name: String,
11158        value: Option<Vec<AvroValue>>,
11159        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11160    },
11161    ConditionWait {
11162        sequence: u64,
11163        occurrence_id: String,
11164        condition_key: Option<String>,
11165        predicate_identity: String,
11166        timeout_seconds: Option<u64>,
11167        result: Option<ConditionWaitResult>,
11168        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11169    },
11170    SearchAttributes {
11171        sequence: u64,
11172        attributes: Value,
11173        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
11174    },
11175    SideEffect {
11176        sequence: u64,
11177        value: AvroValue,
11178    },
11179    VersionMarker {
11180        sequence: u64,
11181        change_id: String,
11182        version: i32,
11183    },
11184    Memo {
11185        sequence: u64,
11186        entries: AvroValue,
11187    },
11188}
11189
11190#[derive(Clone, Debug, PartialEq, Eq)]
11191struct SelectionMarker {
11192    selection_group_id: String,
11193    selection_group_base_sequence: u64,
11194    selection_group_size: usize,
11195    member_key: SelectionKey,
11196    member_index: usize,
11197    member_base_sequence: u64,
11198    member_size: usize,
11199    operation_kind: String,
11200    operation_identity: String,
11201    outcome: String,
11202    resolution_event_id: String,
11203    resolution_event_type: String,
11204}
11205
11206#[derive(Clone, Debug, PartialEq, Eq)]
11207struct SelectionCancellation {
11208    selection_group_id: String,
11209    member_key: SelectionKey,
11210    member_index: usize,
11211    member_base_sequence: u64,
11212    member_size: usize,
11213    operation_kind: String,
11214    operation_identity: String,
11215}
11216
11217fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
11218    let mut markers: Vec<SelectionMarker> = Vec::new();
11219    for event in events
11220        .iter()
11221        .filter(|event| event.event_type == "SelectionResolved")
11222    {
11223        let payload = &event.payload;
11224        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
11225        let group_size = required_selection_usize(payload, "selection_group_size")?;
11226        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
11227        let member_size = required_selection_usize(payload, "member_size")?;
11228        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
11229        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
11230            invalid_recorded_history(
11231                "selection_marker_invalid",
11232                base_sequence,
11233                "non-empty selection_group_id",
11234                &payload.to_string(),
11235                "selection winner history is missing its durable group identity",
11236            )
11237        })?;
11238        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
11239        if group_id != expected_group_id {
11240            return Err(invalid_recorded_history(
11241                "selection_marker_invalid",
11242                base_sequence,
11243                &expected_group_id,
11244                &group_id,
11245                "selection winner history contains an incompatible group identity",
11246            ));
11247        }
11248        let group_end = base_sequence
11249            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
11250            .unwrap_or(u64::MAX);
11251        let member_end = member_base_sequence
11252            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
11253            .unwrap_or(u64::MAX);
11254        if member_index >= group_size
11255            || member_base_sequence < base_sequence
11256            || member_end > group_end
11257        {
11258            return Err(invalid_recorded_history(
11259                "selection_marker_invalid",
11260                base_sequence,
11261                "winner member within selection group bounds",
11262                &payload.to_string(),
11263                "selection winner history contains an invalid member range",
11264            ));
11265        }
11266        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
11267            invalid_recorded_history(
11268                "selection_marker_invalid",
11269                base_sequence,
11270                "selection operation kind",
11271                &payload.to_string(),
11272                "selection winner history is missing its operation kind",
11273            )
11274        })?;
11275        if !matches!(
11276            operation_kind.as_str(),
11277            "activity" | "child" | "timer" | "signal" | "condition" | "group"
11278        ) {
11279            return Err(invalid_recorded_history(
11280                "selection_marker_invalid",
11281                base_sequence,
11282                "activity, child, timer, signal, condition, or group",
11283                &operation_kind,
11284                "selection winner history contains an unsupported operation kind",
11285            ));
11286        }
11287        let operation_identity =
11288            payload_string(payload, "operation_identity").ok_or_else(|| {
11289                invalid_recorded_history(
11290                    "selection_marker_invalid",
11291                    base_sequence,
11292                    "non-empty operation identity",
11293                    &payload.to_string(),
11294                    "selection winner history is missing its durable operation identity",
11295                )
11296            })?;
11297        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
11298            invalid_recorded_history(
11299                "selection_marker_invalid",
11300                base_sequence,
11301                "completed or failed selection outcome",
11302                &payload.to_string(),
11303                "selection winner history is missing its outcome",
11304            )
11305        })?;
11306        if !matches!(outcome.as_str(), "completed" | "failed") {
11307            return Err(invalid_recorded_history(
11308                "selection_marker_invalid",
11309                base_sequence,
11310                "completed or failed selection outcome",
11311                &outcome,
11312                "selection winner history contains an unsupported outcome",
11313            ));
11314        }
11315        let marker = SelectionMarker {
11316            selection_group_id: group_id,
11317            selection_group_base_sequence: base_sequence,
11318            selection_group_size: group_size,
11319            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
11320            member_index,
11321            member_base_sequence,
11322            member_size,
11323            operation_kind,
11324            operation_identity,
11325            outcome,
11326            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
11327                || {
11328                    invalid_recorded_history(
11329                        "selection_marker_invalid",
11330                        base_sequence,
11331                        "durable resolution_event_id",
11332                        &payload.to_string(),
11333                        "selection winner history is missing its terminal event identity",
11334                    )
11335                },
11336            )?,
11337            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
11338                || {
11339                    invalid_recorded_history(
11340                        "selection_marker_invalid",
11341                        base_sequence,
11342                        "durable resolution_event_type",
11343                        &payload.to_string(),
11344                        "selection winner history is missing its terminal event type",
11345                    )
11346                },
11347            )?,
11348        };
11349        if let Some(existing) = markers
11350            .iter()
11351            .find(|existing| existing.selection_group_id == marker.selection_group_id)
11352        {
11353            if existing != &marker {
11354                return Err(invalid_recorded_history(
11355                    "selection_marker_conflict",
11356                    base_sequence,
11357                    &format!("one winner for {}", marker.selection_group_id),
11358                    &payload.to_string(),
11359                    "selection history records conflicting winners for one durable group",
11360                ));
11361            }
11362            continue;
11363        }
11364        markers.push(marker);
11365    }
11366    Ok(markers)
11367}
11368
11369fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
11370    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
11371    for event in events
11372        .iter()
11373        .filter(|event| event.event_type == "SelectionOperationCancelled")
11374    {
11375        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
11376            invalid_recorded_history(
11377                "selection_cancellation_invalid",
11378                0,
11379                "non-empty selection_group_id",
11380                &event.payload.to_string(),
11381                "selection cancellation history is missing its group identity",
11382            )
11383        })?;
11384        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
11385        let marker = SelectionCancellation {
11386            selection_group_id: group_id,
11387            member_key: selection_key_from_value(
11388                event.payload.get("member_key"),
11389                member_base_sequence,
11390            )?,
11391            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
11392            member_base_sequence,
11393            member_size: required_selection_usize(&event.payload, "member_size")?,
11394            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
11395                invalid_recorded_history(
11396                    "selection_cancellation_invalid",
11397                    member_base_sequence,
11398                    "selection operation kind",
11399                    &event.payload.to_string(),
11400                    "selection cancellation is missing its operation kind",
11401                )
11402            })?,
11403            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
11404                || {
11405                    invalid_recorded_history(
11406                        "selection_cancellation_invalid",
11407                        member_base_sequence,
11408                        "selection operation identity",
11409                        &event.payload.to_string(),
11410                        "selection cancellation is missing its operation identity",
11411                    )
11412                },
11413            )?,
11414        };
11415        if let Some(existing) = cancelled.iter().find(|recorded| {
11416            recorded.selection_group_id == marker.selection_group_id
11417                && recorded.member_base_sequence == marker.member_base_sequence
11418        }) {
11419            if existing != &marker {
11420                return Err(invalid_recorded_history(
11421                    "selection_cancellation_conflict",
11422                    member_base_sequence,
11423                    "one stable SelectionOperationCancelled marker",
11424                    &event.payload.to_string(),
11425                    "selection cancellation history contains conflicting member metadata",
11426                ));
11427            }
11428        } else {
11429            cancelled.push(marker);
11430        }
11431    }
11432    Ok(cancelled)
11433}
11434
11435fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
11436    payload
11437        .get(field)
11438        .and_then(value_as_u64)
11439        .filter(|value| *value > 0)
11440        .ok_or_else(|| {
11441            invalid_recorded_history(
11442                "selection_marker_invalid",
11443                0,
11444                &format!("positive integer {field}"),
11445                &payload.to_string(),
11446                "selection history contains invalid durable identity metadata",
11447            )
11448        })
11449}
11450
11451fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
11452    required_selection_usize_allow_zero(payload, field).and_then(|value| {
11453        if value > 0 {
11454            Ok(value)
11455        } else {
11456            Err(invalid_recorded_history(
11457                "selection_marker_invalid",
11458                0,
11459                &format!("positive integer {field}"),
11460                &payload.to_string(),
11461                "selection history contains invalid durable identity metadata",
11462            ))
11463        }
11464    })
11465}
11466
11467fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
11468    payload
11469        .get(field)
11470        .and_then(value_as_u64)
11471        .and_then(|value| usize::try_from(value).ok())
11472        .ok_or_else(|| {
11473            invalid_recorded_history(
11474                "selection_marker_invalid",
11475                0,
11476                &format!("non-negative integer {field}"),
11477                &payload.to_string(),
11478                "selection history contains invalid durable identity metadata",
11479            )
11480        })
11481}
11482
11483#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11484struct RecordedActivityOptions {
11485    task_queue: RecordedSnapshotValue<Option<String>>,
11486    execution_mode: RecordedSnapshotValue<Option<String>>,
11487    retry_policy: ActivityRetrySnapshot,
11488    worker_session: Option<Value>,
11489}
11490
11491#[derive(Clone, Debug)]
11492struct RecordedChildPolicies {
11493    parent_close_policy: String,
11494    cancellation_policy: String,
11495}
11496
11497fn recorded_activity_cancellation_policy(
11498    events: &[&HistoryEvent],
11499    sequence: u64,
11500) -> Result<String> {
11501    let mut policy: Option<String> = None;
11502    for event in events.iter().filter(|event| {
11503        matches!(
11504            event.event_type.as_str(),
11505            "ActivityScheduled"
11506                | "ActivityStarted"
11507                | "ActivityCompleted"
11508                | "ActivityFailed"
11509                | "ActivityTimedOut"
11510                | "ActivityCancelled"
11511        )
11512    }) {
11513        for source in [Some(&event.payload), event.payload.get("activity")]
11514            .into_iter()
11515            .flatten()
11516        {
11517            let Some(value) = source.get("cancellation_policy") else {
11518                continue;
11519            };
11520            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
11521                value.as_str()
11522            else {
11523                return Err(invalid_recorded_history(
11524                    "invalid_activity_cancellation_policy_history",
11525                    sequence,
11526                    "supported Activity cancellation policy",
11527                    &value.to_string(),
11528                    "Activity history contains an invalid cancellation policy",
11529                ));
11530            };
11531            if let Some(previous) = policy.as_deref() {
11532                if previous != incoming {
11533                    return Err(invalid_recorded_history(
11534                        "activity_cancellation_policy_history_conflict",
11535                        sequence,
11536                        previous,
11537                        incoming,
11538                        "Activity cancellation policy changed between history events",
11539                    ));
11540                }
11541            }
11542            policy = Some(incoming.to_string());
11543        }
11544        policy.get_or_insert_with(|| "try_cancel".to_string());
11545    }
11546    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
11547}
11548
11549fn recorded_child_policy_value<'a>(
11550    payload: &'a Value,
11551    field: &str,
11552    sequence: u64,
11553) -> Result<Option<&'a str>> {
11554    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
11555        return Ok(None);
11556    };
11557    let valid = match (field, value.as_str()) {
11558        (
11559            "parent_close_policy",
11560            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11561        ) => true,
11562        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11563            true
11564        }
11565        _ => false,
11566    };
11567    if !valid {
11568        return Err(invalid_recorded_history(
11569            "invalid_child_workflow_policy_history",
11570            sequence,
11571            "supported child workflow policy",
11572            &value.to_string(),
11573            "child workflow history contains an invalid policy",
11574        ));
11575    }
11576    Ok(value.as_str())
11577}
11578
11579fn recorded_child_policies(
11580    events: &[&HistoryEvent],
11581    scheduled: &HistoryEvent,
11582    sequence: u64,
11583) -> Result<RecordedChildPolicies> {
11584    let parent_close_policy =
11585        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11586            .unwrap_or("abandon")
11587            .to_string();
11588    let cancellation_policy =
11589        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11590            .unwrap_or("abandon")
11591            .to_string();
11592    for event in events {
11593        for (field, expected) in [
11594            ("parent_close_policy", parent_close_policy.as_str()),
11595            ("cancellation_policy", cancellation_policy.as_str()),
11596        ] {
11597            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11598                if actual != expected {
11599                    return Err(invalid_recorded_history(
11600                        "child_workflow_policy_history_conflict",
11601                        sequence,
11602                        expected,
11603                        actual,
11604                        "child workflow policy changed between history events",
11605                    ));
11606                }
11607            }
11608        }
11609    }
11610    Ok(RecordedChildPolicies {
11611        parent_close_policy,
11612        cancellation_policy,
11613    })
11614}
11615
11616fn ensure_child_policies_match(
11617    sequence: u64,
11618    recorded: &RecordedChildPolicies,
11619    current: &ChildWorkflowOptions,
11620) -> Result<()> {
11621    for (field, expected, actual) in [
11622        (
11623            "parent_close_policy",
11624            recorded.parent_close_policy.as_str(),
11625            current.parent_close_policy.as_str(),
11626        ),
11627        (
11628            "cancellation_policy",
11629            recorded.cancellation_policy.as_str(),
11630            current.cancellation_policy.as_str(),
11631        ),
11632    ] {
11633        if expected != actual {
11634            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11635                "child_workflow_policy_changed",
11636                Some(sequence),
11637                Some(expected.to_string()),
11638                Some(actual.to_string()),
11639                format!("child workflow {field} changed during replay"),
11640            )));
11641        }
11642    }
11643    Ok(())
11644}
11645
11646#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11647enum RecordedSnapshotValue<T> {
11648    /// Older history did not persist this field, so it cannot constrain replay.
11649    Unknown,
11650    Known(T),
11651}
11652
11653impl<T: PartialEq> RecordedSnapshotValue<T> {
11654    fn matches_current(&self, current: &Self) -> bool {
11655        match self {
11656            Self::Unknown => true,
11657            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11658        }
11659    }
11660}
11661
11662#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11663struct ActivityRetrySnapshot {
11664    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11665    max_attempts: RecordedSnapshotValue<Option<u64>>,
11666    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11667    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11668    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11669    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11670    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11671    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11672}
11673
11674impl ActivityRetrySnapshot {
11675    fn matches_current(&self, current: &Self) -> bool {
11676        self.snapshot_version
11677            .matches_current(&current.snapshot_version)
11678            && self.max_attempts.matches_current(&current.max_attempts)
11679            && self
11680                .backoff_seconds
11681                .matches_current(&current.backoff_seconds)
11682            && self
11683                .start_to_close_timeout
11684                .matches_current(&current.start_to_close_timeout)
11685            && self
11686                .schedule_to_start_timeout
11687                .matches_current(&current.schedule_to_start_timeout)
11688            && self
11689                .schedule_to_close_timeout
11690                .matches_current(&current.schedule_to_close_timeout)
11691            && self
11692                .heartbeat_timeout
11693                .matches_current(&current.heartbeat_timeout)
11694            && self
11695                .non_retryable_error_types
11696                .matches_current(&current.non_retryable_error_types)
11697    }
11698}
11699
11700fn recorded_optional_u64(
11701    object: Option<&serde_json::Map<String, Value>>,
11702    field: &str,
11703) -> RecordedSnapshotValue<Option<u64>> {
11704    match object.and_then(|object| object.get(field)) {
11705        None => RecordedSnapshotValue::Unknown,
11706        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11707        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
11708    }
11709}
11710
11711fn recorded_optional_string(
11712    object: &serde_json::Map<String, Value>,
11713    field: &str,
11714) -> RecordedSnapshotValue<Option<String>> {
11715    match object.get(field) {
11716        None => RecordedSnapshotValue::Unknown,
11717        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11718        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
11719    }
11720}
11721
11722fn recorded_activity_execution_mode(
11723    events: &[&HistoryEvent],
11724    sequence: u64,
11725) -> Result<RecordedSnapshotValue<Option<String>>> {
11726    let mut recorded = RecordedSnapshotValue::Unknown;
11727    for event in events {
11728        for object in [
11729            event.payload.as_object(),
11730            event.payload.get("activity").and_then(Value::as_object),
11731        ]
11732        .into_iter()
11733        .flatten()
11734        {
11735            let mode = match object.get("execution_mode") {
11736                None => None,
11737                Some(Value::Null) => Some(None),
11738                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
11739                Some(_) => {
11740                    return Err(invalid_recorded_history(
11741                        "activity_execution_mode_invalid",
11742                        sequence,
11743                        "null or a non-empty execution mode",
11744                        "invalid execution_mode",
11745                        "activity history contains an invalid execution mode",
11746                    ))
11747                }
11748            };
11749            let legacy_mode = match object.get("local_activity") {
11750                None => None,
11751                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
11752                Some(_) => {
11753                    return Err(invalid_recorded_history(
11754                        "activity_execution_mode_invalid",
11755                        sequence,
11756                        "boolean local_activity",
11757                        "invalid local_activity",
11758                        "activity history contains an invalid local-activity marker",
11759                    ))
11760                }
11761            };
11762            for mode in [mode, legacy_mode].into_iter().flatten() {
11763                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
11764                {
11765                    return Err(invalid_recorded_history(
11766                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
11767                        "activity lifecycle events at one workflow sequence disagree on execution mode",
11768                    ));
11769                }
11770                recorded = RecordedSnapshotValue::Known(mode);
11771            }
11772        }
11773    }
11774    Ok(recorded)
11775}
11776
11777fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
11778    let policy = policy.and_then(Value::as_object);
11779    let backoff_seconds = policy
11780        .and_then(|policy| policy.get("backoff_seconds"))
11781        .and_then(Value::as_array)
11782        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11783        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
11784    let mut non_retryable_error_types = Vec::new();
11785    for error_type in policy
11786        .and_then(|policy| policy.get("non_retryable_error_types"))
11787        .and_then(Value::as_array)
11788        .into_iter()
11789        .flatten()
11790        .filter_map(Value::as_str)
11791        .map(str::trim)
11792        .filter(|error_type| !error_type.is_empty())
11793    {
11794        if !non_retryable_error_types
11795            .iter()
11796            .any(|recorded| recorded == error_type)
11797        {
11798            non_retryable_error_types.push(error_type.to_string());
11799        }
11800    }
11801
11802    ActivityRetrySnapshot {
11803        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
11804        max_attempts: recorded_optional_u64(policy, "max_attempts"),
11805        backoff_seconds,
11806        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
11807        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
11808        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
11809        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
11810        non_retryable_error_types: if policy
11811            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
11812        {
11813            RecordedSnapshotValue::Known(non_retryable_error_types)
11814        } else {
11815            RecordedSnapshotValue::Unknown
11816        },
11817    }
11818}
11819
11820fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
11821    let policy = options.retry_policy.as_ref();
11822    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
11823        Some(Value::Null) => None,
11824        Some(value) => value_as_u64(value),
11825        None => Some(1),
11826    };
11827    let backoff_seconds = policy
11828        .and_then(|policy| policy.get("backoff_seconds"))
11829        .and_then(Value::as_array)
11830        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11831        .unwrap_or_default();
11832    let non_retryable_error_types = policy
11833        .and_then(|policy| policy.get("non_retryable_error_types"))
11834        .and_then(Value::as_array)
11835        .into_iter()
11836        .flatten()
11837        .filter_map(Value::as_str)
11838        .map(str::to_string)
11839        .collect();
11840
11841    ActivityRetrySnapshot {
11842        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
11843        max_attempts: RecordedSnapshotValue::Known(max_attempts),
11844        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
11845        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
11846        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
11847        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
11848        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
11849        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
11850    }
11851}
11852
11853fn activity_options_description(options: &RecordedActivityOptions) -> String {
11854    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
11855}
11856
11857impl RecordedCommand {
11858    fn sequence(&self) -> u64 {
11859        match self {
11860            Self::CancellationGroup { sequence, .. }
11861            | Self::CancellationScope { sequence, .. }
11862            | Self::CancellationBoundary { sequence, .. }
11863            | Self::Activity { sequence, .. }
11864            | Self::Timer { sequence, .. }
11865            | Self::ChildWorkflow { sequence, .. }
11866            | Self::SignalWait { sequence, .. }
11867            | Self::ConditionWait { sequence, .. }
11868            | Self::SearchAttributes { sequence, .. }
11869            | Self::SideEffect { sequence, .. }
11870            | Self::VersionMarker { sequence, .. }
11871            | Self::Memo { sequence, .. } => *sequence,
11872        }
11873    }
11874
11875    fn shape(&self) -> &'static str {
11876        match self {
11877            Self::CancellationScope { .. } => "cancellation scope",
11878            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
11879                "cooperative cancellation"
11880            }
11881            Self::Activity { .. } => "activity",
11882            Self::Timer { .. } => "timer",
11883            Self::ChildWorkflow { .. } => "child workflow",
11884            Self::SignalWait { .. } => "signal wait",
11885            Self::ConditionWait { .. } => "condition wait",
11886            Self::SearchAttributes { .. } => "search-attribute update",
11887            Self::SideEffect { .. } => "side effect",
11888            Self::VersionMarker { .. } => "version marker",
11889            Self::Memo { .. } => "memo upsert",
11890        }
11891    }
11892}
11893
11894fn ensure_version_supported(
11895    change_id: &str,
11896    version: i32,
11897    min_supported: i32,
11898    max_supported: i32,
11899    sequence: u64,
11900) -> Result<()> {
11901    if (min_supported..=max_supported).contains(&version) {
11902        return Ok(());
11903    }
11904    Err(Error::NonDeterministicReplay(ReplayFailure::new(
11905        "version_marker_incompatible_range",
11906        (sequence != 0).then_some(sequence),
11907        Some(format!("{min_supported}..={max_supported}")),
11908        Some(format!("{change_id}:{version}")),
11909        "recorded workflow version is outside the range supported by current code",
11910    )))
11911}
11912
11913#[derive(Clone, Debug)]
11914struct ResumeSignal {
11915    signal_name: String,
11916    arguments: Vec<AvroValue>,
11917}
11918
11919const MAX_PARALLEL_OPERATIONS: usize = 1000;
11920
11921fn parallel_group_prefix(kind: &str) -> &'static str {
11922    match kind {
11923        "activity" => "parallel-activities",
11924        "child" => "parallel-children",
11925        "timer" => "parallel-timers",
11926        _ => "parallel-calls",
11927    }
11928}
11929
11930fn parallel_group_entry(
11931    base_sequence: u64,
11932    size: usize,
11933    index: usize,
11934    kind: &str,
11935) -> ParallelGroupMetadata {
11936    ParallelGroupMetadata {
11937        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
11938        parallel_group_kind: kind.to_string(),
11939        parallel_group_base_sequence: base_sequence,
11940        parallel_group_size: size,
11941        parallel_group_index: index,
11942        parallel_group_mode: None,
11943        selection_member_key: None,
11944        selection_member_index: None,
11945        selection_member_base_sequence: None,
11946        selection_member_size: None,
11947        selection_member_kind: None,
11948    }
11949}
11950
11951struct SelectionMemberMetadata {
11952    key: SelectionKey,
11953    index: usize,
11954    base_sequence: u64,
11955    size: usize,
11956    kind: String,
11957}
11958
11959fn selection_group_entry(
11960    base_sequence: u64,
11961    size: usize,
11962    index: usize,
11963    kind: &str,
11964    member: &SelectionMemberMetadata,
11965) -> ParallelGroupMetadata {
11966    ParallelGroupMetadata {
11967        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
11968        parallel_group_kind: kind.to_string(),
11969        parallel_group_base_sequence: base_sequence,
11970        parallel_group_size: size,
11971        parallel_group_index: index,
11972        parallel_group_mode: Some("select".to_string()),
11973        selection_member_key: Some(member.key.clone()),
11974        selection_member_index: Some(member.index),
11975        selection_member_base_sequence: Some(member.base_sequence),
11976        selection_member_size: Some(member.size),
11977        selection_member_kind: Some(member.kind.clone()),
11978    }
11979}
11980
11981fn apply_parallel_group_path(
11982    command: &mut serde_json::Map<String, Value>,
11983    path: &[ParallelGroupMetadata],
11984) {
11985    let Some(inner) = path.last() else {
11986        return;
11987    };
11988    command.insert(
11989        "parallel_group_id".to_string(),
11990        json!(inner.parallel_group_id),
11991    );
11992    command.insert(
11993        "parallel_group_kind".to_string(),
11994        json!(inner.parallel_group_kind),
11995    );
11996    command.insert(
11997        "parallel_group_base_sequence".to_string(),
11998        json!(inner.parallel_group_base_sequence),
11999    );
12000    command.insert(
12001        "parallel_group_size".to_string(),
12002        json!(inner.parallel_group_size),
12003    );
12004    command.insert(
12005        "parallel_group_index".to_string(),
12006        json!(inner.parallel_group_index),
12007    );
12008    if let Some(mode) = &inner.parallel_group_mode {
12009        command.insert("parallel_group_mode".to_string(), json!(mode));
12010    }
12011    if let Some(key) = &inner.selection_member_key {
12012        command.insert("selection_member_key".to_string(), json!(key));
12013    }
12014    if let Some(index) = inner.selection_member_index {
12015        command.insert("selection_member_index".to_string(), json!(index));
12016    }
12017    if let Some(base_sequence) = inner.selection_member_base_sequence {
12018        command.insert(
12019            "selection_member_base_sequence".to_string(),
12020            json!(base_sequence),
12021        );
12022    }
12023    if let Some(size) = inner.selection_member_size {
12024        command.insert("selection_member_size".to_string(), json!(size));
12025    }
12026    if let Some(kind) = &inner.selection_member_kind {
12027        command.insert("selection_member_kind".to_string(), json!(kind));
12028    }
12029    command.insert("parallel_group_path".to_string(), json!(path));
12030}
12031
12032fn ensure_parallel_path_matches(
12033    sequence: u64,
12034    recorded: Option<&[ParallelGroupMetadata]>,
12035    expected: &[ParallelGroupMetadata],
12036) -> Result<()> {
12037    match (recorded, expected.is_empty()) {
12038        (None, true) => Ok(()),
12039        (Some(recorded), false) if recorded == expected => Ok(()),
12040        (None, false) => Err(invalid_recorded_history(
12041            "parallel_group_metadata_missing",
12042            sequence,
12043            &serde_json::to_string(expected).unwrap_or_default(),
12044            "<missing>",
12045            "recorded parallel member is missing its durable group path",
12046        )),
12047        (Some(recorded), true) => Err(invalid_recorded_history(
12048            "parallel_group_shape_mismatch",
12049            sequence,
12050            "sequential command",
12051            &serde_json::to_string(recorded).unwrap_or_default(),
12052            "recorded command belonged to a parallel group but current code schedules it sequentially",
12053        )),
12054        (Some(recorded), false) => Err(invalid_recorded_history(
12055            "parallel_group_shape_mismatch",
12056            sequence,
12057            &serde_json::to_string(recorded).unwrap_or_default(),
12058            &serde_json::to_string(expected).unwrap_or_default(),
12059            "recorded parallel-group identity or path changed during replay",
12060        )),
12061    }
12062}
12063
12064#[derive(Clone, Debug)]
12065enum ParallelShape {
12066    Leaf,
12067    Group(Vec<ParallelShape>),
12068}
12069
12070struct ParallelDescriptor {
12071    operation: ParallelOperation,
12072    offset: usize,
12073    member_path: Vec<usize>,
12074    group_path: Vec<ParallelGroupMetadata>,
12075}
12076
12077fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
12078    operations
12079        .iter()
12080        .map(|operation| match operation {
12081            ParallelOperation::Group(children) => parallel_leaf_count(children),
12082            _ => 1,
12083        })
12084        .sum()
12085}
12086
12087fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
12088    match operation {
12089        ParallelOperation::Activity { .. } => Some("activity"),
12090        ParallelOperation::ChildWorkflow { .. } => Some("child"),
12091        ParallelOperation::Timer(_) => Some("timer"),
12092        ParallelOperation::Signal(_) => Some("signal"),
12093        ParallelOperation::Condition { .. } => Some("condition"),
12094        ParallelOperation::Group(children) => parallel_group_kind(children),
12095    }
12096}
12097
12098fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
12099    let mut kind = None;
12100    for operation in operations {
12101        let Some(operation_kind) = parallel_operation_kind(operation) else {
12102            continue;
12103        };
12104        match kind {
12105            None => kind = Some(operation_kind),
12106            Some(current) if current == operation_kind => {}
12107            Some(_) => return Some("mixed"),
12108        }
12109    }
12110    kind
12111}
12112
12113fn validate_parallel_operations(
12114    operations: &[ParallelOperation],
12115    member_path: &mut Vec<usize>,
12116    root: bool,
12117) -> Result<()> {
12118    let leaves = parallel_leaf_count(operations);
12119    if leaves > MAX_PARALLEL_OPERATIONS {
12120        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12121            reason: "fan_out_limit_exceeded",
12122            member_path: member_path.clone(),
12123            message: format!(
12124                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12125            ),
12126        }));
12127    }
12128    if !root && operations.is_empty() {
12129        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12130            reason: "nested_group_empty",
12131            member_path: member_path.clone(),
12132            message: "a nested group must contain at least one durable leaf".to_string(),
12133        }));
12134    }
12135
12136    for (index, operation) in operations.iter().enumerate() {
12137        member_path.push(index);
12138        match operation {
12139            ParallelOperation::Activity {
12140                options, arguments, ..
12141            } => {
12142                options
12143                    .validate()
12144                    .map_err(|error| Error::InvalidActivityOptions(error))?;
12145                if let Err(error) = arguments {
12146                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12147                        reason: "arguments_invalid",
12148                        member_path: member_path.clone(),
12149                        message: error.to_string(),
12150                    }));
12151                }
12152            }
12153            ParallelOperation::ChildWorkflow {
12154                options, arguments, ..
12155            } => {
12156                validate_parallel_child_options(options)?;
12157                if let Err(error) = arguments {
12158                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12159                        reason: "arguments_invalid",
12160                        member_path: member_path.clone(),
12161                        message: error.to_string(),
12162                    }));
12163                }
12164            }
12165            ParallelOperation::Timer(duration)
12166                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
12167            {
12168                return Err(Error::TimerDurationOverflow);
12169            }
12170            ParallelOperation::Timer(_) => {}
12171            ParallelOperation::Signal(signal_name) => {
12172                validate_user_signal_name(signal_name)?;
12173                if signal_name.trim().is_empty() {
12174                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12175                        reason: "signal_name_empty",
12176                        member_path: member_path.clone(),
12177                        message: "signal wait name must not be empty".to_string(),
12178                    }));
12179                }
12180            }
12181            ParallelOperation::Condition { options, .. } => {
12182                options.validate()?;
12183            }
12184            ParallelOperation::Group(children) => {
12185                validate_parallel_operations(children, member_path, false)?;
12186            }
12187        }
12188        member_path.pop();
12189    }
12190    Ok(())
12191}
12192
12193fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
12194    if options.task_queue.trim().is_empty() {
12195        return Err(Error::InvalidChildWorkflowOptions(
12196            "task_queue must not be empty".to_string(),
12197        ));
12198    }
12199    for (name, value) in [
12200        (
12201            "execution_timeout_seconds",
12202            options.execution_timeout_seconds,
12203        ),
12204        ("run_timeout_seconds", options.run_timeout_seconds),
12205    ] {
12206        if value == Some(0) {
12207            return Err(Error::InvalidChildWorkflowOptions(format!(
12208                "{name} must be at least 1"
12209            )));
12210        }
12211    }
12212    if options
12213        .retry_policy
12214        .as_ref()
12215        .is_some_and(|policy| policy.max_attempts == Some(0))
12216    {
12217        return Err(Error::InvalidChildWorkflowOptions(
12218            "retry_policy.max_attempts must be at least 1".to_string(),
12219        ));
12220    }
12221    Ok(())
12222}
12223
12224fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
12225    ParallelShape::Group(
12226        operations
12227            .iter()
12228            .map(|operation| match operation {
12229                ParallelOperation::Group(children) => parallel_shape(children),
12230                _ => ParallelShape::Leaf,
12231            })
12232            .collect(),
12233    )
12234}
12235
12236fn parallel_descriptors(
12237    operations: Vec<ParallelOperation>,
12238    base_sequence: u64,
12239) -> Result<Vec<ParallelDescriptor>> {
12240    let size = parallel_leaf_count(&operations);
12241    let kind = parallel_group_kind(&operations).unwrap_or("activity");
12242    let mut descriptors = Vec::with_capacity(size);
12243    let mut cursor = 0;
12244
12245    for (index, operation) in operations.into_iter().enumerate() {
12246        match operation {
12247            ParallelOperation::Group(children) => {
12248                let child_base = base_sequence
12249                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12250                    .ok_or(Error::TimerDurationOverflow)?;
12251                for mut descriptor in parallel_descriptors(children, child_base)? {
12252                    let outer_index = cursor + descriptor.offset;
12253                    descriptor.group_path.insert(
12254                        0,
12255                        parallel_group_entry(base_sequence, size, outer_index, kind),
12256                    );
12257                    descriptor.member_path.insert(0, index);
12258                    descriptor.offset = outer_index;
12259                    descriptors.push(descriptor);
12260                }
12261                cursor = descriptors.len();
12262            }
12263            operation => {
12264                descriptors.push(ParallelDescriptor {
12265                    operation,
12266                    offset: cursor,
12267                    member_path: vec![index],
12268                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
12269                });
12270                cursor += 1;
12271            }
12272        }
12273    }
12274    Ok(descriptors)
12275}
12276
12277enum ParallelLeafCall {
12278    Activity(ActivityCall),
12279    ChildWorkflow(ChildWorkflowCall),
12280    Timer(TimerCall),
12281    Signal(SignalCall),
12282    Condition(ConditionWaitCall),
12283}
12284
12285fn parallel_leaf_call(
12286    ctx: &WorkflowContext,
12287    operation: ParallelOperation,
12288    parallel_group_path: Vec<ParallelGroupMetadata>,
12289) -> ParallelLeafCall {
12290    match operation {
12291        ParallelOperation::Activity {
12292            activity_type,
12293            options,
12294            arguments,
12295        } => ParallelLeafCall::Activity(ActivityCall {
12296            ctx: ctx.clone(),
12297            activity_type,
12298            options,
12299            worker_session: None,
12300            args: Some(arguments),
12301            scheduled: false,
12302            local: false,
12303            local_result: None,
12304            parallel_group_path,
12305        }),
12306        ParallelOperation::ChildWorkflow {
12307            workflow_type,
12308            options,
12309            arguments,
12310        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
12311            ctx: ctx.clone(),
12312            workflow_type,
12313            options,
12314            args: Some(arguments),
12315            scheduled: false,
12316            matched_pending: false,
12317            parallel_group_path,
12318        }),
12319        ParallelOperation::Timer(duration) => {
12320            let delay_seconds = duration
12321                .as_secs()
12322                .checked_add(u64::from(duration.subsec_nanos() > 0));
12323            ParallelLeafCall::Timer(TimerCall {
12324                ctx: ctx.clone(),
12325                delay_seconds,
12326                scheduled: false,
12327                matched_pending: false,
12328                parallel_group_path,
12329            })
12330        }
12331        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
12332            ctx: ctx.clone(),
12333            signal_name,
12334            runtime_reserved_allowed: false,
12335            opened_wait: false,
12336            matched_pending: false,
12337            parallel_group_path,
12338        }),
12339        ParallelOperation::Condition { options, predicate } => {
12340            ParallelLeafCall::Condition(ConditionWaitCall {
12341                ctx: ctx.clone(),
12342                options,
12343                predicate,
12344                occurrence_id: None,
12345                opened_wait: false,
12346                parallel_group_path,
12347            })
12348        }
12349        ParallelOperation::Group(_) => {
12350            unreachable!("parallel descriptors contain only durable leaves")
12351        }
12352    }
12353}
12354
12355impl ParallelLeafCall {
12356    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
12357        match self {
12358            Self::Activity(call) => Pin::new(call)
12359                .poll_avro_value(cx)
12360                .map_ok(ParallelAvroResult::Activity),
12361            Self::ChildWorkflow(call) => Pin::new(call)
12362                .poll_avro_value(cx)
12363                .map_ok(ParallelAvroResult::ChildWorkflow),
12364            Self::Timer(call) => Pin::new(call)
12365                .poll(cx)
12366                .map_ok(|()| ParallelAvroResult::Timer),
12367            Self::Signal(call) => Pin::new(call)
12368                .poll_avro_value(cx)
12369                .map_ok(ParallelAvroResult::Signal),
12370            Self::Condition(call) => Pin::new(call)
12371                .poll(cx)
12372                .map_ok(ParallelAvroResult::Condition),
12373        }
12374    }
12375}
12376
12377struct ParallelLeaf {
12378    call: ParallelLeafCall,
12379    sequence: u64,
12380    member_path: Vec<usize>,
12381    group_path: Vec<ParallelGroupMetadata>,
12382    result: Option<ParallelAvroResult>,
12383}
12384
12385/// Future returned by [`WorkflowContext::parallel`].
12386pub struct ParallelCall {
12387    ctx: WorkflowContext,
12388    operations: Option<Vec<ParallelOperation>>,
12389    shape: Option<ParallelShape>,
12390    leaves: Vec<ParallelLeaf>,
12391    pending_scope_delivery: bool,
12392    worker_session: Option<WorkerSessionOptions>,
12393}
12394
12395impl ParallelCall {
12396    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
12397        Self {
12398            ctx,
12399            operations: Some(operations),
12400            shape: None,
12401            leaves: Vec::new(),
12402            pending_scope_delivery: false,
12403            worker_session: None,
12404        }
12405    }
12406
12407    fn initialize(&mut self) -> Result<()> {
12408        if let Some(session) = &self.worker_session {
12409            session.to_wire()?;
12410        }
12411        let operations = self.operations.take().unwrap_or_default();
12412        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
12413        self.shape = Some(parallel_shape(&operations));
12414        if operations.is_empty() {
12415            return Ok(());
12416        }
12417
12418        let base_sequence = {
12419            let state = self
12420                .ctx
12421                .state
12422                .lock()
12423                .map_err(|_| Error::WorkflowStatePoisoned)?;
12424            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12425                recorded.sequence()
12426            } else {
12427                let last = state
12428                    .recorded_commands
12429                    .last()
12430                    .map(RecordedCommand::sequence)
12431                    .unwrap_or(0);
12432                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12433                    .and_then(|sequence| sequence.checked_add(1))
12434                    .ok_or_else(|| {
12435                        Error::InvalidParallelGroup(ParallelGroupError {
12436                            reason: "sequence_overflow",
12437                            member_path: Vec::new(),
12438                            message: "parallel group sequence identity overflowed u64".to_string(),
12439                        })
12440                    })?
12441            }
12442        };
12443
12444        let descriptors = parallel_descriptors(operations, base_sequence)?;
12445        {
12446            let mut state = self
12447                .ctx
12448                .state
12449                .lock()
12450                .map_err(|_| Error::WorkflowStatePoisoned)?;
12451            let cursor = state.command_cursor;
12452            self.ctx.validate_scope_membership(&mut state, cursor)?;
12453            if state.prepare_parallel_scope_cancellation(&descriptors)? {
12454                self.pending_scope_delivery = true;
12455                return Ok(());
12456            }
12457            state.expand_cancellation_group(&descriptors)?;
12458            state.prepare_group_cancellation(&descriptors)?;
12459        }
12460        self.leaves = descriptors
12461            .into_iter()
12462            .map(|descriptor| {
12463                let mut call = parallel_leaf_call(
12464                    &self.ctx,
12465                    descriptor.operation,
12466                    descriptor.group_path.clone(),
12467                );
12468                if let (Some(session), ParallelLeafCall::Activity(activity)) =
12469                    (&self.worker_session, &mut call)
12470                {
12471                    activity.worker_session = Some(session.clone());
12472                }
12473                ParallelLeaf {
12474                    call,
12475                    sequence: base_sequence + descriptor.offset as u64,
12476                    member_path: descriptor.member_path,
12477                    group_path: descriptor.group_path,
12478                    result: None,
12479                }
12480            })
12481            .collect();
12482        Ok(())
12483    }
12484
12485    fn poll_avro_value(
12486        mut self: Pin<&mut Self>,
12487        cx: &mut TaskContext<'_>,
12488    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
12489        if self.operations.is_some() {
12490            if let Err(error) = self.initialize() {
12491                return Poll::Ready(Err(error));
12492            }
12493        }
12494        if self.pending_scope_delivery {
12495            return Poll::Pending;
12496        }
12497        if self.leaves.is_empty() {
12498            return Poll::Ready(Ok(Vec::new()));
12499        }
12500
12501        let mut failures = Vec::new();
12502        let mut pending = false;
12503        for (index, leaf) in self.leaves.iter_mut().enumerate() {
12504            if leaf.result.is_some() {
12505                continue;
12506            }
12507            match leaf.call.poll_avro_value(cx) {
12508                Poll::Ready(Ok(result)) => leaf.result = Some(result),
12509                Poll::Ready(Err(error)) => failures.push((index, error)),
12510                Poll::Pending => pending = true,
12511            }
12512        }
12513
12514        if !failures.is_empty() {
12515            if let Some(position) = failures
12516                .iter()
12517                .position(|(_, error)| workflow_task_integrity_error(error))
12518            {
12519                return Poll::Ready(Err(failures.remove(position).1));
12520            }
12521            if self
12522                .ctx
12523                .state
12524                .lock()
12525                .map_err(|_| Error::WorkflowStatePoisoned)?
12526                .cancellation_delivery_intent
12527                .is_some()
12528            {
12529                return Poll::Pending;
12530            }
12531            if let Some(position) = failures
12532                .iter()
12533                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
12534            {
12535                return Poll::Ready(Err(failures.remove(position).1));
12536            }
12537            failures.sort_by_key(|(index, _)| *index);
12538            let (failed_index, cause) = failures.remove(0);
12539            let failed = &self.leaves[failed_index];
12540            let completed = self
12541                .leaves
12542                .iter()
12543                .filter_map(|leaf| {
12544                    leaf.result
12545                        .clone()
12546                        .and_then(|result| result.into_json_result().ok())
12547                        .map(|result| ParallelCompletion {
12548                            member_path: leaf.member_path.clone(),
12549                            result,
12550                        })
12551                })
12552                .collect();
12553            let group_id = failed
12554                .group_path
12555                .first()
12556                .map(|entry| entry.parallel_group_id.clone())
12557                .unwrap_or_default();
12558            let sequences = self
12559                .leaves
12560                .iter()
12561                .map(|leaf| leaf.sequence)
12562                .collect::<Vec<_>>();
12563            self.ctx
12564                .state
12565                .lock()
12566                .map_err(|_| Error::WorkflowStatePoisoned)?
12567                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12568            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12569                group_id,
12570                member_path: failed.member_path.clone(),
12571                group_path: failed.group_path.clone(),
12572                completed,
12573                cause: Box::new(cause),
12574            })));
12575        }
12576        if pending
12577            || self
12578                .ctx
12579                .state
12580                .lock()
12581                .map_err(|_| Error::WorkflowStatePoisoned)?
12582                .cancellation_delivery_intent
12583                .is_some()
12584        {
12585            return Poll::Pending;
12586        }
12587
12588        let mut flat_results = self
12589            .leaves
12590            .iter_mut()
12591            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12592            .collect::<Vec<_>>()
12593            .into_iter();
12594        let results = parallel_results_for_shape(
12595            self.shape.as_ref().expect("initialized parallel shape"),
12596            &mut flat_results,
12597        );
12598        let sequences = self
12599            .leaves
12600            .iter()
12601            .map(|leaf| leaf.sequence)
12602            .collect::<Vec<_>>();
12603        self.ctx
12604            .state
12605            .lock()
12606            .map_err(|_| Error::WorkflowStatePoisoned)?
12607            .advance_cancellation_sequences(&sequences, None);
12608        Poll::Ready(Ok(match results {
12609            ParallelAvroResult::Group(results) => results,
12610            ParallelAvroResult::Activity(_)
12611            | ParallelAvroResult::ChildWorkflow(_)
12612            | ParallelAvroResult::Timer
12613            | ParallelAvroResult::Signal(_)
12614            | ParallelAvroResult::Condition(_) => {
12615                unreachable!("root parallel shape is a group")
12616            }
12617        }))
12618    }
12619}
12620
12621fn parallel_results_for_shape(
12622    shape: &ParallelShape,
12623    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12624) -> ParallelAvroResult {
12625    match shape {
12626        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12627        ParallelShape::Group(children) => ParallelAvroResult::Group(
12628            children
12629                .iter()
12630                .map(|child| parallel_results_for_shape(child, flat_results))
12631                .collect(),
12632        ),
12633    }
12634}
12635
12636impl Future for ParallelCall {
12637    type Output = Result<Vec<ParallelResult>>;
12638
12639    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12640        self.poll_avro_value(cx)
12641            .map_ok(|results| {
12642                results
12643                    .into_iter()
12644                    .map(ParallelAvroResult::into_json_result)
12645                    .collect::<Result<Vec<_>>>()
12646            })
12647            .map_ok(|result| result)
12648            .flatten_result()
12649    }
12650}
12651
12652#[derive(Clone, Debug)]
12653struct SelectionMemberPlan {
12654    key: SelectionKey,
12655    index: usize,
12656    base_sequence: u64,
12657    size: usize,
12658    kind: String,
12659    shape: ParallelShape,
12660    leaf_start: usize,
12661}
12662
12663fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12664    match operation {
12665        ParallelOperation::Activity { .. } => "activity",
12666        ParallelOperation::ChildWorkflow { .. } => "child",
12667        ParallelOperation::Timer(_) => "timer",
12668        ParallelOperation::Signal(_) => "signal",
12669        ParallelOperation::Condition { .. } => "condition",
12670        ParallelOperation::Group(_) => "group",
12671    }
12672}
12673
12674fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12675    match operation {
12676        ParallelOperation::Group(children) => parallel_shape(children),
12677        _ => ParallelShape::Leaf,
12678    }
12679}
12680
12681fn selection_descriptors(
12682    operations: Vec<(SelectionKey, ParallelOperation)>,
12683    base_sequence: u64,
12684) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12685    if operations.is_empty() {
12686        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12687            reason: "selection_empty",
12688            member_path: Vec::new(),
12689            message: "durable selection requires at least one operation".to_string(),
12690        }));
12691    }
12692    let operation_refs = operations
12693        .iter()
12694        .map(|(_, operation)| operation)
12695        .collect::<Vec<_>>();
12696    let total_size = operation_refs
12697        .iter()
12698        .map(|operation| match operation {
12699            ParallelOperation::Group(children) => parallel_leaf_count(children),
12700            _ => 1,
12701        })
12702        .sum::<usize>();
12703    if total_size > MAX_PARALLEL_OPERATIONS {
12704        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12705            reason: "fan_out_limit_exceeded",
12706            member_path: Vec::new(),
12707            message: format!(
12708                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12709            ),
12710        }));
12711    }
12712    let group_kind = {
12713        let mut kind = None;
12714        for operation in &operation_refs {
12715            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
12716            match kind {
12717                None => kind = Some(operation_kind),
12718                Some(current) if current == operation_kind => {}
12719                Some(_) => {
12720                    kind = Some("mixed");
12721                    break;
12722                }
12723            }
12724        }
12725        kind.unwrap_or("mixed")
12726    };
12727
12728    let mut descriptors = Vec::with_capacity(total_size);
12729    let mut members = Vec::with_capacity(operations.len());
12730    let mut cursor = 0usize;
12731    let mut seen_keys: Vec<SelectionKey> = Vec::new();
12732    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
12733        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
12734            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12735                reason: "selection_key_invalid",
12736                member_path: vec![member_index],
12737                message: "selection member keys must be non-empty strings or non-negative integers"
12738                    .to_string(),
12739            }));
12740        }
12741        if seen_keys.contains(&key) {
12742            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12743                reason: "selection_key_duplicate",
12744                member_path: vec![member_index],
12745                message: format!("selection member key {key:?} is duplicated"),
12746            }));
12747        }
12748        seen_keys.push(key.clone());
12749        let member_size = match &operation {
12750            ParallelOperation::Group(children) => parallel_leaf_count(children),
12751            _ => 1,
12752        };
12753        if member_size == 0 {
12754            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12755                reason: "selection_member_empty",
12756                member_path: vec![member_index],
12757                message: "a selection member must contain at least one durable leaf".to_string(),
12758            }));
12759        }
12760        let member_base = base_sequence
12761            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12762            .ok_or(Error::TimerDurationOverflow)?;
12763        let member_kind = selection_operation_kind(&operation).to_string();
12764        let member_shape = selection_operation_shape(&operation);
12765        let leaf_start = descriptors.len();
12766        match operation {
12767            ParallelOperation::Group(children) => {
12768                validate_parallel_operations(&children, &mut vec![member_index], false)?;
12769                for mut descriptor in parallel_descriptors(children, member_base)? {
12770                    let flat_index = cursor + descriptor.offset;
12771                    descriptor.group_path.insert(
12772                        0,
12773                        selection_group_entry(
12774                            base_sequence,
12775                            total_size,
12776                            flat_index,
12777                            group_kind,
12778                            &SelectionMemberMetadata {
12779                                key: key.clone(),
12780                                index: member_index,
12781                                base_sequence: member_base,
12782                                size: member_size,
12783                                kind: member_kind.clone(),
12784                            },
12785                        ),
12786                    );
12787                    descriptor.member_path.insert(0, member_index);
12788                    descriptor.offset = flat_index;
12789                    descriptors.push(descriptor);
12790                }
12791            }
12792            operation => {
12793                validate_parallel_operations(
12794                    std::slice::from_ref(&operation),
12795                    &mut Vec::new(),
12796                    true,
12797                )?;
12798                descriptors.push(ParallelDescriptor {
12799                    operation,
12800                    offset: cursor,
12801                    member_path: vec![member_index],
12802                    group_path: vec![selection_group_entry(
12803                        base_sequence,
12804                        total_size,
12805                        cursor,
12806                        group_kind,
12807                        &SelectionMemberMetadata {
12808                            key: key.clone(),
12809                            index: member_index,
12810                            base_sequence: member_base,
12811                            size: member_size,
12812                            kind: member_kind.clone(),
12813                        },
12814                    )],
12815                });
12816            }
12817        }
12818        members.push(SelectionMemberPlan {
12819            key,
12820            index: member_index,
12821            base_sequence: member_base,
12822            size: member_size,
12823            kind: member_kind,
12824            shape: member_shape,
12825            leaf_start,
12826        });
12827        cursor += member_size;
12828    }
12829    Ok((descriptors, members))
12830}
12831
12832struct SelectionLeaf {
12833    call: ParallelLeafCall,
12834    outcome: Option<Result<ParallelAvroResult>>,
12835}
12836
12837/// Stable reference to one member of a durable selection group.
12838#[derive(Clone)]
12839pub struct DurableOperationHandle {
12840    ctx: WorkflowContext,
12841    pub key: SelectionKey,
12842    pub index: usize,
12843    pub kind: String,
12844    pub identity: String,
12845    pub base_sequence: u64,
12846    pub size: usize,
12847    pub selection_group_id: String,
12848    shape: ParallelShape,
12849}
12850
12851impl std::fmt::Debug for DurableOperationHandle {
12852    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12853        formatter
12854            .debug_struct("DurableOperationHandle")
12855            .field("key", &self.key)
12856            .field("index", &self.index)
12857            .field("kind", &self.kind)
12858            .field("identity", &self.identity)
12859            .field("base_sequence", &self.base_sequence)
12860            .field("size", &self.size)
12861            .field("selection_group_id", &self.selection_group_id)
12862            .finish()
12863    }
12864}
12865
12866impl DurableOperationHandle {
12867    /// Await this member after another member has already won the selection.
12868    pub fn await_result(&self) -> DurableOperationAwaitCall {
12869        DurableOperationAwaitCall {
12870            handle: self.clone(),
12871        }
12872    }
12873
12874    /// Request cancellation without affecting siblings. The future resolves
12875    /// to unit; only `SelectionOperationCancelled` history proves cancellation
12876    /// beat a concurrently committed terminal result.
12877    pub fn cancel(&self) -> CancelDurableOperationCall {
12878        CancelDurableOperationCall {
12879            handle: self.clone(),
12880            emitted: false,
12881        }
12882    }
12883}
12884
12885/// The one winner committed for a durable selection group.
12886#[derive(Debug)]
12887pub struct SelectionResult {
12888    pub key: SelectionKey,
12889    pub index: usize,
12890    pub kind: String,
12891    pub identity: String,
12892    pub value: Option<ParallelResult>,
12893    pub failure: Option<Error>,
12894    pub winner: DurableOperationHandle,
12895    pub handles: Vec<DurableOperationHandle>,
12896}
12897
12898impl SelectionResult {
12899    pub fn succeeded(&self) -> bool {
12900        self.failure.is_none()
12901    }
12902
12903    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
12904        self.handles.iter().find(|handle| &handle.key == key)
12905    }
12906
12907    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
12908        self.handles
12909            .iter()
12910            .filter(|handle| handle.index != self.index)
12911            .collect()
12912    }
12913
12914    pub fn into_result(self) -> Result<ParallelResult> {
12915        match (self.value, self.failure) {
12916            (Some(value), None) => Ok(value),
12917            (_, Some(error)) => Err(error),
12918            _ => Err(Error::WorkerLoop(
12919                "selection result contained neither a value nor a failure".to_string(),
12920            )),
12921        }
12922    }
12923}
12924
12925/// Future returned by [`WorkflowContext::select`].
12926pub struct SelectCall {
12927    ctx: WorkflowContext,
12928    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
12929    members: Vec<SelectionMemberPlan>,
12930    leaves: Vec<SelectionLeaf>,
12931    group_id: Option<String>,
12932}
12933
12934impl SelectCall {
12935    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
12936        Self {
12937            ctx,
12938            operations: Some(operations),
12939            members: Vec::new(),
12940            leaves: Vec::new(),
12941            group_id: None,
12942        }
12943    }
12944
12945    fn initialize(&mut self) -> Result<()> {
12946        let operations = self.operations.take().unwrap_or_default();
12947        let base_sequence = {
12948            let state = self
12949                .ctx
12950                .state
12951                .lock()
12952                .map_err(|_| Error::WorkflowStatePoisoned)?;
12953            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
12954                state.recorded_commands.get(state.command_cursor)
12955            {
12956                *sequence
12957            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
12958            {
12959                marker.selection_group_base_sequence
12960            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12961                recorded.sequence()
12962            } else {
12963                let last = state
12964                    .recorded_commands
12965                    .last()
12966                    .map(RecordedCommand::sequence)
12967                    .unwrap_or(0);
12968                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12969                    .and_then(|sequence| sequence.checked_add(1))
12970                    .ok_or(Error::TimerDurationOverflow)?
12971            }
12972        };
12973        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
12974        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
12975        {
12976            let mut state = self
12977                .ctx
12978                .state
12979                .lock()
12980                .map_err(|_| Error::WorkflowStatePoisoned)?;
12981            state.expand_cancellation_group(&descriptors)?;
12982            state.prepare_group_cancellation(&descriptors)?;
12983        }
12984        self.leaves = descriptors
12985            .into_iter()
12986            .map(|descriptor| SelectionLeaf {
12987                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
12988                outcome: None,
12989            })
12990            .collect();
12991        self.members = members;
12992        self.group_id = Some(group_id);
12993        Ok(())
12994    }
12995}
12996
12997impl Future for SelectCall {
12998    type Output = Result<SelectionResult>;
12999
13000    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13001        if self.operations.is_some() {
13002            if let Err(error) = self.initialize() {
13003                return Poll::Ready(Err(error));
13004            }
13005        }
13006
13007        for leaf in &mut self.leaves {
13008            if leaf.outcome.is_some() {
13009                continue;
13010            }
13011            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
13012                if outcome
13013                    .as_ref()
13014                    .err()
13015                    .is_some_and(workflow_task_integrity_error)
13016                {
13017                    return Poll::Ready(outcome.map(|_| unreachable!()));
13018                }
13019                leaf.outcome = Some(outcome);
13020            }
13021        }
13022
13023        if self
13024            .ctx
13025            .state
13026            .lock()
13027            .map_err(|_| Error::WorkflowStatePoisoned)?
13028            .cancellation_delivery_intent
13029            .is_some()
13030        {
13031            return Poll::Pending;
13032        }
13033
13034        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
13035            matches!(
13036                leaf.outcome,
13037                Some(Err(Error::CooperativeCancellationRequested(_)))
13038            )
13039        }) {
13040            return Poll::Ready(
13041                leaf.outcome
13042                    .take()
13043                    .expect("matched cancellation")
13044                    .map(|_| unreachable!()),
13045            );
13046        }
13047
13048        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
13049        let selection_member_range = self
13050            .members
13051            .first()
13052            .map(|member| member.base_sequence)
13053            .zip(self.leaves.len().try_into().ok())
13054            .map(|(base_sequence, size): (u64, u64)| {
13055                base_sequence..base_sequence.saturating_add(size)
13056            });
13057        let marker = {
13058            let mut state = match self.ctx.state.lock() {
13059                Ok(state) => state,
13060                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13061            };
13062            let marker = state
13063                .selection_markers
13064                .get(state.selection_marker_cursor)
13065                .cloned();
13066            if marker.is_none()
13067                && all_members_terminal
13068                && selection_member_range.as_ref().is_some_and(|member_range| {
13069                    state
13070                        .recorded_commands
13071                        .iter()
13072                        .any(|command| member_range.contains(&command.sequence()))
13073                })
13074            {
13075                // Terminal member history can be committed before the server's
13076                // SelectionResolved marker becomes visible to this task. That
13077                // marker is the durable barrier the selection is still waiting
13078                // on, so an otherwise commandless replay remains legitimately
13079                // pending instead of failing as an untracked yield.
13080                state.matched_recorded_pending = true;
13081            }
13082            marker
13083        };
13084        let Some(marker) = marker else {
13085            return Poll::Pending;
13086        };
13087        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
13088            || marker.selection_group_size != self.leaves.len()
13089            || self.members.first().map(|member| member.base_sequence)
13090                != Some(marker.selection_group_base_sequence)
13091        {
13092            return Poll::Ready(Err(invalid_recorded_history(
13093                "selection_group_shape_mismatch",
13094                marker.selection_group_base_sequence,
13095                self.group_id
13096                    .as_deref()
13097                    .unwrap_or("initialized selection group"),
13098                &marker.selection_group_id,
13099                "recorded selection group differs from current workflow code",
13100            )));
13101        }
13102        let Some(member_position) = self.members.iter().position(|member| {
13103            member.key == marker.member_key
13104                && member.index == marker.member_index
13105                && member.base_sequence == marker.member_base_sequence
13106                && member.size == marker.member_size
13107                && member.kind == marker.operation_kind
13108        }) else {
13109            return Poll::Ready(Err(invalid_recorded_history(
13110                "selection_member_shape_mismatch",
13111                marker.member_base_sequence,
13112                "winner member matching current workflow code",
13113                &format!("{:?}", marker.member_key),
13114                "recorded selection winner differs from the authored member identity",
13115            )));
13116        };
13117        let member = self.members[member_position].clone();
13118        let (handles, resolution_sequence) = {
13119            let mut state = match self.ctx.state.lock() {
13120                Ok(state) => state,
13121                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13122            };
13123            let identities = self
13124                .members
13125                .iter()
13126                .map(|candidate| {
13127                    selection_operation_identity(
13128                        &state,
13129                        &candidate.kind,
13130                        candidate.base_sequence,
13131                        candidate.size,
13132                    )
13133                })
13134                .collect::<Vec<_>>();
13135            if let Some((position, missing)) = identities
13136                .iter()
13137                .enumerate()
13138                .find(|(_, identity)| identity.is_empty())
13139                .map(|(position, identity)| (position, identity.clone()))
13140            {
13141                let candidate = &self.members[position];
13142                return Poll::Ready(Err(invalid_recorded_history(
13143                    "selection_operation_identity_missing",
13144                    candidate.base_sequence,
13145                    &format!(
13146                        "durable {} resource identity from scheduled/open history",
13147                        candidate.kind
13148                    ),
13149                    &missing,
13150                    "selection member history is missing its canonical durable identity",
13151                )));
13152            }
13153            let expected_winner_identity = &identities[member_position];
13154            let resolution_sequence = match validated_selection_resolution_sequence(
13155                &state,
13156                &marker,
13157                &member,
13158                expected_winner_identity,
13159            ) {
13160                Ok(sequence) => sequence,
13161                Err(error) => return Poll::Ready(Err(error)),
13162            };
13163            let handles = self
13164                .members
13165                .iter()
13166                .zip(identities)
13167                .map(|(member, identity)| DurableOperationHandle {
13168                    ctx: self.ctx.clone(),
13169                    key: member.key.clone(),
13170                    index: member.index,
13171                    kind: member.kind.clone(),
13172                    identity,
13173                    base_sequence: member.base_sequence,
13174                    size: member.size,
13175                    selection_group_id: marker.selection_group_id.clone(),
13176                    shape: member.shape.clone(),
13177                })
13178                .collect::<Vec<_>>();
13179            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
13180                return Poll::Ready(Err(error));
13181            }
13182            state.selection_marker_cursor += 1;
13183            (handles, resolution_sequence)
13184        };
13185
13186        let mut winner_failure = None;
13187        let mut flat_results = Vec::with_capacity(member.size);
13188        if marker.outcome == "failed" {
13189            let resolution_offset = match resolution_sequence
13190                .checked_sub(member.base_sequence)
13191                .and_then(|offset| usize::try_from(offset).ok())
13192            {
13193                Some(offset) if offset < member.size => offset,
13194                _ => {
13195                    return Poll::Ready(Err(invalid_recorded_history(
13196                        "selection_resolution_event_mismatch",
13197                        member.base_sequence,
13198                        "failure event within selected member bounds",
13199                        &resolution_sequence.to_string(),
13200                        "selection failure event is outside the authored member",
13201                    )))
13202                }
13203            };
13204            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
13205            match leaf.outcome.take() {
13206                Some(Err(error)) => winner_failure = Some(error),
13207                _ => {
13208                    return Poll::Ready(Err(invalid_recorded_history(
13209                        "selection_winner_outcome_mismatch",
13210                        member.base_sequence,
13211                        "exact failed terminal history referenced by SelectionResolved",
13212                        "missing or successful resolution event",
13213                        "selection winner marker disagrees with terminal operation history",
13214                    )))
13215                }
13216            }
13217        } else {
13218            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
13219                match leaf.outcome.take() {
13220                    Some(Ok(result)) => flat_results.push(result),
13221                    Some(Err(_)) => {
13222                        return Poll::Ready(Err(invalid_recorded_history(
13223                            "selection_winner_outcome_mismatch",
13224                            member.base_sequence,
13225                            "fully completed nested selection member",
13226                            "failed durable leaf",
13227                            "completed selection winner contains a failed leaf",
13228                        )))
13229                    }
13230                    None => {
13231                        return Poll::Ready(Err(invalid_recorded_history(
13232                            "selection_winner_unresolved",
13233                            member.base_sequence,
13234                            "terminal history for every completed winner leaf",
13235                            "pending member history",
13236                            "completed SelectionResolved member has an unfinished durable barrier",
13237                        )))
13238                    }
13239                }
13240            }
13241        }
13242        let value = if winner_failure.is_none() {
13243            let mut flat_results = flat_results.into_iter();
13244            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
13245            match value.into_json_result() {
13246                Ok(value) => Some(value),
13247                Err(error) => return Poll::Ready(Err(error)),
13248            }
13249        } else {
13250            None
13251        };
13252        let winner = handles[member_position].clone();
13253        self.ctx
13254            .state
13255            .lock()
13256            .map_err(|_| Error::WorkflowStatePoisoned)?
13257            .advance_cancellation_selection(&marker.selection_group_id);
13258        Poll::Ready(Ok(SelectionResult {
13259            key: winner.key.clone(),
13260            index: winner.index,
13261            kind: winner.kind.clone(),
13262            identity: winner.identity.clone(),
13263            value,
13264            failure: winner_failure,
13265            winner,
13266            handles,
13267        }))
13268    }
13269}
13270
13271fn selection_operation_identity(
13272    state: &WorkflowState,
13273    kind: &str,
13274    base_sequence: u64,
13275    size: usize,
13276) -> String {
13277    if kind == "group" {
13278        return format!("group:{base_sequence}:{size}");
13279    }
13280    let fields: &[&str] = match kind {
13281        "activity" => &["activity_execution_id"],
13282        "child" => &["child_workflow_run_id"],
13283        "timer" => &["timer_id"],
13284        "signal" => &["signal_wait_id"],
13285        "condition" => &["condition_wait_id"],
13286        _ => &[],
13287    };
13288    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
13289        for event in state
13290            .history_events
13291            .iter()
13292            .filter(|event| durable_event_sequence(event) == Some(sequence))
13293        {
13294            for field in fields {
13295                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
13296                    if !identity.is_empty() {
13297                        return identity.to_string();
13298                    }
13299                }
13300            }
13301        }
13302    }
13303    String::new()
13304}
13305
13306fn validated_selection_resolution_sequence(
13307    state: &WorkflowState,
13308    marker: &SelectionMarker,
13309    member: &SelectionMemberPlan,
13310    expected_identity: &str,
13311) -> Result<u64> {
13312    if expected_identity.is_empty() {
13313        return Err(invalid_recorded_history(
13314            "selection_operation_identity_missing",
13315            member.base_sequence,
13316            &format!(
13317                "durable {} resource identity from scheduled/open history",
13318                member.kind
13319            ),
13320            "missing operation identity",
13321            "selection member history is missing its canonical durable identity",
13322        ));
13323    }
13324    if marker.operation_identity != expected_identity {
13325        return Err(invalid_recorded_history(
13326            "selection_operation_identity_mismatch",
13327            member.base_sequence,
13328            expected_identity,
13329            &marker.operation_identity,
13330            "selection winner identity does not match durable scheduled/open history",
13331        ));
13332    }
13333
13334    let failure_types = [
13335        "ActivityFailed",
13336        "ActivityCancelled",
13337        "ActivityTimedOut",
13338        "ChildRunFailed",
13339        "ChildRunCancelled",
13340        "ChildRunTerminated",
13341    ];
13342    let success_types = [
13343        "ActivityCompleted",
13344        "ChildRunCompleted",
13345        "TimerFired",
13346        "SignalApplied",
13347        "ConditionWaitSatisfied",
13348        "ConditionWaitTimedOut",
13349    ];
13350    let terminal_types: &[&str] = if marker.outcome == "failed" {
13351        &failure_types
13352    } else {
13353        &success_types
13354    };
13355    let mut candidates = Vec::new();
13356    let member_commands = (member.base_sequence
13357        ..member.base_sequence.saturating_add(member.size as u64))
13358        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
13359        .map(|command| (command.sequence(), command))
13360        .collect::<BTreeMap<_, _>>();
13361    let mut resolved_conditions = BTreeSet::new();
13362    for event in state.history_events.iter() {
13363        let Some(sequence) = durable_event_sequence(event) else {
13364            continue;
13365        };
13366        let Some(command) = member_commands.get(&sequence) else {
13367            continue;
13368        };
13369        if !terminal_types.contains(&event.event_type.as_str()) {
13370            continue;
13371        }
13372        if matches!(command, RecordedCommand::ConditionWait { .. }) {
13373            if !matches!(
13374                event.event_type.as_str(),
13375                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
13376            ) && !(event.event_type == "TimerFired"
13377                && event.payload.get("timer_kind").and_then(Value::as_str)
13378                    == Some("condition_timeout"))
13379            {
13380                continue;
13381            }
13382            if !resolved_conditions.insert(sequence) {
13383                continue;
13384            }
13385        }
13386        let event_id = event
13387            .raw
13388            .get("id")
13389            .or_else(|| event.raw.get("event_id"))
13390            .and_then(Value::as_str)
13391            .filter(|value| !value.is_empty())
13392            .ok_or_else(|| {
13393                invalid_recorded_history(
13394                    "selection_resolution_event_id_missing",
13395                    member.base_sequence,
13396                    "terminal selection history with a durable event id",
13397                    &event.payload.to_string(),
13398                    "selection terminal history cannot be bound to its winner marker",
13399                )
13400            })?;
13401        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
13402    }
13403    let resolution = if marker.outcome == "failed" {
13404        candidates.first()
13405    } else {
13406        candidates.last()
13407    };
13408    let Some((event_id, event_type, sequence)) = resolution else {
13409        return Err(invalid_recorded_history(
13410            "selection_resolution_event_missing",
13411            member.base_sequence,
13412            "terminal history for the selected member",
13413            &format!("{:?}", marker.member_key),
13414            "selection winner marker has no matching durable terminal event",
13415        ));
13416    };
13417    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
13418        return Err(invalid_recorded_history(
13419            "selection_resolution_event_mismatch",
13420            member.base_sequence,
13421            &format!("{event_type}:{event_id}"),
13422            &format!(
13423                "{}:{}",
13424                marker.resolution_event_type, marker.resolution_event_id
13425            ),
13426            "selection winner marker does not reference the event that made its member terminal",
13427        ));
13428    }
13429    Ok(*sequence)
13430}
13431
13432fn selection_member_recorded_command(
13433    state: &WorkflowState,
13434    authored_sequence: u64,
13435) -> Option<&RecordedCommand> {
13436    let original = state
13437        .recorded_commands
13438        .iter()
13439        .find(|command| command.sequence() == authored_sequence)?;
13440    let RecordedCommand::ConditionWait {
13441        occurrence_id,
13442        parallel_group_path: Some(_),
13443        ..
13444    } = original
13445    else {
13446        return Some(original);
13447    };
13448    // Decoding proves each physical reopen has the same authored identity and
13449    // group path after a satisfied predecessor. Only its latest wait can make
13450    // this logical member terminal.
13451    state
13452        .recorded_commands
13453        .iter()
13454        .filter(|command| {
13455            matches!(command, RecordedCommand::ConditionWait {
13456                occurrence_id: candidate, ..
13457            } if candidate == occurrence_id)
13458        })
13459        .max_by_key(|command| command.sequence())
13460}
13461
13462fn recorded_selection_member_outcome(
13463    state: &WorkflowState,
13464    handle: &DurableOperationHandle,
13465) -> Result<Option<ParallelResult>> {
13466    for event in state.history_events.iter() {
13467        let Some(sequence) = durable_event_sequence(event) else {
13468            continue;
13469        };
13470        if sequence < handle.base_sequence
13471            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
13472            || !matches!(
13473                event.event_type.as_str(),
13474                "ActivityFailed"
13475                    | "ActivityCancelled"
13476                    | "ActivityTimedOut"
13477                    | "ChildRunFailed"
13478                    | "ChildRunCancelled"
13479                    | "ChildRunTerminated"
13480            )
13481        {
13482            continue;
13483        }
13484        let Some(command) = state
13485            .recorded_commands
13486            .iter()
13487            .find(|command| command.sequence() == sequence)
13488        else {
13489            continue;
13490        };
13491        match command {
13492            RecordedCommand::Activity {
13493                outcome: Some(Err(failure)),
13494                ..
13495            } => return Err(Error::ActivityFailed(failure.clone())),
13496            RecordedCommand::ChildWorkflow {
13497                outcome: Some(Err(failure)),
13498                ..
13499            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
13500            _ => {}
13501        }
13502    }
13503
13504    let mut results = Vec::with_capacity(handle.size);
13505    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13506        let Some(command) = selection_member_recorded_command(state, sequence) else {
13507            return Ok(None);
13508        };
13509        let result = match command {
13510            RecordedCommand::Activity { outcome, .. } => match outcome {
13511                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
13512                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
13513                None => return Ok(None),
13514            },
13515            RecordedCommand::Timer { fired, .. } => {
13516                if !fired {
13517                    return Ok(None);
13518                }
13519                ParallelAvroResult::Timer
13520            }
13521            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
13522                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
13523                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
13524                None => return Ok(None),
13525            },
13526            RecordedCommand::SignalWait { value, .. } => match value {
13527                Some(value) => ParallelAvroResult::Signal(value.clone()),
13528                None => return Ok(None),
13529            },
13530            RecordedCommand::ConditionWait { result, .. } => match result {
13531                Some(result) => ParallelAvroResult::Condition(*result),
13532                None => return Ok(None),
13533            },
13534            other => {
13535                return Err(command_mismatch(
13536                    other,
13537                    format!("selected {} member", handle.kind),
13538                ))
13539            }
13540        };
13541        results.push(result);
13542    }
13543    let mut results = results.into_iter();
13544    parallel_results_for_shape(&handle.shape, &mut results)
13545        .into_json_result()
13546        .map(Some)
13547}
13548
13549fn recorded_selection_member_is_terminal(
13550    state: &WorkflowState,
13551    handle: &DurableOperationHandle,
13552) -> bool {
13553    let mut completed = 0usize;
13554    let mut all_completed = true;
13555    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13556        let Some(command) = selection_member_recorded_command(state, sequence) else {
13557            all_completed = false;
13558            continue;
13559        };
13560        let terminal = match command {
13561            RecordedCommand::Activity {
13562                outcome: Some(Err(_)),
13563                ..
13564            }
13565            | RecordedCommand::ChildWorkflow {
13566                outcome: Some(Err(_)),
13567                ..
13568            } => return true,
13569            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13570            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13571            RecordedCommand::Timer { fired, .. } => *fired,
13572            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13573            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13574            RecordedCommand::SearchAttributes { .. }
13575            | RecordedCommand::CancellationScope { .. }
13576            | RecordedCommand::SideEffect { .. }
13577            | RecordedCommand::VersionMarker { .. }
13578            | RecordedCommand::Memo { .. }
13579            | RecordedCommand::CancellationBoundary { .. }
13580            | RecordedCommand::CancellationGroup { .. } => false,
13581        };
13582        if !terminal {
13583            all_completed = false;
13584            continue;
13585        }
13586        completed += 1;
13587    }
13588    all_completed && completed == handle.size
13589}
13590
13591fn selection_cancellation_for_handle(
13592    state: &WorkflowState,
13593    handle: &DurableOperationHandle,
13594) -> Result<bool> {
13595    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13596        recorded.selection_group_id == handle.selection_group_id
13597            && recorded.member_base_sequence == handle.base_sequence
13598    }) else {
13599        return Ok(false);
13600    };
13601    validate_selection_cancellation_marker(marker, handle)?;
13602    Ok(true)
13603}
13604
13605fn validate_selection_cancellations_for_handles(
13606    state: &WorkflowState,
13607    handles: &[DurableOperationHandle],
13608) -> Result<()> {
13609    let Some(group_id) = handles
13610        .first()
13611        .map(|handle| handle.selection_group_id.as_str())
13612    else {
13613        return Ok(());
13614    };
13615    for marker in state
13616        .cancelled_selection_members
13617        .iter()
13618        .filter(|marker| marker.selection_group_id == group_id)
13619    {
13620        let Some(handle) = handles
13621            .iter()
13622            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13623        else {
13624            return Err(invalid_recorded_history(
13625                "selection_cancellation_member_mismatch",
13626                marker.member_base_sequence,
13627                "SelectionOperationCancelled matching an authored selection handle",
13628                &format!("{marker:?}"),
13629                "selection cancellation member base does not name an authored member",
13630            ));
13631        };
13632        validate_selection_cancellation_marker(marker, handle)?;
13633    }
13634    Ok(())
13635}
13636
13637fn validate_selection_cancellation_marker(
13638    marker: &SelectionCancellation,
13639    handle: &DurableOperationHandle,
13640) -> Result<()> {
13641    if marker.selection_group_id != handle.selection_group_id
13642        || marker.member_key != handle.key
13643        || marker.member_index != handle.index
13644        || marker.member_base_sequence != handle.base_sequence
13645        || marker.member_size != handle.size
13646        || marker.operation_kind != handle.kind
13647        || marker.operation_identity != handle.identity
13648    {
13649        return Err(invalid_recorded_history(
13650            "selection_cancellation_member_mismatch",
13651            handle.base_sequence,
13652            "SelectionOperationCancelled matching the authored selection handle",
13653            &format!("{marker:?}"),
13654            "selection cancellation history targets different authored member metadata",
13655        ));
13656    }
13657    Ok(())
13658}
13659
13660/// Future returned by [`DurableOperationHandle::await_result`].
13661pub struct DurableOperationAwaitCall {
13662    handle: DurableOperationHandle,
13663}
13664
13665impl Future for DurableOperationAwaitCall {
13666    type Output = Result<ParallelResult>;
13667
13668    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13669        let mut state = match self.handle.ctx.state.lock() {
13670            Ok(state) => state,
13671            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13672        };
13673        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13674            return Poll::Ready(Err(error));
13675        }
13676        match state.prepare_selection_handle_cancellation(&self.handle) {
13677            Ok(true) => return Poll::Pending,
13678            Ok(false) => {}
13679            Err(error) => return Poll::Ready(Err(error)),
13680        }
13681        match selection_cancellation_for_handle(&state, &self.handle) {
13682            Err(error) => return Poll::Ready(Err(error)),
13683            Ok(false) => {}
13684            Ok(true) => {
13685                state.advance_cancellation_receipt(
13686                    &self.handle.selection_group_id,
13687                    self.handle.base_sequence,
13688                );
13689                return Poll::Ready(Err(Error::DurableOperationCancelled(
13690                    DurableOperationCancelled {
13691                        selection_group_id: self.handle.selection_group_id.clone(),
13692                        member_key: self.handle.key.clone(),
13693                        member_index: self.handle.index,
13694                        operation_kind: self.handle.kind.clone(),
13695                        operation_identity: self.handle.identity.clone(),
13696                    },
13697                )));
13698            }
13699        }
13700        match recorded_selection_member_outcome(&state, &self.handle) {
13701            Ok(Some(result)) => {
13702                state.advance_cancellation_handle(&self.handle, false);
13703                Poll::Ready(Ok(result))
13704            }
13705            Ok(None) => Poll::Pending,
13706            Err(error) => {
13707                if !workflow_task_integrity_error(&error) {
13708                    state.advance_cancellation_handle(&self.handle, true);
13709                }
13710                Poll::Ready(Err(error))
13711            }
13712        }
13713    }
13714}
13715
13716fn validate_selection_delivery_handle(
13717    state: &WorkflowState,
13718    handle: &DurableOperationHandle,
13719) -> Result<()> {
13720    let path = state
13721        .recorded_commands
13722        .iter()
13723        .find(|command| command.sequence() == handle.base_sequence)
13724        .and_then(|command| match command {
13725            RecordedCommand::Activity {
13726                parallel_group_path,
13727                ..
13728            }
13729            | RecordedCommand::ChildWorkflow {
13730                parallel_group_path,
13731                ..
13732            }
13733            | RecordedCommand::Timer {
13734                parallel_group_path,
13735                ..
13736            }
13737            | RecordedCommand::SignalWait {
13738                parallel_group_path,
13739                ..
13740            }
13741            | RecordedCommand::ConditionWait {
13742                parallel_group_path,
13743                ..
13744            } => parallel_group_path.as_ref(),
13745            _ => None,
13746        })
13747        .and_then(|path| path.first());
13748    let matches = path.is_some_and(|entry| {
13749        entry.parallel_group_mode.as_deref() == Some("select")
13750            && entry.parallel_group_id == handle.selection_group_id
13751            && entry.selection_member_key.as_ref() == Some(&handle.key)
13752            && entry.selection_member_index == Some(handle.index)
13753            && entry.selection_member_base_sequence == Some(handle.base_sequence)
13754            && entry.selection_member_size == Some(handle.size)
13755            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
13756    });
13757    if !matches
13758        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
13759            != handle.identity
13760    {
13761        return Err(invalid_recorded_history(
13762            "cooperative_cancellation_call_mismatch",
13763            handle.base_sequence,
13764            "selection handle matching its authored durable identity",
13765            &format!("{handle:?}"),
13766            "selection handle identity or member metadata changed before cancellation replay",
13767        ));
13768    }
13769    Ok(())
13770}
13771
13772/// Future returned by [`DurableOperationHandle::cancel`].
13773pub struct CancelDurableOperationCall {
13774    handle: DurableOperationHandle,
13775    emitted: bool,
13776}
13777
13778impl Future for CancelDurableOperationCall {
13779    type Output = Result<()>;
13780
13781    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13782        let ctx = self.handle.ctx.clone();
13783        let mut state = match ctx.state.lock() {
13784            Ok(state) => state,
13785            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13786        };
13787        match selection_cancellation_for_handle(&state, &self.handle) {
13788            Err(error) => return Poll::Ready(Err(error)),
13789            Ok(true) => {
13790                state.advance_cancellation_receipt(
13791                    &self.handle.selection_group_id,
13792                    self.handle.base_sequence,
13793                );
13794                return Poll::Ready(Ok(()));
13795            }
13796            Ok(false) => {}
13797        }
13798        if recorded_selection_member_is_terminal(&state, &self.handle) {
13799            return Poll::Ready(Ok(()));
13800        }
13801        if !self.emitted {
13802            state.commands.push(json!({
13803                "type": "cancel_selection_operation",
13804                "selection_group_id": self.handle.selection_group_id,
13805                "member_key": self.handle.key,
13806                "member_index": self.handle.index,
13807                "member_base_sequence": self.handle.base_sequence,
13808                "member_size": self.handle.size,
13809                "operation_kind": self.handle.kind,
13810                "operation_identity": self.handle.identity,
13811            }));
13812            self.emitted = true;
13813        }
13814        // The cancellation command is only a request. Do not expose workflow
13815        // state after cancel until committed SelectionOperationCancelled
13816        // history proves that the request won the race with member completion.
13817        Poll::Pending
13818    }
13819}
13820
13821trait PollNestedResultExt<T> {
13822    fn flatten_result(self) -> Poll<Result<T>>;
13823}
13824
13825impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
13826    fn flatten_result(self) -> Poll<Result<T>> {
13827        match self {
13828            Poll::Ready(Ok(result)) => Poll::Ready(result),
13829            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13830            Poll::Pending => Poll::Pending,
13831        }
13832    }
13833}
13834
13835struct SagaCompensation {
13836    activity_type: String,
13837    options: ActivityOptions,
13838    arguments: AvroValue,
13839    registration_order: usize,
13840}
13841
13842/// Workflow-local deterministic saga compensation helper.
13843///
13844/// Register each compensation only after its forward step succeeds. Passing
13845/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
13846/// reverse registration order after any failure, including cooperative
13847/// cancellation. Each compensation is an ordinary durable activity, so replay,
13848/// duplicate delivery, and worker restart use existing history semantics.
13849pub struct Saga {
13850    ctx: WorkflowContext,
13851    compensations: Vec<SagaCompensation>,
13852}
13853
13854impl Saga {
13855    fn new(ctx: WorkflowContext) -> Self {
13856        Self {
13857            ctx,
13858            compensations: Vec::new(),
13859        }
13860    }
13861
13862    pub fn add_compensation<T: Serialize>(
13863        &mut self,
13864        activity_type: impl Into<String>,
13865        args: T,
13866    ) -> Result<&mut Self> {
13867        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
13868    }
13869
13870    pub fn add_compensation_with_options<T: Serialize>(
13871        &mut self,
13872        activity_type: impl Into<String>,
13873        options: ActivityOptions,
13874        args: T,
13875    ) -> Result<&mut Self> {
13876        let activity_type = activity_type.into();
13877        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
13878            return Err(Error::Codec(
13879                "saga compensation activity type must be non-empty without surrounding whitespace"
13880                    .to_string(),
13881            ));
13882        }
13883        options.validate().map_err(Error::InvalidActivityOptions)?;
13884        let arguments = AvroValue::from_serialize(&args)?;
13885        let registration_order = self.compensations.len() + 1;
13886        self.compensations.push(SagaCompensation {
13887            activity_type,
13888            options,
13889            arguments,
13890            registration_order,
13891        });
13892        Ok(self)
13893    }
13894
13895    /// Compensate `initiating_failure` and return the failure that must remain.
13896    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
13897        let _shield = match self.ctx.cancellation_shield() {
13898            Ok(shield) => shield,
13899            Err(error) => return error,
13900        };
13901        while let Some(compensation) = self.compensations.pop() {
13902            if let Err(compensation_failure) = self
13903                .ctx
13904                .activity_with_options(
13905                    compensation.activity_type.clone(),
13906                    compensation.options,
13907                    compensation.arguments,
13908                )
13909                .await
13910            {
13911                if workflow_task_integrity_error(&compensation_failure) {
13912                    return compensation_failure;
13913                }
13914                return Error::SagaCompensationFailed(SagaCompensationFailure {
13915                    initiating_failure: Box::new(initiating_failure),
13916                    compensation_failure: Box::new(compensation_failure),
13917                    compensation_activity_type: compensation.activity_type,
13918                    compensation_registration_order: compensation.registration_order,
13919                });
13920            }
13921        }
13922        initiating_failure
13923    }
13924
13925    /// Return a successful forward value or compensate and preserve its failure.
13926    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
13927        match outcome {
13928            Ok(value) => Ok(value),
13929            Err(error) => Err(self.compensate(error).await),
13930        }
13931    }
13932}
13933
13934pub struct ActivityCall {
13935    ctx: WorkflowContext,
13936    activity_type: String,
13937    options: ActivityOptions,
13938    worker_session: Option<WorkerSessionOptions>,
13939    args: Option<Result<AvroValue>>,
13940    scheduled: bool,
13941    local: bool,
13942    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
13943    parallel_group_path: Vec<ParallelGroupMetadata>,
13944}
13945
13946impl ActivityCall {
13947    fn poll_avro_value(
13948        mut self: Pin<&mut Self>,
13949        _cx: &mut TaskContext<'_>,
13950    ) -> Poll<Result<AvroValue>> {
13951        let ctx = self.ctx.clone();
13952        let mut state = match ctx.state.lock() {
13953            Ok(state) => state,
13954            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13955        };
13956
13957        if let Some(result) = &self.local_result {
13958            return match result.lock() {
13959                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
13960                    Poll::Ready(result.map_err(Error::ActivityFailed))
13961                }),
13962                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13963            };
13964        }
13965        if self.scheduled {
13966            return Poll::Pending;
13967        }
13968
13969        let options = match self.options.validate() {
13970            Ok(options) => options,
13971            Err(error) => {
13972                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
13973            }
13974        };
13975        if self.local {
13976            if self.worker_session.is_some() {
13977                return Poll::Ready(Err(Error::WorkerLoop(
13978                    "local activities cannot use worker-session routing".into(),
13979                )));
13980            }
13981            if let Err(error) = local_activity::validate(&options) {
13982                return Poll::Ready(Err(error));
13983            }
13984        }
13985        let session = match self
13986            .worker_session
13987            .as_ref()
13988            .map(WorkerSessionOptions::to_wire)
13989            .transpose()
13990        {
13991            Ok(value) => value,
13992            Err(error) => return Poll::Ready(Err(error)),
13993        };
13994        let session_queue = session
13995            .as_ref()
13996            .and_then(|session| session["queue"].as_str());
13997        let task_queue = options
13998            .task_queue
13999            .clone()
14000            .or_else(|| session_queue.map(str::to_owned))
14001            .unwrap_or_else(|| state.task_queue.clone());
14002        if session_queue.is_some_and(|queue| queue != task_queue) {
14003            return Poll::Ready(Err(Error::WorkerLoop(
14004                "worker-session queue must match the activity task queue".into(),
14005            )));
14006        }
14007        let current_recorded_options = RecordedActivityOptions {
14008            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
14009            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
14010            retry_policy: current_activity_retry_snapshot(&options),
14011            worker_session: session,
14012        };
14013
14014        let cursor = state.command_cursor;
14015        let call_kind = if self.local {
14016            CancellationCallKind::LocalActivity
14017        } else {
14018            CancellationCallKind::Activity
14019        };
14020        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14021            return Poll::Ready(Err(error));
14022        }
14023        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
14024            Ok(recorded) => recorded,
14025            Err(error) => return Poll::Ready(Err(error)),
14026        };
14027        if let Some(recorded) = recorded {
14028            let sequence = recorded.sequence();
14029            match recorded {
14030                RecordedCommand::Activity {
14031                    activity_type,
14032                    cancellation_policy,
14033                    options: recorded_options,
14034                    outcome,
14035                    parallel_group_path,
14036                    ..
14037                } => {
14038                    let current_policy = options
14039                        .cancellation_policy
14040                        .unwrap_or(CancellationPolicy::TryCancel)
14041                        .as_str();
14042                    if cancellation_policy != current_policy {
14043                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14044                            ReplayFailure::new(
14045                                "activity_cancellation_policy_changed",
14046                                Some(sequence),
14047                                Some(cancellation_policy),
14048                                Some(current_policy.to_string()),
14049                                "Activity cancellation policy changed during replay",
14050                            ),
14051                        )));
14052                    }
14053                    if let Err(error) = ensure_parallel_path_matches(
14054                        sequence,
14055                        parallel_group_path.as_deref(),
14056                        &self.parallel_group_path,
14057                    ) {
14058                        return Poll::Ready(Err(error));
14059                    }
14060                    if let Some(recorded_type) = activity_type {
14061                        if recorded_type != self.activity_type {
14062                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14063                                ReplayFailure::new(
14064                                    "recorded_command_detail_mismatch",
14065                                    Some(sequence),
14066                                    Some(format!("activity:{recorded_type}")),
14067                                    Some(format!("activity:{}", self.activity_type)),
14068                                    "recorded activity type differs from the current workflow command",
14069                                ),
14070                            )));
14071                        }
14072                    }
14073                    if let Some(recorded_options) = recorded_options {
14074                        if recorded_options.worker_session
14075                            != current_recorded_options.worker_session
14076                        {
14077                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14078                                "activity_worker_session_mismatch", Some(sequence),
14079                                Some(activity_options_description(&recorded_options)),
14080                                Some(activity_options_description(&current_recorded_options)),
14081                                "recorded worker-session routing differs from the current activity",
14082                            ))));
14083                        }
14084                        if !recorded_options
14085                            .task_queue
14086                            .matches_current(&current_recorded_options.task_queue)
14087                        {
14088                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14089                                ReplayFailure::new(
14090                                    "activity_task_queue_mismatch",
14091                                    Some(sequence),
14092                                    Some(activity_options_description(&recorded_options)),
14093                                    Some(activity_options_description(&current_recorded_options)),
14094                                    "recorded activity task queue differs from the current workflow command",
14095                                ),
14096                            )));
14097                        }
14098                        if (self.local
14099                            && matches!(
14100                                recorded_options.execution_mode,
14101                                RecordedSnapshotValue::Unknown
14102                            ))
14103                            || !recorded_options
14104                                .execution_mode
14105                                .matches_current(&current_recorded_options.execution_mode)
14106                        {
14107                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14108                                ReplayFailure::new(
14109                                    "activity_execution_mode_mismatch",
14110                                    Some(sequence),
14111                                    Some(activity_options_description(&recorded_options)),
14112                                    Some(activity_options_description(&current_recorded_options)),
14113                                    "recorded activity execution mode differs from the current workflow command",
14114                                ),
14115                            )));
14116                        }
14117                        if !recorded_options
14118                            .retry_policy
14119                            .matches_current(&current_recorded_options.retry_policy)
14120                        {
14121                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14122                                ReplayFailure::new(
14123                                    "activity_retry_policy_mismatch",
14124                                    Some(sequence),
14125                                    Some(activity_options_description(&recorded_options)),
14126                                    Some(activity_options_description(&current_recorded_options)),
14127                                    "recorded activity retry policy differs from the current workflow command",
14128                                ),
14129                            )));
14130                        }
14131                    }
14132                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
14133                        return Poll::Ready(Err(error));
14134                    }
14135                    match state.prepare_scalar_cancellation(
14136                        cursor,
14137                        call_kind,
14138                        &self.parallel_group_path,
14139                    ) {
14140                        Ok(true) => {
14141                            self.scheduled = true;
14142                            return Poll::Pending;
14143                        }
14144                        Ok(false) => {}
14145                        Err(error) => return Poll::Ready(Err(error)),
14146                    }
14147                    state.command_cursor += 1;
14148                    if let Some(outcome) = outcome {
14149                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14150                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
14151                    }
14152                    state.matched_recorded_pending = true;
14153                    self.scheduled = true;
14154                    return Poll::Pending;
14155                }
14156                other => {
14157                    return Poll::Ready(Err(command_mismatch(
14158                        &other,
14159                        format!("activity:{}", self.activity_type),
14160                    )));
14161                }
14162            }
14163        }
14164
14165        if !self.scheduled {
14166            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14167                Ok(args) => args,
14168                Err(error) => return Poll::Ready(Err(error)),
14169            };
14170            let arguments = normalize_avro_arguments(args);
14171            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
14172                Ok(envelope) => envelope,
14173                Err(error) => return Poll::Ready(Err(error)),
14174            };
14175
14176            let mut command = serde_json::Map::from_iter([
14177                (
14178                    "type".to_string(),
14179                    json!(if self.local {
14180                        "record_local_activity"
14181                    } else {
14182                        "schedule_activity"
14183                    }),
14184                ),
14185                (
14186                    "activity_type".to_string(),
14187                    json!(self.activity_type.clone()),
14188                ),
14189                ("queue".to_string(), json!(task_queue)),
14190                ("arguments".to_string(), envelope),
14191            ]);
14192            for (field, value) in [
14193                ("start_to_close_timeout", options.start_to_close_timeout),
14194                (
14195                    "schedule_to_start_timeout",
14196                    options.schedule_to_start_timeout,
14197                ),
14198                (
14199                    "schedule_to_close_timeout",
14200                    options.schedule_to_close_timeout,
14201                ),
14202                ("heartbeat_timeout", options.heartbeat_timeout),
14203            ] {
14204                if let Some(value) = value {
14205                    command.insert(field.to_string(), json!(value));
14206                }
14207            }
14208            if let Some(retry_policy) = &options.retry_policy {
14209                command.insert("retry_policy".to_string(), retry_policy.clone());
14210            }
14211            if let Some(policy) = options.cancellation_policy {
14212                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
14213            }
14214            if let Some(session) = current_recorded_options.worker_session {
14215                command.insert("worker_session".into(), session);
14216            }
14217            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14218            ctx.apply_scope_membership(&mut command);
14219            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
14220                Ok(true) => {
14221                    self.scheduled = true;
14222                    return Poll::Pending;
14223                }
14224                Ok(false) => {}
14225                Err(error) => return Poll::Ready(Err(error)),
14226            }
14227            if self.local {
14228                command.remove("queue");
14229                command.insert("execution_mode".into(), json!("local"));
14230                let result = Arc::new(Mutex::new(None));
14231                let command_index = state.commands.len();
14232                state.local_activity_requests.push(local_activity::Request {
14233                    command_index,
14234                    options,
14235                    arguments,
14236                    result: result.clone(),
14237                });
14238                self.local_result = Some(result);
14239            }
14240            state.commands.push(Value::Object(command));
14241            self.scheduled = true;
14242        }
14243
14244        Poll::Pending
14245    }
14246}
14247
14248impl Future for ActivityCall {
14249    type Output = Result<Value>;
14250
14251    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14252        match self.poll_avro_value(cx) {
14253            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
14254            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14255            Poll::Pending => Poll::Pending,
14256        }
14257    }
14258}
14259
14260/// Future returned by [`WorkflowContext::sleep`].
14261pub struct TimerCall {
14262    ctx: WorkflowContext,
14263    delay_seconds: Option<u64>,
14264    scheduled: bool,
14265    matched_pending: bool,
14266    parallel_group_path: Vec<ParallelGroupMetadata>,
14267}
14268
14269impl Future for TimerCall {
14270    type Output = Result<()>;
14271
14272    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14273        if self.matched_pending {
14274            return Poll::Pending;
14275        }
14276
14277        let ctx = self.ctx.clone();
14278        let Some(requested_delay) = self.delay_seconds else {
14279            return Poll::Ready(Err(Error::TimerDurationOverflow));
14280        };
14281        let mut state = match ctx.state.lock() {
14282            Ok(state) => state,
14283            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14284        };
14285
14286        let cursor = state.command_cursor;
14287        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14288            return Poll::Ready(Err(error));
14289        }
14290        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
14291        {
14292            Ok(recorded) => recorded,
14293            Err(error) => return Poll::Ready(Err(error)),
14294        };
14295        if let Some(recorded) = recorded {
14296            match recorded {
14297                RecordedCommand::Timer {
14298                    sequence,
14299                    delay_seconds,
14300                    fired,
14301                    parallel_group_path,
14302                    ..
14303                } => {
14304                    if let Err(error) =
14305                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
14306                    {
14307                        return Poll::Ready(Err(error));
14308                    }
14309                    if let Err(error) = ensure_parallel_path_matches(
14310                        sequence,
14311                        parallel_group_path.as_deref(),
14312                        &self.parallel_group_path,
14313                    ) {
14314                        return Poll::Ready(Err(error));
14315                    }
14316                    if delay_seconds != requested_delay {
14317                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14318                            ReplayFailure::new(
14319                                "timer_delay_mismatch",
14320                                Some(sequence),
14321                                Some(format!("timer:{delay_seconds}s")),
14322                                Some(format!("timer:{requested_delay}s")),
14323                                "recorded timer delay differs from the current workflow command",
14324                            ),
14325                        )));
14326                    }
14327                    if let Err(error) =
14328                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
14329                    {
14330                        return Poll::Ready(Err(error));
14331                    }
14332                    match state.prepare_scalar_cancellation(
14333                        cursor,
14334                        CancellationCallKind::Timer,
14335                        &self.parallel_group_path,
14336                    ) {
14337                        Ok(true) => {
14338                            self.scheduled = true;
14339                            self.matched_pending = true;
14340                            return Poll::Pending;
14341                        }
14342                        Ok(false) => {}
14343                        Err(error) => return Poll::Ready(Err(error)),
14344                    }
14345                    state.command_cursor += 1;
14346                    if fired {
14347                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14348                        return Poll::Ready(Ok(()));
14349                    }
14350                    state.matched_recorded_pending = true;
14351                    self.scheduled = true;
14352                    self.matched_pending = true;
14353                    return Poll::Pending;
14354                }
14355                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
14356            }
14357        }
14358
14359        if !self.scheduled {
14360            let mut command = serde_json::Map::from_iter([
14361                ("type".to_string(), json!("start_timer")),
14362                ("delay_seconds".to_string(), json!(requested_delay)),
14363            ]);
14364            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
14365                Ok(Some(proof)) => {
14366                    command.insert("cancellation_cleanup".into(), proof);
14367                }
14368                Ok(None) => {}
14369                Err(error) => return Poll::Ready(Err(error)),
14370            }
14371            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14372            ctx.apply_scope_membership(&mut command);
14373            match state.prepare_scalar_cancellation(
14374                cursor,
14375                CancellationCallKind::Timer,
14376                &self.parallel_group_path,
14377            ) {
14378                Ok(true) => {
14379                    self.scheduled = true;
14380                    self.matched_pending = true;
14381                    return Poll::Pending;
14382                }
14383                Ok(false) => {}
14384                Err(error) => return Poll::Ready(Err(error)),
14385            }
14386            state.commands.push(Value::Object(command));
14387            self.scheduled = true;
14388        }
14389
14390        Poll::Pending
14391    }
14392}
14393
14394/// Future returned by [`WorkflowContext::wait_condition`].
14395pub struct ConditionWaitCall {
14396    ctx: WorkflowContext,
14397    options: ConditionWaitOptions,
14398    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
14399    occurrence_id: Option<String>,
14400    opened_wait: bool,
14401    parallel_group_path: Vec<ParallelGroupMetadata>,
14402}
14403
14404impl Future for ConditionWaitCall {
14405    type Output = Result<ConditionWaitResult>;
14406
14407    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14408        if self.opened_wait {
14409            return Poll::Pending;
14410        }
14411
14412        let options = match self.options.validate() {
14413            Ok(options) => options,
14414            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
14415        };
14416        let ctx = self.ctx.clone();
14417        let occurrence_id = match self.occurrence_id.as_ref() {
14418            Some(occurrence_id) => occurrence_id.clone(),
14419            None => {
14420                let mut state = match ctx.state.lock() {
14421                    Ok(state) => state,
14422                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14423                };
14424                let ordinal = state.condition_wait_occurrence_counter;
14425                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
14426                    Some(next) => next,
14427                    None => {
14428                        return Poll::Ready(Err(Error::WorkerLoop(
14429                            "condition wait occurrence counter overflowed".to_string(),
14430                        )))
14431                    }
14432                };
14433                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
14434                drop(state);
14435                self.occurrence_id = Some(occurrence_id.clone());
14436                occurrence_id
14437            }
14438        };
14439
14440        let recorded_result = {
14441            let mut state = match ctx.state.lock() {
14442                Ok(state) => state,
14443                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14444            };
14445            let initial_cursor = state.command_cursor;
14446            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
14447                return Poll::Ready(Err(error));
14448            }
14449            let recorded = match state
14450                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
14451            {
14452                Ok(recorded) => recorded,
14453                Err(error) => return Poll::Ready(Err(error)),
14454            };
14455            let Some(recorded) = recorded else {
14456                drop(state);
14457                return self.poll_new_condition(options);
14458            };
14459            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
14460                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
14461            }
14462
14463            let mut cursor = state.command_cursor;
14464            let mut result = None;
14465            let mut pending_delivery = false;
14466            loop {
14467                if cursor > initial_cursor
14468                    && matches!(
14469                        state.recorded_commands.get(cursor),
14470                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
14471                    )
14472                {
14473                    break;
14474                }
14475                let recorded = match state
14476                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
14477                {
14478                    Ok(recorded) => recorded,
14479                    Err(error) => return Poll::Ready(Err(error)),
14480                };
14481                let Some(RecordedCommand::ConditionWait {
14482                    sequence,
14483                    occurrence_id: ref recorded_occurrence_id,
14484                    ref condition_key,
14485                    ref predicate_identity,
14486                    timeout_seconds,
14487                    result: recorded_result,
14488                    ref parallel_group_path,
14489                    ..
14490                }) = recorded
14491                else {
14492                    break;
14493                };
14494
14495                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
14496                    break;
14497                }
14498                if let Err(error) = ensure_parallel_path_matches(
14499                    sequence,
14500                    parallel_group_path.as_deref(),
14501                    &self.parallel_group_path,
14502                ) {
14503                    return Poll::Ready(Err(error));
14504                }
14505                if let Err(error) = validate_recorded_condition_wait(
14506                    sequence,
14507                    recorded_occurrence_id,
14508                    condition_key.as_deref(),
14509                    predicate_identity,
14510                    timeout_seconds,
14511                    &occurrence_id,
14512                    &options,
14513                ) {
14514                    return Poll::Ready(Err(error));
14515                }
14516                if result == Some(ConditionWaitResult::TimedOut) {
14517                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14518                        "condition_wait_reopened_after_timeout",
14519                        Some(sequence),
14520                        Some("timed-out condition is terminal".to_string()),
14521                        Some("another physical wait-open".to_string()),
14522                        "condition history reopened one logical wait after its durable timeout",
14523                    ))));
14524                }
14525                if let Err(error) =
14526                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
14527                {
14528                    return Poll::Ready(Err(error));
14529                }
14530                match state.prepare_scalar_cancellation(
14531                    cursor,
14532                    CancellationCallKind::Condition,
14533                    &self.parallel_group_path,
14534                ) {
14535                    Ok(pending) => pending_delivery |= pending,
14536                    Err(error) => return Poll::Ready(Err(error)),
14537                }
14538                result = recorded_result;
14539                if result.is_some() {
14540                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14541                }
14542                cursor += 1;
14543            }
14544            state.command_cursor = cursor;
14545            if pending_delivery {
14546                self.opened_wait = true;
14547                return Poll::Pending;
14548            }
14549            result
14550        };
14551
14552        if let Some(result) = recorded_result {
14553            return Poll::Ready(Ok(result));
14554        }
14555
14556        self.poll_open_condition(options, true)
14557    }
14558}
14559
14560impl ConditionWaitCall {
14561    fn poll_new_condition(
14562        self: Pin<&mut Self>,
14563        options: ValidatedConditionWaitOptions,
14564    ) -> Poll<Result<ConditionWaitResult>> {
14565        self.poll_open_condition(options, false)
14566    }
14567
14568    fn poll_open_condition(
14569        mut self: Pin<&mut Self>,
14570        options: ValidatedConditionWaitOptions,
14571        recorded_wait: bool,
14572    ) -> Poll<Result<ConditionWaitResult>> {
14573        {
14574            let ctx = self.ctx.clone();
14575            let mut state = match ctx.state.lock() {
14576                Ok(state) => state,
14577                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14578            };
14579            let cursor = state.command_cursor;
14580            match state.prepare_scalar_cancellation(
14581                cursor,
14582                CancellationCallKind::Condition,
14583                &self.parallel_group_path,
14584            ) {
14585                Ok(true) => {
14586                    self.opened_wait = true;
14587                    return Poll::Pending;
14588                }
14589                Ok(false) => {}
14590                Err(error) => return Poll::Ready(Err(error)),
14591            }
14592        }
14593        let selection_member = self
14594            .parallel_group_path
14595            .first()
14596            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14597        match (self.predicate)() {
14598            Ok(true) if !selection_member || recorded_wait => {
14599                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14600            }
14601            Ok(_) => {}
14602            Err(error) => return Poll::Ready(Err(error)),
14603        }
14604        if options.timeout_seconds == Some(0) && !selection_member {
14605            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14606        }
14607
14608        let ctx = self.ctx.clone();
14609        let mut state = match ctx.state.lock() {
14610            Ok(state) => state,
14611            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14612        };
14613        let mut command = serde_json::Map::from_iter([
14614            ("type".to_string(), json!("open_condition_wait")),
14615            (
14616                "condition_wait_occurrence_id".to_string(),
14617                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14618            ),
14619            ("condition_key".to_string(), json!(options.condition_key)),
14620            (
14621                "condition_definition_fingerprint".to_string(),
14622                json!(options.predicate_identity),
14623            ),
14624        ]);
14625        if let Some(timeout_seconds) = options.timeout_seconds {
14626            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14627        }
14628        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14629        ctx.apply_scope_membership(&mut command);
14630        state.commands.push(Value::Object(command));
14631        drop(state);
14632        self.opened_wait = true;
14633        Poll::Pending
14634    }
14635}
14636
14637fn validate_recorded_condition_wait(
14638    sequence: u64,
14639    recorded_occurrence_id: &str,
14640    recorded_key: Option<&str>,
14641    recorded_predicate_identity: &str,
14642    recorded_timeout_seconds: Option<u64>,
14643    current_occurrence_id: &str,
14644    current: &ValidatedConditionWaitOptions,
14645) -> Result<()> {
14646    if recorded_occurrence_id != current_occurrence_id {
14647        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14648            "condition_wait_occurrence_mismatch",
14649            Some(sequence),
14650            Some(recorded_occurrence_id.to_string()),
14651            Some(current_occurrence_id.to_string()),
14652            "recorded condition occurrence differs from the current authored wait position",
14653        )));
14654    }
14655    if recorded_key != Some(current.condition_key.as_str()) {
14656        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14657            "condition_wait_key_mismatch",
14658            Some(sequence),
14659            recorded_key.map(str::to_string),
14660            Some(current.condition_key.clone()),
14661            "recorded condition identity differs from the current workflow wait",
14662        )));
14663    }
14664    if recorded_predicate_identity != current.predicate_identity {
14665        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14666            "condition_wait_predicate_mismatch",
14667            Some(sequence),
14668            Some(recorded_predicate_identity.to_string()),
14669            Some(current.predicate_identity.clone()),
14670            "recorded condition predicate behavior differs from current workflow code",
14671        )));
14672    }
14673    if recorded_timeout_seconds != current.timeout_seconds {
14674        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14675            "condition_wait_timeout_mismatch",
14676            Some(sequence),
14677            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14678            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14679            "recorded condition timeout differs from the current workflow wait",
14680        )));
14681    }
14682    Ok(())
14683}
14684
14685/// Future returned by [`WorkflowContext::start_child_workflow`].
14686pub struct ChildWorkflowCall {
14687    ctx: WorkflowContext,
14688    workflow_type: String,
14689    options: ChildWorkflowOptions,
14690    args: Option<Result<AvroValue>>,
14691    scheduled: bool,
14692    matched_pending: bool,
14693    parallel_group_path: Vec<ParallelGroupMetadata>,
14694}
14695
14696impl ChildWorkflowCall {
14697    fn poll_avro_value(
14698        mut self: Pin<&mut Self>,
14699        _cx: &mut TaskContext<'_>,
14700    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14701        if self.matched_pending {
14702            return Poll::Pending;
14703        }
14704
14705        let ctx = self.ctx.clone();
14706        let mut state = match ctx.state.lock() {
14707            Ok(state) => state,
14708            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14709        };
14710
14711        let cursor = state.command_cursor;
14712        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14713            return Poll::Ready(Err(error));
14714        }
14715        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
14716        {
14717            Ok(recorded) => recorded,
14718            Err(error) => return Poll::Ready(Err(error)),
14719        };
14720        if let Some(recorded) = recorded {
14721            let sequence = recorded.sequence();
14722            match recorded {
14723                RecordedCommand::ChildWorkflow {
14724                    workflow_type,
14725                    policies,
14726                    outcome,
14727                    parallel_group_path,
14728                    ..
14729                } => {
14730                    if let Err(error) = ensure_parallel_path_matches(
14731                        sequence,
14732                        parallel_group_path.as_deref(),
14733                        &self.parallel_group_path,
14734                    ) {
14735                        return Poll::Ready(Err(error));
14736                    }
14737                    if let Some(recorded_type) = workflow_type {
14738                        if recorded_type != self.workflow_type {
14739                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14740                                ReplayFailure::new(
14741                                    "recorded_command_detail_mismatch",
14742                                    Some(sequence),
14743                                    Some(format!("child workflow:{recorded_type}")),
14744                                    Some(format!("child workflow:{}", self.workflow_type)),
14745                                    "recorded child workflow type differs from the current workflow command",
14746                                ),
14747                            )));
14748                        }
14749                    }
14750                    if let Err(error) =
14751                        ensure_child_policies_match(sequence, &policies, &self.options)
14752                    {
14753                        return Poll::Ready(Err(error));
14754                    }
14755                    if let Err(error) =
14756                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
14757                    {
14758                        return Poll::Ready(Err(error));
14759                    }
14760                    match state.prepare_scalar_cancellation(
14761                        cursor,
14762                        CancellationCallKind::Child,
14763                        &self.parallel_group_path,
14764                    ) {
14765                        Ok(true) => {
14766                            self.scheduled = true;
14767                            self.matched_pending = true;
14768                            return Poll::Pending;
14769                        }
14770                        Ok(false) => {}
14771                        Err(error) => return Poll::Ready(Err(error)),
14772                    }
14773                    state.command_cursor += 1;
14774                    if let Some(outcome) = outcome {
14775                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14776                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
14777                    }
14778                    state.matched_recorded_pending = true;
14779                    self.scheduled = true;
14780                    self.matched_pending = true;
14781                    return Poll::Pending;
14782                }
14783                other => {
14784                    return Poll::Ready(Err(command_mismatch(
14785                        &other,
14786                        format!("child workflow:{}", self.workflow_type),
14787                    )));
14788                }
14789            }
14790        }
14791
14792        if !self.scheduled {
14793            if self.options.task_queue.trim().is_empty() {
14794                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14795                    "task_queue must not be empty".to_string(),
14796                )));
14797            }
14798            for (name, value) in [
14799                (
14800                    "execution_timeout_seconds",
14801                    self.options.execution_timeout_seconds,
14802                ),
14803                ("run_timeout_seconds", self.options.run_timeout_seconds),
14804            ] {
14805                if value == Some(0) {
14806                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
14807                        "{name} must be at least 1"
14808                    ))));
14809                }
14810            }
14811
14812            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14813                Ok(args) => args,
14814                Err(error) => return Poll::Ready(Err(error)),
14815            };
14816            let arguments = match encode_typed_envelope(
14817                &normalize_avro_arguments(args),
14818                &state.payload_codec,
14819            ) {
14820                Ok(arguments) => arguments,
14821                Err(error) => return Poll::Ready(Err(error)),
14822            };
14823            let mut command = json!({
14824                "type": "start_child_workflow",
14825                "workflow_type": self.workflow_type,
14826                "queue": self.options.task_queue,
14827                "parent_close_policy": self.options.parent_close_policy.as_str(),
14828                "arguments": arguments,
14829            });
14830            let object = command
14831                .as_object_mut()
14832                .expect("child workflow command is always an object");
14833            if self.options.cancellation_policy != CancellationPolicy::Abandon {
14834                object.insert(
14835                    "cancellation_policy".to_string(),
14836                    json!(self.options.cancellation_policy.as_str()),
14837                );
14838            }
14839            if let Some(policy) = &self.options.retry_policy {
14840                let mut retry_policy = serde_json::Map::new();
14841                if let Some(max_attempts) = policy.max_attempts {
14842                    if max_attempts == 0 {
14843                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14844                            "retry_policy.max_attempts must be at least 1".to_string(),
14845                        )));
14846                    }
14847                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
14848                }
14849                if !policy.backoff_seconds.is_empty() {
14850                    retry_policy
14851                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
14852                }
14853                if !policy.non_retryable_error_types.is_empty() {
14854                    retry_policy.insert(
14855                        "non_retryable_error_types".to_string(),
14856                        json!(policy.non_retryable_error_types),
14857                    );
14858                }
14859                if retry_policy.is_empty() {
14860                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14861                        "retry_policy must configure at least one field".to_string(),
14862                    )));
14863                }
14864                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
14865            }
14866            if let Some(seconds) = self.options.execution_timeout_seconds {
14867                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
14868            }
14869            if let Some(seconds) = self.options.run_timeout_seconds {
14870                object.insert("run_timeout_seconds".to_string(), json!(seconds));
14871            }
14872            apply_parallel_group_path(object, &self.parallel_group_path);
14873            ctx.apply_scope_membership(object);
14874            match state.prepare_scalar_cancellation(
14875                cursor,
14876                CancellationCallKind::Child,
14877                &self.parallel_group_path,
14878            ) {
14879                Ok(true) => {
14880                    self.scheduled = true;
14881                    self.matched_pending = true;
14882                    return Poll::Pending;
14883                }
14884                Ok(false) => {}
14885                Err(error) => return Poll::Ready(Err(error)),
14886            }
14887            state.commands.push(command);
14888            self.scheduled = true;
14889        }
14890
14891        Poll::Pending
14892    }
14893}
14894
14895impl Future for ChildWorkflowCall {
14896    type Output = Result<ChildWorkflowResult>;
14897
14898    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14899        match self.poll_avro_value(cx) {
14900            Poll::Ready(Ok(result)) => match result.result.into_json() {
14901                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
14902                    parent: result.parent,
14903                    child: result.child,
14904                    child_workflow_type: result.child_workflow_type,
14905                    result: projected,
14906                })),
14907                Err(error) => Poll::Ready(Err(error)),
14908            },
14909            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14910            Poll::Pending => Poll::Pending,
14911        }
14912    }
14913}
14914
14915fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
14916    Error::NonDeterministicReplay(ReplayFailure::new(
14917        "recorded_command_mismatch",
14918        Some(recorded.sequence()),
14919        Some(recorded.shape().to_string()),
14920        Some(actual.into()),
14921        "current workflow command does not match the recorded durable command sequence",
14922    ))
14923}
14924
14925pub struct SignalCall {
14926    ctx: WorkflowContext,
14927    signal_name: String,
14928    runtime_reserved_allowed: bool,
14929    opened_wait: bool,
14930    matched_pending: bool,
14931    parallel_group_path: Vec<ParallelGroupMetadata>,
14932}
14933
14934impl SignalCall {
14935    fn poll_avro_value(
14936        mut self: Pin<&mut Self>,
14937        _cx: &mut TaskContext<'_>,
14938    ) -> Poll<Result<Vec<AvroValue>>> {
14939        if self.matched_pending {
14940            return Poll::Pending;
14941        }
14942        if !self.runtime_reserved_allowed {
14943            if let Err(error) = validate_user_signal_name(&self.signal_name) {
14944                return Poll::Ready(Err(error));
14945            }
14946        }
14947
14948        let ctx = self.ctx.clone();
14949        let mut state = match ctx.state.lock() {
14950            Ok(state) => state,
14951            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14952        };
14953
14954        let cursor = state.command_cursor;
14955        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14956            return Poll::Ready(Err(error));
14957        }
14958        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
14959        {
14960            Ok(recorded) => recorded,
14961            Err(error) => return Poll::Ready(Err(error)),
14962        };
14963        if let Some(recorded) = recorded {
14964            match recorded {
14965                RecordedCommand::SignalWait {
14966                    sequence,
14967                    signal_name,
14968                    value,
14969                    parallel_group_path,
14970                } => {
14971                    if let Err(error) = ensure_parallel_path_matches(
14972                        sequence,
14973                        parallel_group_path.as_deref(),
14974                        &self.parallel_group_path,
14975                    ) {
14976                        return Poll::Ready(Err(error));
14977                    }
14978                    if signal_name != self.signal_name {
14979                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14980                            ReplayFailure::new(
14981                                "recorded_command_detail_mismatch",
14982                                Some(sequence),
14983                                Some(format!("signal wait:{signal_name}")),
14984                                Some(format!("signal wait:{}", self.signal_name)),
14985                                "recorded signal name differs from the current workflow command",
14986                            ),
14987                        )));
14988                    }
14989
14990                    if let Err(error) =
14991                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
14992                    {
14993                        return Poll::Ready(Err(error));
14994                    }
14995                    match state.prepare_scalar_cancellation(
14996                        cursor,
14997                        CancellationCallKind::Signal,
14998                        &self.parallel_group_path,
14999                    ) {
15000                        Ok(true) => {
15001                            self.opened_wait = true;
15002                            self.matched_pending = true;
15003                            return Poll::Pending;
15004                        }
15005                        Ok(false) => {}
15006                        Err(error) => return Poll::Ready(Err(error)),
15007                    }
15008                    state.command_cursor += 1;
15009                    if let Some(value) = value {
15010                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15011                        return Poll::Ready(Ok(value));
15012                    }
15013                    if state
15014                        .resume_signal
15015                        .as_ref()
15016                        .is_some_and(|signal| signal.signal_name == self.signal_name)
15017                    {
15018                        let signal = state
15019                            .resume_signal
15020                            .take()
15021                            .expect("matching resume signal is present");
15022                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
15023                        return Poll::Ready(Ok(signal.arguments));
15024                    }
15025
15026                    state.matched_recorded_pending = true;
15027                    self.opened_wait = true;
15028                    self.matched_pending = true;
15029                    return Poll::Pending;
15030                }
15031                other => {
15032                    return Poll::Ready(Err(command_mismatch(
15033                        &other,
15034                        format!("signal wait:{}", self.signal_name),
15035                    )));
15036                }
15037            }
15038        }
15039
15040        match state.prepare_scalar_cancellation(
15041            cursor,
15042            CancellationCallKind::Signal,
15043            &self.parallel_group_path,
15044        ) {
15045            Ok(true) => {
15046                self.opened_wait = true;
15047                self.matched_pending = true;
15048                return Poll::Pending;
15049            }
15050            Ok(false) => {}
15051            Err(error) => return Poll::Ready(Err(error)),
15052        }
15053
15054        if state
15055            .resume_signal
15056            .as_ref()
15057            .is_some_and(|signal| signal.signal_name == self.signal_name)
15058        {
15059            let signal = state
15060                .resume_signal
15061                .take()
15062                .expect("matching resume signal is present");
15063            state.unavailable_cancellation_boundary(&self.parallel_group_path);
15064            return Poll::Ready(Ok(signal.arguments));
15065        }
15066
15067        if !self.opened_wait {
15068            let mut command = serde_json::Map::from_iter([
15069                ("type".to_string(), json!("open_signal_wait")),
15070                ("signal_name".to_string(), json!(self.signal_name)),
15071            ]);
15072            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15073            ctx.apply_scope_membership(&mut command);
15074            state.commands.push(Value::Object(command));
15075            self.opened_wait = true;
15076        }
15077
15078        Poll::Pending
15079    }
15080}
15081
15082impl Future for SignalCall {
15083    type Output = Result<Vec<Value>>;
15084
15085    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15086        match self.poll_avro_value(cx) {
15087            Poll::Ready(Ok(values)) => Poll::Ready(
15088                values
15089                    .into_iter()
15090                    .map(AvroValue::into_json)
15091                    .collect::<Result<Vec<_>>>(),
15092            ),
15093            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15094            Poll::Pending => Poll::Pending,
15095        }
15096    }
15097}
15098
15099#[derive(Clone, Debug)]
15100pub struct ActivityContext {
15101    client: Client,
15102    pub task_id: String,
15103    pub activity_attempt_id: String,
15104    pub lease_owner: String,
15105    pub activity_type: String,
15106    pub attempt_number: u64,
15107    pub task_queue: String,
15108    pub worker_id: String,
15109    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
15110    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
15111    worker_session: Option<WorkerSession>,
15112}
15113
15114impl ActivityContext {
15115    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
15116        if let Some(heartbeats) = &self.local_heartbeats {
15117            return heartbeats
15118                .lock()
15119                .map_err(|_| Error::WorkflowStatePoisoned)?
15120                .record(details);
15121        }
15122        if let Some(guard) = &self.claim_guard {
15123            return guard.heartbeat(self, details).await;
15124        }
15125        if let Some(session) = &self.worker_session {
15126            if !session.active() {
15127                return Err(Error::ActivityExecutionAbandoned(
15128                    "worker-session lease or TTL is no longer active".into(),
15129                ));
15130            }
15131            let result = self
15132                .client
15133                .heartbeat_activity_task_value(
15134                    &self.task_id,
15135                    &self.activity_attempt_id,
15136                    &self.lease_owner,
15137                    details,
15138                )
15139                .await;
15140            return worker_session::settle_activity_heartbeat(
15141                session,
15142                result,
15143                &self.task_id,
15144                &self.activity_attempt_id,
15145                &self.lease_owner,
15146            );
15147        }
15148        self.client
15149            .heartbeat_activity_task(
15150                &self.task_id,
15151                &self.activity_attempt_id,
15152                &self.lease_owner,
15153                details,
15154            )
15155            .await
15156    }
15157}
15158
15159fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
15160    validate_payload_codec(codec)?;
15161    match value {
15162        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
15163            value, codec,
15164        )?)),
15165        None => Ok(AvroValue::Array(Vec::new())),
15166    }
15167}
15168
15169fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
15170    let Some(signal_name) = task
15171        .signal_name
15172        .as_deref()
15173        .filter(|value| !value.is_empty())
15174    else {
15175        return Ok(None);
15176    };
15177    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
15178    let AvroValue::Array(arguments) = decoded else {
15179        unreachable!("normalize_avro_arguments always returns an array");
15180    };
15181
15182    Ok(Some(ResumeSignal {
15183        signal_name: signal_name.to_string(),
15184        arguments,
15185    }))
15186}
15187
15188fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
15189    validate_payload_codec(&task.payload_codec)?;
15190    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
15191    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
15192    for event in &task.history_events {
15193        validate_history_event_payloads(event, &task.payload_codec)?;
15194    }
15195    Ok(())
15196}
15197
15198fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
15199    validate_payload_codec(&task.payload_codec)?;
15200    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
15201}
15202
15203fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
15204    validate_payload_codec(&task.payload_codec)?;
15205    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
15206    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
15207    for event in &task.history_events {
15208        validate_history_event_payloads(event, &task.payload_codec)?;
15209    }
15210
15211    let Some(export) = task.history_export.as_ref() else {
15212        return Ok(());
15213    };
15214    let export_codec = match export.get("payloads") {
15215        Some(payloads) => declared_payload_codec(payloads, "codec")?,
15216        None => None,
15217    }
15218    .unwrap_or(&task.payload_codec);
15219    validate_payload_codec(export_codec)?;
15220
15221    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
15222        for event in events {
15223            let event_type = event
15224                .get("event_type")
15225                .or_else(|| event.get("type"))
15226                .and_then(Value::as_str)
15227                .unwrap_or_default();
15228            if let Some(payload) = event.get("payload") {
15229                validate_history_payloads(event_type, payload, export_codec)?;
15230            }
15231        }
15232    }
15233    for signal in export
15234        .get("signals")
15235        .and_then(Value::as_array)
15236        .into_iter()
15237        .flatten()
15238    {
15239        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
15240        validate_payload_codec(codec)?;
15241        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
15242    }
15243    for activity in export
15244        .get("activities")
15245        .and_then(Value::as_array)
15246        .into_iter()
15247        .flatten()
15248    {
15249        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
15250        validate_payload_codec(codec)?;
15251        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
15252        validate_optional_inbound_payload(activity.get("result"), codec)?;
15253    }
15254    Ok(())
15255}
15256
15257fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
15258    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
15259}
15260
15261fn validate_history_payloads(
15262    event_type: &str,
15263    payload: &Value,
15264    fallback_codec: &str,
15265) -> Result<()> {
15266    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
15267    validate_payload_codec(codec)?;
15268    for field in history_payload_fields(event_type) {
15269        validate_optional_inbound_payload(payload.get(*field), codec)?;
15270    }
15271    Ok(())
15272}
15273
15274const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
15275
15276fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
15277    match event_type {
15278        "ActivityCompleted" => &["result"],
15279        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
15280        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
15281        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
15282        "ChildRunCompleted" => &["result", "output"],
15283        "WorkflowCompleted" => &["output"],
15284        "ServiceCallStarted"
15285        | "ServiceCallCompleted"
15286        | "ServiceCallFailed"
15287        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
15288        _ => &[],
15289    }
15290}
15291
15292fn signal_history_payload(payload: &Value) -> Option<&Value> {
15293    SIGNAL_HISTORY_PAYLOAD_FIELDS
15294        .iter()
15295        .find_map(|field| payload.get(*field))
15296}
15297
15298fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
15299    match value.get(field) {
15300        None => Ok(None),
15301        Some(Value::String(codec)) => Ok(Some(codec)),
15302        Some(_) => Err(invalid_payload_envelope()),
15303    }
15304}
15305
15306fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
15307    validate_payload_codec(codec)?;
15308    if let Some(value) = value.filter(|value| !value.is_null()) {
15309        decode_wire_avro_value(value, codec)?;
15310    }
15311    Ok(())
15312}
15313
15314fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
15315    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
15316        invalid_recorded_history(
15317            "parallel_group_metadata_invalid",
15318            sequence,
15319            "non-empty parallel_group_id",
15320            &payload.to_string(),
15321            "parallel-group history is missing its stable identity",
15322        )
15323    })?;
15324    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
15325        invalid_recorded_history(
15326            "parallel_group_metadata_invalid",
15327            sequence,
15328            "activity, child, timer, signal, condition, or mixed group kind",
15329            &payload.to_string(),
15330            "parallel-group history is missing its group kind",
15331        )
15332    })?;
15333    if !matches!(
15334        kind.as_str(),
15335        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
15336    ) {
15337        return Err(invalid_recorded_history(
15338            "parallel_group_metadata_invalid",
15339            sequence,
15340            "activity, child, timer, signal, condition, or mixed group kind",
15341            &kind,
15342            "parallel-group history contains an unsupported group kind",
15343        ));
15344    }
15345    let base_sequence = payload
15346        .get("parallel_group_base_sequence")
15347        .and_then(value_as_u64)
15348        .filter(|value| *value > 0)
15349        .ok_or_else(|| {
15350            invalid_recorded_history(
15351                "parallel_group_metadata_invalid",
15352                sequence,
15353                "positive parallel_group_base_sequence",
15354                &payload.to_string(),
15355                "parallel-group history contains an invalid base sequence",
15356            )
15357        })?;
15358    let size = payload
15359        .get("parallel_group_size")
15360        .and_then(value_as_u64)
15361        .and_then(|value| usize::try_from(value).ok())
15362        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
15363        .ok_or_else(|| {
15364            invalid_recorded_history(
15365                "parallel_group_metadata_invalid",
15366                sequence,
15367                "bounded positive parallel_group_size",
15368                &payload.to_string(),
15369                "parallel-group history contains an invalid group size",
15370            )
15371        })?;
15372    let index = payload
15373        .get("parallel_group_index")
15374        .and_then(value_as_u64)
15375        .and_then(|value| usize::try_from(value).ok())
15376        .filter(|value| *value < size)
15377        .ok_or_else(|| {
15378            invalid_recorded_history(
15379                "parallel_group_metadata_invalid",
15380                sequence,
15381                "parallel_group_index within group bounds",
15382                &payload.to_string(),
15383                "parallel-group history contains an invalid member index",
15384            )
15385        })?;
15386    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
15387        return Err(invalid_recorded_history(
15388            "parallel_group_metadata_invalid",
15389            sequence,
15390            "base sequence plus member index equals workflow sequence",
15391            &payload.to_string(),
15392            "parallel-group path does not preserve durable workflow position",
15393        ));
15394    }
15395    let mode = payload
15396        .get("parallel_group_mode")
15397        .and_then(Value::as_str)
15398        .unwrap_or("all");
15399    if !matches!(mode, "all" | "select") {
15400        return Err(invalid_recorded_history(
15401            "parallel_group_metadata_invalid",
15402            sequence,
15403            "parallel group mode all or select",
15404            mode,
15405            "parallel-group history contains an unsupported group mode",
15406        ));
15407    }
15408    let expected_id = if mode == "select" {
15409        format!("select-calls:{base_sequence}:{size}")
15410    } else {
15411        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
15412    };
15413    if group_id != expected_id {
15414        return Err(invalid_recorded_history(
15415            "parallel_group_metadata_invalid",
15416            sequence,
15417            &expected_id,
15418            &group_id,
15419            "parallel-group history contains an incompatible stable group ID",
15420        ));
15421    }
15422    let selection_member_key = if mode == "select" {
15423        Some(selection_key_from_value(
15424            payload.get("selection_member_key"),
15425            sequence,
15426        )?)
15427    } else {
15428        None
15429    };
15430    let selection_member_index = if mode == "select" {
15431        Some(required_parallel_usize(
15432            payload,
15433            "selection_member_index",
15434            sequence,
15435        )?)
15436    } else {
15437        None
15438    };
15439    let selection_member_base_sequence = if mode == "select" {
15440        Some(
15441            payload
15442                .get("selection_member_base_sequence")
15443                .and_then(value_as_u64)
15444                .filter(|value| *value >= base_sequence)
15445                .ok_or_else(|| {
15446                    invalid_recorded_history(
15447                        "parallel_group_metadata_invalid",
15448                        sequence,
15449                        "selection member base within its group",
15450                        &payload.to_string(),
15451                        "selection history contains an invalid member base sequence",
15452                    )
15453                })?,
15454        )
15455    } else {
15456        None
15457    };
15458    let selection_member_size = if mode == "select" {
15459        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
15460        if member_size == 0 {
15461            return Err(invalid_recorded_history(
15462                "parallel_group_metadata_invalid",
15463                sequence,
15464                "positive selection member size",
15465                &payload.to_string(),
15466                "selection history contains an invalid member size",
15467            ));
15468        }
15469        Some(member_size)
15470    } else {
15471        None
15472    };
15473    let selection_member_kind = if mode == "select" {
15474        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
15475            invalid_recorded_history(
15476                "parallel_group_metadata_invalid",
15477                sequence,
15478                "selection member operation kind",
15479                &payload.to_string(),
15480                "selection history is missing its authored member kind",
15481            )
15482        })?;
15483        if !matches!(
15484            kind.as_str(),
15485            "activity" | "child" | "timer" | "signal" | "condition" | "group"
15486        ) {
15487            return Err(invalid_recorded_history(
15488                "parallel_group_metadata_invalid",
15489                sequence,
15490                "activity, child, timer, signal, condition, or group selection member kind",
15491                &kind,
15492                "selection history contains an unsupported member kind",
15493            ));
15494        }
15495        Some(kind)
15496    } else {
15497        None
15498    };
15499    if let (Some(member_base), Some(member_size)) =
15500        (selection_member_base_sequence, selection_member_size)
15501    {
15502        let member_end = member_base
15503            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
15504            .ok_or_else(|| {
15505                invalid_recorded_history(
15506                    "parallel_group_metadata_invalid",
15507                    sequence,
15508                    "bounded selection member range",
15509                    &payload.to_string(),
15510                    "selection member range overflowed",
15511                )
15512            })?;
15513        let group_end = base_sequence
15514            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
15515            .unwrap_or(u64::MAX);
15516        if sequence < member_base || sequence >= member_end || member_end > group_end {
15517            return Err(invalid_recorded_history(
15518                "parallel_group_metadata_invalid",
15519                sequence,
15520                "workflow sequence within one bounded selection member",
15521                &payload.to_string(),
15522                "selection member range does not contain its durable leaf",
15523            ));
15524        }
15525    }
15526    Ok(ParallelGroupMetadata {
15527        parallel_group_id: group_id,
15528        parallel_group_kind: kind,
15529        parallel_group_base_sequence: base_sequence,
15530        parallel_group_size: size,
15531        parallel_group_index: index,
15532        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
15533        selection_member_key,
15534        selection_member_index,
15535        selection_member_base_sequence,
15536        selection_member_size,
15537        selection_member_kind,
15538    })
15539}
15540
15541fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
15542    payload
15543        .get(field)
15544        .and_then(value_as_u64)
15545        .and_then(|value| usize::try_from(value).ok())
15546        .ok_or_else(|| {
15547            invalid_recorded_history(
15548                "parallel_group_metadata_invalid",
15549                sequence,
15550                &format!("non-negative integer {field}"),
15551                &payload.to_string(),
15552                "selection history contains invalid member metadata",
15553            )
15554        })
15555}
15556
15557fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15558    match value {
15559        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15560        Some(value) => value_as_u64(value)
15561            .and_then(|value| usize::try_from(value).ok())
15562            .map(SelectionKey::Index)
15563            .ok_or_else(|| {
15564                invalid_recorded_history(
15565                    "selection_member_key_invalid",
15566                    sequence,
15567                    "non-empty string or non-negative integer member key",
15568                    &value.to_string(),
15569                    "selection history contains an invalid member key",
15570                )
15571            }),
15572        None => Err(invalid_recorded_history(
15573            "selection_member_key_missing",
15574            sequence,
15575            "selection_member_key",
15576            "<missing>",
15577            "selection history is missing its stable member key",
15578        )),
15579    }
15580}
15581
15582fn recorded_parallel_group_path(
15583    events: &[&HistoryEvent],
15584    sequence: u64,
15585) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15586    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15587    for event in events {
15588        let payload = &event.payload;
15589        let has_metadata = payload.get("parallel_group_path").is_some()
15590            || payload.get("parallel_group_id").is_some()
15591            || payload.get("parallel_group_kind").is_some()
15592            || payload.get("parallel_group_base_sequence").is_some()
15593            || payload.get("parallel_group_size").is_some()
15594            || payload.get("parallel_group_index").is_some()
15595            || payload.get("parallel_group_mode").is_some()
15596            || payload.get("selection_member_key").is_some();
15597        if !has_metadata {
15598            continue;
15599        }
15600
15601        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15602        let path = match payload.get("parallel_group_path") {
15603            None => vec![top_level.clone()],
15604            Some(Value::Array(entries)) if !entries.is_empty() => entries
15605                .iter()
15606                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15607                .collect::<Result<Vec<_>>>()?,
15608            Some(value) => {
15609                return Err(invalid_recorded_history(
15610                    "parallel_group_metadata_invalid",
15611                    sequence,
15612                    "non-empty parallel_group_path list",
15613                    &value.to_string(),
15614                    "parallel-group history contains an invalid group path",
15615                ));
15616            }
15617        };
15618        if path.last() != Some(&top_level) {
15619            return Err(invalid_recorded_history(
15620                "parallel_group_metadata_invalid",
15621                sequence,
15622                &serde_json::to_string(&path.last()).unwrap_or_default(),
15623                &serde_json::to_string(&top_level).unwrap_or_default(),
15624                "parallel-group top-level fields do not match the innermost path entry",
15625            ));
15626        }
15627        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15628            return Err(invalid_recorded_history(
15629                "parallel_group_history_conflict",
15630                sequence,
15631                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15632                &serde_json::to_string(&path).unwrap_or_default(),
15633                "parallel-group metadata changed between scheduling and resolution history",
15634            ));
15635        }
15636        recorded = Some(path);
15637    }
15638    Ok(recorded)
15639}
15640
15641fn recorded_commands(
15642    events: &[HistoryEvent],
15643    fallback_codec: &str,
15644    parent: WorkflowIdentity,
15645) -> Result<Vec<RecordedCommand>> {
15646    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15647    let mut last_new_sequence = None;
15648
15649    for event in events {
15650        let is_activity = matches!(
15651            event.event_type.as_str(),
15652            "ActivityScheduled"
15653                | "ActivityStarted"
15654                | "ActivityHeartbeatRecorded"
15655                | "ActivityRetryScheduled"
15656                | "ActivityCompleted"
15657                | "ActivityFailed"
15658                | "ActivityCancelled"
15659                | "ActivityTimedOut"
15660        );
15661        let is_workflow_timer = matches!(
15662            event.event_type.as_str(),
15663            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15664        ) && !is_internal_timer_event(event);
15665        let is_child_workflow = matches!(
15666            event.event_type.as_str(),
15667            "ChildWorkflowScheduled"
15668                | "ChildRunStarted"
15669                | "ChildRunCompleted"
15670                | "ChildRunFailed"
15671                | "ChildRunCancelled"
15672                | "ChildRunTerminated"
15673        );
15674        let is_signal_wait = is_recorded_signal_wait_event(event);
15675        let is_condition_wait = is_recorded_condition_wait_event(event);
15676        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15677        let is_side_effect = event.event_type == "SideEffectRecorded";
15678        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15679        let is_memo = event.event_type == "MemoUpserted";
15680        if !is_activity
15681            && !is_workflow_timer
15682            && !is_child_workflow
15683            && !is_signal_wait
15684            && !is_condition_wait
15685            && !is_search_attributes
15686            && !is_side_effect
15687            && !is_version_marker
15688            && !is_memo
15689        {
15690            continue;
15691        }
15692
15693        let sequence = durable_event_sequence(event).ok_or_else(|| {
15694            Error::NonDeterministicReplay(ReplayFailure::new(
15695                "durable_command_sequence_missing",
15696                None,
15697                Some("positive workflow sequence".to_string()),
15698                Some(event.event_type.clone()),
15699                "durable command history event has no workflow sequence",
15700            ))
15701        })?;
15702        if sequence == 0 {
15703            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15704                "durable_command_sequence_invalid",
15705                Some(sequence),
15706                Some("positive workflow sequence".to_string()),
15707                Some(sequence.to_string()),
15708                "durable command history uses an invalid workflow sequence",
15709            )));
15710        }
15711        if !events_by_sequence.contains_key(&sequence) {
15712            if let Some(previous) = last_new_sequence {
15713                if sequence < previous {
15714                    return Err(invalid_recorded_history(
15715                        "durable_command_sequence_mismatch",
15716                        sequence,
15717                        &format!("workflow sequence greater than {previous}"),
15718                        &sequence.to_string(),
15719                        "durable commands are not strictly ordered by their recorded workflow sequence",
15720                    ));
15721                }
15722            }
15723            last_new_sequence = Some(sequence);
15724        }
15725        events_by_sequence.entry(sequence).or_default().push(event);
15726    }
15727
15728    let commands: Vec<RecordedCommand> = events_by_sequence
15729        .into_iter()
15730        .map(|(sequence, sequence_events)| {
15731            let activity_events: Vec<_> = sequence_events
15732                .iter()
15733                .copied()
15734                .filter(|event| event.event_type.starts_with("Activity"))
15735                .collect();
15736            let timer_events: Vec<_> = sequence_events
15737                .iter()
15738                .copied()
15739                .filter(|event| event.event_type.starts_with("Timer"))
15740                .collect();
15741            let child_events: Vec<_> = sequence_events
15742                .iter()
15743                .copied()
15744                .filter(|event| {
15745                    event.event_type == "ChildWorkflowScheduled"
15746                        || event.event_type.starts_with("ChildRun")
15747                })
15748                .collect();
15749            let signal_wait_events: Vec<_> = sequence_events
15750                .iter()
15751                .copied()
15752                .filter(|event| is_recorded_signal_wait_event(event))
15753                .collect();
15754            let condition_wait_events: Vec<_> = sequence_events
15755                .iter()
15756                .copied()
15757                .filter(|event| is_recorded_condition_wait_event(event))
15758                .collect();
15759            let search_attribute_events: Vec<_> = sequence_events
15760                .iter()
15761                .copied()
15762                .filter(|event| event.event_type == "SearchAttributesUpserted")
15763                .collect();
15764            let side_effect_events: Vec<_> = sequence_events
15765                .iter()
15766                .copied()
15767                .filter(|event| event.event_type == "SideEffectRecorded")
15768                .collect();
15769            let version_marker_events: Vec<_> = sequence_events
15770                .iter()
15771                .copied()
15772                .filter(|event| event.event_type == "VersionMarkerRecorded")
15773                .collect();
15774            let memo_events: Vec<_> = sequence_events
15775                .iter()
15776                .copied()
15777                .filter(|event| event.event_type == "MemoUpserted")
15778                .collect();
15779
15780            let command_kind_count = usize::from(!activity_events.is_empty())
15781                + usize::from(!timer_events.is_empty())
15782                + usize::from(!child_events.is_empty())
15783                + usize::from(!signal_wait_events.is_empty())
15784                + usize::from(!condition_wait_events.is_empty())
15785                + usize::from(!search_attribute_events.is_empty())
15786                + usize::from(!side_effect_events.is_empty())
15787                + usize::from(!version_marker_events.is_empty())
15788                + usize::from(!memo_events.is_empty());
15789            if command_kind_count > 1 {
15790                let actual = [
15791                    (!activity_events.is_empty()).then_some("activity"),
15792                    (!timer_events.is_empty()).then_some("timer"),
15793                    (!child_events.is_empty()).then_some("child workflow"),
15794                    (!signal_wait_events.is_empty()).then_some("signal wait"),
15795                    (!condition_wait_events.is_empty()).then_some("condition wait"),
15796                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
15797                    (!side_effect_events.is_empty()).then_some("side effect"),
15798                    (!version_marker_events.is_empty()).then_some("version marker"),
15799                    (!memo_events.is_empty()).then_some("memo upsert"),
15800                ]
15801                .into_iter()
15802                .flatten()
15803                .collect::<Vec<_>>()
15804                .join(" and ");
15805                return Err(invalid_recorded_history(
15806                    "durable_command_sequence_collision",
15807                    sequence,
15808                    "one durable command kind",
15809                    &actual,
15810                    "one workflow sequence records more than one durable command kind",
15811                ));
15812            }
15813
15814            if !activity_events.is_empty() {
15815                let parallel_group_path =
15816                    recorded_parallel_group_path(&activity_events, sequence)?;
15817                let scheduled_count = activity_events
15818                    .iter()
15819                    .filter(|event| event.event_type == "ActivityScheduled")
15820                    .count();
15821                if scheduled_count > 1 {
15822                    return Err(invalid_recorded_history(
15823                        "duplicate_activity_schedule",
15824                        sequence,
15825                        "at most one ActivityScheduled event",
15826                        "multiple ActivityScheduled events",
15827                        "activity history schedules more than one command at one workflow sequence",
15828                    ));
15829                }
15830                let activity_type = activity_events.iter().find_map(|event| {
15831                    event
15832                        .payload
15833                        .get("activity_type")
15834                        .or_else(|| event.payload.get("activity_name"))
15835                        .and_then(Value::as_str)
15836                        .map(str::to_string)
15837                });
15838                if activity_events.iter().filter_map(|event| {
15839                    event
15840                        .payload
15841                        .get("activity_type")
15842                        .or_else(|| event.payload.get("activity_name"))
15843                        .and_then(Value::as_str)
15844                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
15845                    return Err(invalid_recorded_history(
15846                        "activity_identity_mismatch",
15847                        sequence,
15848                        activity_type.as_deref().unwrap_or("one activity identity"),
15849                        "conflicting activity identities",
15850                        "activity lifecycle events at one workflow sequence disagree on identity",
15851                    ));
15852                }
15853                let terminal: Vec<_> = activity_events
15854                    .iter()
15855                    .copied()
15856                    .filter(|event| {
15857                        matches!(
15858                            event.event_type.as_str(),
15859                            "ActivityCompleted"
15860                                | "ActivityFailed"
15861                                | "ActivityCancelled"
15862                                | "ActivityTimedOut"
15863                        )
15864                    })
15865                    .collect();
15866                let duplicate_delivery = terminal.first().is_some_and(|first| {
15867                    terminal.iter().all(|event| {
15868                        event.event_type == first.event_type && event.payload == first.payload
15869                    })
15870                });
15871                if terminal.len() > 1 && !duplicate_delivery {
15872                    return Err(invalid_recorded_history(
15873                        "duplicate_activity_terminal_event",
15874                        sequence,
15875                        "at most one terminal activity event",
15876                        "multiple terminal activity events",
15877                        "activity history settles one command more than once",
15878                    ));
15879                }
15880                let outcome = terminal
15881                    .first()
15882                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
15883                    .transpose()?;
15884                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
15885                let activity_snapshot = activity_events
15886                    .iter()
15887                    .find(|event| event.event_type == "ActivityScheduled")
15888                    .and_then(|event| event.payload.get("activity"))
15889                    .and_then(Value::as_object);
15890                let options = Some(match activity_snapshot {
15891                    Some(activity) => RecordedActivityOptions {
15892                        task_queue: recorded_optional_string(activity, "queue"),
15893                        execution_mode,
15894                        retry_policy: recorded_activity_retry_snapshot(
15895                            activity.get("retry_policy"),
15896                        ),
15897                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15898                    },
15899                    None => RecordedActivityOptions {
15900                        task_queue: RecordedSnapshotValue::Unknown,
15901                        execution_mode,
15902                        retry_policy: recorded_activity_retry_snapshot(None),
15903                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15904                    },
15905                });
15906                return Ok(RecordedCommand::Activity {
15907                    sequence,
15908                    activity_type,
15909                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
15910                    options,
15911                    outcome,
15912                    parallel_group_path,
15913                });
15914            }
15915
15916            if !child_events.is_empty() {
15917                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
15918                let scheduled: Vec<_> = child_events
15919                    .iter()
15920                    .copied()
15921                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
15922                    .collect();
15923                if scheduled.len() != 1 {
15924                    return Err(invalid_recorded_history(
15925                        "child_workflow_schedule_missing_or_duplicate",
15926                        sequence,
15927                        "one ChildWorkflowScheduled event",
15928                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
15929                        "child workflow replay requires exactly one recorded schedule event",
15930                    ));
15931                }
15932                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
15933                let workflow_type = child_events.iter().find_map(|event| {
15934                    event
15935                        .payload
15936                        .get("child_workflow_type")
15937                        .or_else(|| event.payload.get("workflow_type"))
15938                        .and_then(Value::as_str)
15939                        .filter(|value| !value.is_empty())
15940                        .map(str::to_string)
15941                });
15942                if child_events
15943                    .iter()
15944                    .filter_map(|event| {
15945                        event
15946                            .payload
15947                            .get("child_workflow_type")
15948                            .or_else(|| event.payload.get("workflow_type"))
15949                            .and_then(Value::as_str)
15950                    })
15951                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
15952                {
15953                    return Err(invalid_recorded_history(
15954                        "child_workflow_identity_mismatch",
15955                        sequence,
15956                        workflow_type
15957                            .as_deref()
15958                            .unwrap_or("one child workflow type"),
15959                        "conflicting child workflow types",
15960                        "child workflow lifecycle events at one sequence disagree on type",
15961                    ));
15962                }
15963                let mut outcomes = child_workflow_outcomes(
15964                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
15965                    fallback_codec,
15966                    parent.clone(),
15967                )?;
15968                let terminal_events = child_events
15969                    .iter()
15970                    .copied()
15971                    .filter(|event| event.event_type.starts_with("ChildRun"))
15972                    .collect::<Vec<_>>();
15973                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
15974                    terminal_events.iter().all(|event| {
15975                        event.event_type == first.event_type && event.payload == first.payload
15976                    })
15977                });
15978                if outcomes.len() > 1 && !duplicate_delivery {
15979                    return Err(invalid_recorded_history(
15980                        "duplicate_child_workflow_terminal_event",
15981                        sequence,
15982                        "at most one terminal child event",
15983                        "multiple terminal child events",
15984                        "child workflow history settles one command more than once",
15985                    ));
15986                }
15987                return Ok(RecordedCommand::ChildWorkflow {
15988                    sequence,
15989                    workflow_type,
15990                    policies,
15991                    outcome: outcomes.pop(),
15992                    parallel_group_path,
15993                });
15994            }
15995
15996            if !signal_wait_events.is_empty() {
15997                let opened: Vec<_> = signal_wait_events
15998                    .iter()
15999                    .copied()
16000                    .filter(|event| event.event_type == "SignalWaitOpened")
16001                    .collect();
16002                if opened.len() != 1 {
16003                    return Err(invalid_recorded_history(
16004                        "signal_wait_open_missing_or_duplicate",
16005                        sequence,
16006                        "one SignalWaitOpened event",
16007                        &format!("{} SignalWaitOpened events", opened.len()),
16008                        "signal replay requires exactly one canonical wait-open event",
16009                    ));
16010                }
16011
16012                let applied: Vec<_> = signal_wait_events
16013                    .iter()
16014                    .copied()
16015                    .filter(|event| event.event_type == "SignalApplied")
16016                    .collect();
16017                if applied.len() > 1 {
16018                    return Err(invalid_recorded_history(
16019                        "duplicate_signal_wait_apply",
16020                        sequence,
16021                        "at most one SignalApplied event",
16022                        "multiple SignalApplied events",
16023                        "signal history applies one durable wait more than once",
16024                    ));
16025                }
16026
16027                let signal_names = signal_wait_events
16028                    .iter()
16029                    .map(|event| required_signal_wait_name(event, sequence))
16030                    .collect::<Result<Vec<_>>>()?;
16031                let signal_name = signal_names
16032                    .first()
16033                    .expect("signal wait events are not empty")
16034                    .clone();
16035                if signal_names.iter().any(|candidate| candidate != &signal_name) {
16036                    return Err(invalid_recorded_history(
16037                        "signal_wait_identity_mismatch",
16038                        sequence,
16039                        &signal_name,
16040                        "conflicting signal names",
16041                        "signal wait lifecycle events at one workflow sequence disagree on identity",
16042                    ));
16043                }
16044                let value = applied
16045                    .first()
16046                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
16047                    .transpose()?;
16048                return Ok(RecordedCommand::SignalWait {
16049                    sequence,
16050                    signal_name,
16051                    value,
16052                    parallel_group_path: recorded_parallel_group_path(
16053                        &signal_wait_events,
16054                        sequence,
16055                    )?,
16056                });
16057            }
16058
16059            if !condition_wait_events.is_empty() {
16060                return recorded_condition_wait(
16061                    sequence,
16062                    &condition_wait_events,
16063                    events,
16064                );
16065            }
16066
16067            if !search_attribute_events.is_empty() {
16068                if search_attribute_events.len() != 1 {
16069                    return Err(invalid_recorded_history(
16070                        "duplicate_search_attribute_update",
16071                        sequence,
16072                        "one SearchAttributesUpserted event",
16073                        &format!(
16074                            "{} SearchAttributesUpserted events",
16075                            search_attribute_events.len()
16076                        ),
16077                        "search-attribute history records one workflow command more than once",
16078                    ));
16079                }
16080                let payload = &search_attribute_events[0].payload;
16081                let attributes = payload
16082                    .get("attributes")
16083                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
16084                    .cloned()
16085                    .ok_or_else(|| {
16086                        invalid_recorded_history(
16087                            "search_attribute_update_missing",
16088                            sequence,
16089                            "non-empty attributes object",
16090                            "missing or invalid attributes",
16091                            "search-attribute history is missing its recorded mutation",
16092                        )
16093                    })?;
16094                let attribute_types =
16095                    recorded_search_attribute_types(payload, &attributes, sequence)?;
16096                return Ok(RecordedCommand::SearchAttributes {
16097                    sequence,
16098                    attributes,
16099                    attribute_types,
16100                });
16101            }
16102
16103            if !side_effect_events.is_empty() {
16104                if side_effect_events.len() != 1 {
16105                    return Err(invalid_recorded_history(
16106                        "duplicate_side_effect_record",
16107                        sequence,
16108                        "one SideEffectRecorded event",
16109                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
16110                        "side-effect history records one workflow command more than once",
16111                    ));
16112                }
16113                let event = side_effect_events[0];
16114                let result = event.payload.get("result").ok_or_else(|| {
16115                    invalid_recorded_history(
16116                        "side_effect_result_missing",
16117                        sequence,
16118                        "recorded result payload",
16119                        "missing result",
16120                        "side-effect history is missing its recorded value",
16121                    )
16122                })?;
16123                let has_published_envelope = result.as_str().is_some()
16124                    || result.as_object().is_some_and(|envelope| {
16125                        envelope.get("codec").and_then(Value::as_str).is_some()
16126                            && envelope.get("blob").and_then(Value::as_str).is_some()
16127                    });
16128                if !has_published_envelope {
16129                    return Err(invalid_recorded_history(
16130                        "side_effect_payload_malformed",
16131                        sequence,
16132                        "payload blob or {codec, blob} envelope",
16133                        &result.to_string(),
16134                        "side-effect history result does not use a published payload envelope",
16135                    ));
16136                }
16137                let codec = event
16138                    .payload
16139                    .get("payload_codec")
16140                    .and_then(Value::as_str)
16141                    .unwrap_or(fallback_codec);
16142                let value = decode_wire_avro_value(result, codec).map_err(|error| {
16143                    if error.to_string().contains("unsupported_payload_codec") {
16144                        return error;
16145                    }
16146
16147                    invalid_recorded_history(
16148                        "side_effect_payload_incompatible",
16149                        sequence,
16150                        &format!("valid {codec} payload envelope"),
16151                        &error.to_string(),
16152                        "side-effect history payload cannot be decoded with its recorded codec",
16153                    )
16154                })?;
16155                return Ok(RecordedCommand::SideEffect { sequence, value });
16156            }
16157
16158            if !version_marker_events.is_empty() {
16159                if version_marker_events.len() != 1 {
16160                    return Err(invalid_recorded_history(
16161                        "duplicate_version_marker_record",
16162                        sequence,
16163                        "one VersionMarkerRecorded event",
16164                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
16165                        "version-marker history records one workflow command more than once",
16166                    ));
16167                }
16168                let payload = &version_marker_events[0].payload;
16169                let change_id = payload
16170                    .get("change_id")
16171                    .and_then(Value::as_str)
16172                    .filter(|value| !value.is_empty())
16173                    .map(str::to_string)
16174                    .ok_or_else(|| {
16175                        invalid_recorded_history(
16176                            "version_marker_field_missing",
16177                            sequence,
16178                            "non-empty change_id",
16179                            "missing or invalid change_id",
16180                            "version-marker history is missing its stable change ID",
16181                        )
16182                    })?;
16183                let version = required_version_i32(payload, "version", sequence)?;
16184                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
16185                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
16186                if min_supported > max_supported || version < min_supported || version > max_supported {
16187                    return Err(invalid_recorded_history(
16188                        "version_marker_history_range_invalid",
16189                        sequence,
16190                        "min_supported <= version <= max_supported",
16191                        &format!("{min_supported} <= {version} <= {max_supported}"),
16192                        "recorded version marker contains an internally incompatible range",
16193                    ));
16194                }
16195                return Ok(RecordedCommand::VersionMarker {
16196                    sequence,
16197                    change_id,
16198                    version,
16199                });
16200            }
16201
16202            if !memo_events.is_empty() {
16203                if memo_events.len() != 1 {
16204                    return Err(invalid_recorded_history(
16205                        "duplicate_memo_upsert_record",
16206                        sequence,
16207                        "one MemoUpserted event",
16208                        &format!("{} MemoUpserted events", memo_events.len()),
16209                        "memo history records one workflow update more than once",
16210                    ));
16211                }
16212                let payload = &memo_events[0].payload;
16213                let entries = payload.get("entries").cloned().ok_or_else(|| {
16214                    invalid_recorded_history(
16215                        "memo_entries_missing",
16216                        sequence,
16217                        "memo entries object",
16218                        "missing entries",
16219                        "MemoUpserted history is missing replay identity entries",
16220                    )
16221                })?;
16222                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
16223                    invalid_recorded_history(
16224                        "memo_entries_invalid",
16225                        sequence,
16226                        "valid canonical memo entries",
16227                        &error.to_string(),
16228                        "MemoUpserted history contains invalid replay identity entries",
16229                    )
16230                })?;
16231                let merged = payload.get("merged").cloned().ok_or_else(|| {
16232                    invalid_recorded_history(
16233                        "memo_merged_projection_missing",
16234                        sequence,
16235                        "merged memo projection",
16236                        "missing merged",
16237                        "MemoUpserted history is missing its merged projection",
16238                    )
16239                })?;
16240                decode_memo_history_map(&merged, false).map_err(|error| {
16241                    invalid_recorded_history(
16242                        "memo_merged_projection_invalid",
16243                        sequence,
16244                        "valid merged memo projection",
16245                        &error.to_string(),
16246                        "MemoUpserted history contains an invalid merged projection",
16247                    )
16248                })?;
16249
16250                return Ok(RecordedCommand::Memo { sequence, entries });
16251            }
16252            let scheduled: Vec<_> = timer_events
16253                .iter()
16254                .copied()
16255                .filter(|event| event.event_type == "TimerScheduled")
16256                .collect();
16257            let fired: Vec<_> = timer_events
16258                .iter()
16259                .copied()
16260                .filter(|event| event.event_type == "TimerFired")
16261                .collect();
16262            if scheduled.len() != 1 {
16263                return Err(invalid_recorded_history(
16264                    "timer_schedule_missing_or_duplicate",
16265                    sequence,
16266                    "one TimerScheduled event",
16267                    &format!("{} TimerScheduled events", scheduled.len()),
16268                    "timer replay requires exactly one recorded schedule event",
16269                ));
16270            }
16271            if fired.len() > 1 {
16272                return Err(invalid_recorded_history(
16273                    "duplicate_timer_fire",
16274                    sequence,
16275                    "at most one TimerFired event",
16276                    "multiple TimerFired events",
16277                    "timer history contains more than one fire event for a workflow sequence",
16278                ));
16279            }
16280
16281            let scheduled = scheduled[0];
16282            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16283            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16284            if let Some(fired) = fired.first() {
16285                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16286                if fired_timer_id != timer_id {
16287                    return Err(invalid_recorded_history(
16288                        "timer_identity_mismatch",
16289                        sequence,
16290                        &timer_id,
16291                        &fired_timer_id,
16292                        "TimerFired does not correspond to the recorded TimerScheduled event",
16293                    ));
16294                }
16295                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16296                if fired_delay != delay_seconds {
16297                    return Err(invalid_recorded_history(
16298                        "timer_history_delay_mismatch",
16299                        sequence,
16300                        &delay_seconds.to_string(),
16301                        &fired_delay.to_string(),
16302                        "TimerScheduled and TimerFired record different delays",
16303                    ));
16304                }
16305            }
16306
16307            Ok(RecordedCommand::Timer {
16308                sequence,
16309                delay_seconds,
16310                fired: !fired.is_empty(),
16311                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
16312            })
16313        })
16314        .collect::<Result<_>>()?;
16315
16316    let mut marker_decisions = HashMap::new();
16317    for command in &commands {
16318        if let RecordedCommand::VersionMarker {
16319            sequence,
16320            change_id,
16321            version,
16322        } = command
16323        {
16324            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
16325                if version != first_version {
16326                    return Err(invalid_recorded_history(
16327                        "version_marker_conflict",
16328                        *sequence,
16329                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
16330                        &format!("version {version} at sequence {sequence}"),
16331                        "workflow history contains conflicting decisions for one stable change ID",
16332                    ));
16333                }
16334            } else {
16335                marker_decisions.insert(change_id.clone(), (*version, *sequence));
16336            }
16337        }
16338    }
16339
16340    Ok(commands)
16341}
16342
16343fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
16344    payload
16345        .get(field)
16346        .and_then(Value::as_i64)
16347        .and_then(|value| i32::try_from(value).ok())
16348        .ok_or_else(|| {
16349            invalid_recorded_history(
16350                "version_marker_field_missing",
16351                sequence,
16352                &format!("integer {field}"),
16353                "missing or out-of-range integer",
16354                "version-marker history is missing a required integer field",
16355            )
16356        })
16357}
16358
16359fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
16360    event
16361        .payload
16362        .get("sequence")
16363        .or_else(|| event.payload.get("workflow_sequence"))
16364        .or_else(|| event.raw.get("sequence"))
16365        .or_else(|| event.raw.get("workflow_sequence"))
16366        .and_then(value_as_u64)
16367}
16368
16369fn is_internal_timer_event(event: &HistoryEvent) -> bool {
16370    matches!(
16371        event
16372            .payload
16373            .get("timer_kind")
16374            .or_else(|| event.raw.get("timer_kind"))
16375            .and_then(Value::as_str),
16376        Some("condition_timeout" | "signal_timeout")
16377    )
16378}
16379
16380fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
16381    matches!(
16382        event.event_type.as_str(),
16383        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16384    )
16385}
16386
16387fn recorded_condition_wait(
16388    sequence: u64,
16389    condition_events: &[&HistoryEvent],
16390    all_events: &[HistoryEvent],
16391) -> Result<RecordedCommand> {
16392    let opened = condition_events
16393        .iter()
16394        .copied()
16395        .filter(|event| event.event_type == "ConditionWaitOpened")
16396        .collect::<Vec<_>>();
16397    if opened.len() != 1 {
16398        return Err(invalid_recorded_history(
16399            "condition_wait_open_missing_or_duplicate",
16400            sequence,
16401            "one ConditionWaitOpened event",
16402            &format!("{} ConditionWaitOpened events", opened.len()),
16403            "condition replay requires exactly one canonical wait-open event",
16404        ));
16405    }
16406    let terminal = condition_events
16407        .iter()
16408        .copied()
16409        .filter(|event| {
16410            matches!(
16411                event.event_type.as_str(),
16412                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16413            )
16414        })
16415        .collect::<Vec<_>>();
16416    if terminal.len() > 1 {
16417        return Err(invalid_recorded_history(
16418            "duplicate_condition_wait_terminal_event",
16419            sequence,
16420            "at most one condition terminal event",
16421            "multiple condition terminal events",
16422            "condition history settles one durable wait more than once",
16423        ));
16424    }
16425
16426    let opened = opened[0];
16427    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
16428    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
16429    for event in condition_events
16430        .iter()
16431        .copied()
16432        .filter(|event| !std::ptr::eq(*event, opened))
16433    {
16434        let event_wait_id = required_condition_wait_id(event, sequence)?;
16435        if event_wait_id != condition_wait_id {
16436            return Err(invalid_recorded_history(
16437                "condition_wait_id_mismatch",
16438                sequence,
16439                &condition_wait_id,
16440                &event_wait_id,
16441                "condition lifecycle events at one sequence disagree on wait identity",
16442            ));
16443        }
16444        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
16445        if event_occurrence_id != occurrence_id {
16446            return Err(invalid_recorded_history(
16447                "condition_wait_occurrence_history_mismatch",
16448                sequence,
16449                &occurrence_id,
16450                &event_occurrence_id,
16451                "condition lifecycle events at one sequence disagree on authored occurrence identity",
16452            ));
16453        }
16454    }
16455
16456    let condition_key = optional_non_empty_history_string(opened, "condition_key");
16457    let predicate_identity = opened
16458        .payload
16459        .get("condition_definition_fingerprint")
16460        .and_then(Value::as_str)
16461        .filter(|value| !value.is_empty())
16462        .map(str::to_string)
16463        .ok_or_else(|| {
16464            invalid_recorded_history(
16465                "condition_wait_predicate_fingerprint_missing",
16466                sequence,
16467                "non-empty condition_definition_fingerprint",
16468                &opened.event_type,
16469                "canonical condition history is missing its predicate identity",
16470            )
16471        })?;
16472    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
16473    for event in condition_events
16474        .iter()
16475        .copied()
16476        .filter(|event| !std::ptr::eq(*event, opened))
16477    {
16478        for (field, opened_value) in [
16479            ("condition_key", condition_key.as_deref()),
16480            (
16481                "condition_definition_fingerprint",
16482                Some(predicate_identity.as_str()),
16483            ),
16484        ] {
16485            if let Some(value) = optional_non_empty_history_string(event, field) {
16486                if opened_value.is_some_and(|opened_value| opened_value != value) {
16487                    return Err(invalid_recorded_history(
16488                        "condition_wait_definition_history_mismatch",
16489                        sequence,
16490                        opened_value.unwrap_or_default(),
16491                        &value,
16492                        "condition lifecycle events disagree on the recorded definition",
16493                    ));
16494                }
16495            }
16496        }
16497        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
16498            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
16499                return Err(invalid_recorded_history(
16500                    "condition_wait_definition_history_mismatch",
16501                    sequence,
16502                    &format!("{}s", timeout_seconds.unwrap_or_default()),
16503                    &format!("{event_timeout}s"),
16504                    "condition lifecycle events disagree on the recorded timeout",
16505                ));
16506            }
16507        }
16508    }
16509
16510    let timeout_timer_events = all_events
16511        .iter()
16512        .filter(|event| {
16513            matches!(
16514                event.event_type.as_str(),
16515                "TimerScheduled" | "TimerCancelled" | "TimerFired"
16516            ) && event.payload.get("timer_kind").and_then(Value::as_str)
16517                == Some("condition_timeout")
16518                && event
16519                    .payload
16520                    .get("condition_wait_id")
16521                    .and_then(Value::as_str)
16522                    == Some(condition_wait_id.as_str())
16523        })
16524        .collect::<Vec<_>>();
16525    let scheduled = timeout_timer_events
16526        .iter()
16527        .copied()
16528        .filter(|event| event.event_type == "TimerScheduled")
16529        .collect::<Vec<_>>();
16530    let fired = timeout_timer_events
16531        .iter()
16532        .copied()
16533        .filter(|event| event.event_type == "TimerFired")
16534        .collect::<Vec<_>>();
16535    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
16536        return Err(invalid_recorded_history(
16537            "condition_wait_timeout_history_invalid",
16538            sequence,
16539            "one timeout schedule and at most one fire",
16540            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
16541            "condition timeout history has a missing or duplicate lifecycle event",
16542        ));
16543    }
16544    if let Some(scheduled) = scheduled.first() {
16545        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16546        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16547        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
16548            return Err(invalid_recorded_history(
16549                "condition_wait_timeout_delay_mismatch",
16550                sequence,
16551                &format!("{}s", timeout_seconds.unwrap_or_default()),
16552                &format!("{delay_seconds}s"),
16553                "condition timeout timer differs from the wait definition",
16554            ));
16555        }
16556        if let Some(fired) = fired.first() {
16557            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16558            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16559            if fired_timer_id != timer_id || fired_delay != delay_seconds {
16560                return Err(invalid_recorded_history(
16561                    "condition_wait_timeout_identity_mismatch",
16562                    sequence,
16563                    &format!("{timer_id}:{delay_seconds}s"),
16564                    &format!("{fired_timer_id}:{fired_delay}s"),
16565                    "condition timeout fire does not match its durable schedule",
16566                ));
16567            }
16568        }
16569    }
16570
16571    let result = terminal.first().map(|event| {
16572        if event.event_type == "ConditionWaitTimedOut" {
16573            ConditionWaitResult::TimedOut
16574        } else {
16575            ConditionWaitResult::Satisfied
16576        }
16577    });
16578    let result = if !fired.is_empty() {
16579        if result == Some(ConditionWaitResult::Satisfied) {
16580            return Err(invalid_recorded_history(
16581                "condition_wait_terminal_conflict",
16582                sequence,
16583                "one satisfied or timed-out outcome",
16584                "satisfied event and fired timeout",
16585                "condition history records conflicting terminal outcomes",
16586            ));
16587        }
16588        Some(ConditionWaitResult::TimedOut)
16589    } else {
16590        result
16591    };
16592
16593    Ok(RecordedCommand::ConditionWait {
16594        sequence,
16595        occurrence_id,
16596        condition_key,
16597        predicate_identity,
16598        timeout_seconds,
16599        result,
16600        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16601    })
16602}
16603
16604fn recorded_condition_group_path(
16605    condition_events: &[&HistoryEvent],
16606    all_events: &[HistoryEvent],
16607    sequence: u64,
16608) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16609    let opened = condition_events
16610        .iter()
16611        .copied()
16612        .find(|event| event.event_type == "ConditionWaitOpened")
16613        .expect("canonical condition opener is validated first");
16614    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16615    let previous_events = all_events
16616        .iter()
16617        .take_while(|event| !std::ptr::eq(*event, opened))
16618        .collect::<Vec<_>>();
16619    let originals = previous_events
16620        .iter()
16621        .copied()
16622        .filter(|event| event.event_type == "ConditionWaitOpened")
16623        .filter(|event| {
16624            event
16625                .payload
16626                .get("condition_wait_occurrence_id")
16627                .and_then(Value::as_str)
16628                == Some(occurrence.as_str())
16629        })
16630        .collect::<Vec<_>>();
16631    let Some(original) = originals.first().copied() else {
16632        return recorded_parallel_group_path(condition_events, sequence);
16633    };
16634    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16635    if authored_sequence == sequence {
16636        return recorded_parallel_group_path(condition_events, sequence);
16637    }
16638    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16639    if original_path.is_none() {
16640        return recorded_parallel_group_path(condition_events, sequence);
16641    }
16642    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16643    let identity_matches = [
16644        "condition_key",
16645        "condition_definition_fingerprint",
16646        "timeout_seconds",
16647    ]
16648    .iter()
16649    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16650    let previous = originals
16651        .iter()
16652        .copied()
16653        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16654        .max_by_key(|event| durable_event_sequence(event));
16655    let previously_satisfied = previous.is_some_and(|previous| {
16656        previous_events.iter().any(|event| {
16657            event.event_type == "ConditionWaitSatisfied"
16658                && event.payload.get("condition_wait_id")
16659                    == previous.payload.get("condition_wait_id")
16660                && event.payload.get("condition_wait_occurrence_id")
16661                    == previous.payload.get("condition_wait_occurrence_id")
16662                && durable_event_sequence(event) == durable_event_sequence(previous)
16663        })
16664    });
16665    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16666        return Err(invalid_recorded_history(
16667            "condition_wait_group_reopen_mismatch",
16668            sequence,
16669            "same authored condition and group path after a satisfied physical wait",
16670            &opened.payload.to_string(),
16671            "grouped condition reopen has no matching recorded predecessor",
16672        ));
16673    }
16674    Ok(reopened_path)
16675}
16676
16677fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16678    event
16679        .payload
16680        .get("condition_wait_occurrence_id")
16681        .and_then(Value::as_str)
16682        .filter(|value| !value.is_empty())
16683        .map(str::to_string)
16684        .ok_or_else(|| {
16685            invalid_recorded_history(
16686                "condition_wait_occurrence_id_missing",
16687                sequence,
16688                "non-empty condition_wait_occurrence_id",
16689                &event.event_type,
16690                "condition history is missing authored occurrence identity",
16691            )
16692        })
16693}
16694
16695fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16696    event
16697        .payload
16698        .get("condition_wait_id")
16699        .and_then(Value::as_str)
16700        .filter(|value| !value.is_empty())
16701        .map(str::to_string)
16702        .ok_or_else(|| {
16703            invalid_recorded_history(
16704                "condition_wait_id_missing",
16705                sequence,
16706                "non-empty condition_wait_id",
16707                &event.event_type,
16708                "canonical condition history is missing its durable wait identity",
16709            )
16710        })
16711}
16712
16713fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
16714    event
16715        .payload
16716        .get(field)
16717        .and_then(Value::as_str)
16718        .filter(|value| !value.is_empty())
16719        .map(str::to_string)
16720}
16721
16722fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
16723    match event.payload.get(field) {
16724        None | Some(Value::Null) => Ok(None),
16725        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
16726            invalid_recorded_history(
16727                "condition_wait_definition_invalid",
16728                sequence,
16729                &format!("non-negative integer {field}"),
16730                &value.to_string(),
16731                "condition history contains an invalid numeric definition field",
16732            )
16733        }),
16734    }
16735}
16736
16737fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
16738    event
16739        .payload
16740        .get("signal_name")
16741        .or_else(|| event.raw.get("signal_name"))
16742        .and_then(Value::as_str)
16743        .filter(|value| !value.is_empty())
16744        .map(str::to_string)
16745        .ok_or_else(|| {
16746            invalid_recorded_history(
16747                "signal_wait_name_missing",
16748                sequence,
16749                "non-empty signal_name",
16750                &event.event_type,
16751                "canonical signal-wait history is missing its signal identity",
16752            )
16753        })
16754}
16755
16756fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
16757    // Applying a buffered control-plane signal has no authored call sequence.
16758    // Its outer sequence orders history events and must not become a wait.
16759    if event.event_type == "SignalApplied"
16760        && event
16761            .payload
16762            .get("signal_wait_id")
16763            .and_then(Value::as_str)
16764            .is_some_and(|id| id.starts_with("signal-command:"))
16765        && event.payload.get("sequence").is_none()
16766        && event.payload.get("workflow_sequence").is_none()
16767    {
16768        return false;
16769    }
16770    matches!(
16771        event.event_type.as_str(),
16772        "SignalWaitOpened" | "SignalApplied"
16773    )
16774}
16775
16776fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
16777    event
16778        .payload
16779        .get(field)
16780        .and_then(Value::as_str)
16781        .filter(|value| !value.is_empty())
16782        .map(str::to_string)
16783        .ok_or_else(|| {
16784            invalid_recorded_history(
16785                "timer_history_field_missing",
16786                sequence,
16787                field,
16788                &event.event_type,
16789                "timer history is missing a required identity field",
16790            )
16791        })
16792}
16793
16794fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
16795    event
16796        .payload
16797        .get(field)
16798        .and_then(value_as_u64)
16799        .ok_or_else(|| {
16800            invalid_recorded_history(
16801                "timer_history_field_missing",
16802                sequence,
16803                field,
16804                &event.event_type,
16805                "timer history is missing a required numeric field",
16806            )
16807        })
16808}
16809
16810fn recorded_search_attribute_types(
16811    payload: &Value,
16812    attributes: &Value,
16813    sequence: u64,
16814) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
16815    let Some(raw_types) = payload.get("attribute_types") else {
16816        // This is the explicit compatibility rule for histories recorded
16817        // before typed identity was persisted. Values still constrain replay;
16818        // the unknown type snapshot does not assert a typed match.
16819        return Ok(RecordedSnapshotValue::Unknown);
16820    };
16821    let Some(raw_types) = raw_types.as_object() else {
16822        return Err(invalid_recorded_history(
16823            "search_attribute_types_malformed",
16824            sequence,
16825            "canonical attribute type map",
16826            &raw_types.to_string(),
16827            "search-attribute history contains malformed type identity",
16828        ));
16829    };
16830    let attribute_keys = attributes
16831        .as_object()
16832        .expect("recorded search attributes were validated as an object");
16833    let mut types = BTreeMap::new();
16834    for (key, value) in raw_types {
16835        let Some(attribute_type) = value.as_str() else {
16836            return Err(invalid_recorded_history(
16837                "search_attribute_types_malformed",
16838                sequence,
16839                "canonical string type name",
16840                &value.to_string(),
16841                "search-attribute history contains a non-string type identity",
16842            ));
16843        };
16844        if !attribute_keys.contains_key(key)
16845            || !matches!(
16846                attribute_type,
16847                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
16848            )
16849        {
16850            return Err(invalid_recorded_history(
16851                "search_attribute_types_malformed",
16852                sequence,
16853                "canonical types for keys present in attributes",
16854                &format!("{key}:{attribute_type}"),
16855                "search-attribute history contains unsupported or orphaned type identity",
16856            ));
16857        }
16858        types.insert(key.clone(), attribute_type.to_string());
16859    }
16860    Ok(RecordedSnapshotValue::Known(types))
16861}
16862
16863fn invalid_recorded_history(
16864    reason: &str,
16865    sequence: u64,
16866    expected: &str,
16867    actual: &str,
16868    message: &str,
16869) -> Error {
16870    Error::NonDeterministicReplay(ReplayFailure::new(
16871        reason,
16872        Some(sequence),
16873        Some(expected.to_string()),
16874        Some(actual.to_string()),
16875        message,
16876    ))
16877}
16878
16879type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
16880
16881fn activity_outcome(
16882    event: &HistoryEvent,
16883    fallback_codec: &str,
16884    recorded_activity_type: Option<String>,
16885) -> Result<ActivityOutcome> {
16886    if event.event_type == "ActivityCompleted" {
16887        let codec = event
16888            .payload
16889            .get("payload_codec")
16890            .and_then(Value::as_str)
16891            .unwrap_or(fallback_codec);
16892        return Ok(Ok(decode_wire_avro_value(
16893            event.payload.get("result").unwrap_or(&Value::Null),
16894            codec,
16895        )?));
16896    }
16897
16898    let payload = &event.payload;
16899    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
16900        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
16901        "ActivityCancelled" => (
16902            ActivityFailureKind::Cancelled,
16903            "cancelled",
16904            "activity was cancelled",
16905        ),
16906        "ActivityTimedOut" => (
16907            ActivityFailureKind::TimedOut,
16908            "timeout",
16909            "activity timed out",
16910        ),
16911        _ => unreachable!("activity_outcome is called only for terminal activity events"),
16912    };
16913    let exception = payload
16914        .get("exception")
16915        .filter(|value| !value.is_null())
16916        .cloned();
16917    let failure_category = payload_string(payload, "failure_category");
16918    let timeout_kind = payload_string(payload, "timeout_kind");
16919    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
16920        ActivityFailureKind::Failed => failure_category
16921            .clone()
16922            .unwrap_or_else(|| fallback_reason.to_string()),
16923        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
16924        ActivityFailureKind::TimedOut => timeout_kind
16925            .clone()
16926            .unwrap_or_else(|| fallback_reason.to_string()),
16927    });
16928    let message = payload_string(payload, "message")
16929        .or_else(|| {
16930            exception
16931                .as_ref()
16932                .and_then(|value| payload_string(value, "message"))
16933        })
16934        .unwrap_or_else(|| fallback_message.to_string());
16935
16936    Ok(Err(ActivityFailure {
16937        kind,
16938        reason,
16939        message,
16940        activity_execution_id: payload_string(payload, "activity_execution_id"),
16941        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
16942        activity_type: payload_string(payload, "activity_type")
16943            .or_else(|| payload_string(payload, "activity_name"))
16944            .or(recorded_activity_type),
16945        activity_class: payload_string(payload, "activity_class"),
16946        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
16947        failure_id: payload_string(payload, "failure_id"),
16948        failure_category,
16949        timeout_kind,
16950        non_retryable: payload
16951            .get("non_retryable")
16952            .and_then(Value::as_bool)
16953            .unwrap_or(false),
16954        exception_type: payload_string(payload, "exception_type").or_else(|| {
16955            exception
16956                .as_ref()
16957                .and_then(|value| payload_string(value, "type"))
16958        }),
16959        exception_class: payload_string(payload, "exception_class").or_else(|| {
16960            exception
16961                .as_ref()
16962                .and_then(|value| payload_string(value, "class"))
16963        }),
16964        code: payload
16965            .get("code")
16966            .filter(|value| !value.is_null())
16967            .cloned(),
16968        exception,
16969    }))
16970}
16971
16972type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
16973
16974fn child_workflow_outcomes(
16975    events: &[HistoryEvent],
16976    fallback_codec: &str,
16977    parent: WorkflowIdentity,
16978) -> Result<Vec<ChildWorkflowOutcome>> {
16979    let mut outcomes = Vec::new();
16980
16981    for event in events {
16982        let kind = match event.event_type.as_str() {
16983            "ChildRunCompleted" => None,
16984            "ChildRunFailed" => Some((
16985                ChildWorkflowFailureKind::Failed,
16986                "child_workflow",
16987                "child workflow failed",
16988            )),
16989            "ChildRunCancelled" => Some((
16990                ChildWorkflowFailureKind::Cancelled,
16991                "cancelled",
16992                "child workflow was cancelled",
16993            )),
16994            "ChildRunTerminated" => Some((
16995                ChildWorkflowFailureKind::Terminated,
16996                "terminated",
16997                "child workflow was terminated",
16998            )),
16999            _ => continue,
17000        };
17001        let payload = &event.payload;
17002        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
17003        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
17004        let child_workflow_type = payload_string(payload, "child_workflow_type");
17005
17006        if let Some((kind, reason, fallback_message)) = kind {
17007            let exception = payload
17008                .get("exception")
17009                .filter(|value| !value.is_null())
17010                .cloned();
17011            let message = payload_string(payload, "message")
17012                .or_else(|| {
17013                    exception
17014                        .as_ref()
17015                        .and_then(|value| payload_string(value, "message"))
17016                })
17017                .unwrap_or_else(|| fallback_message.to_string());
17018            let exception_type = payload_string(payload, "exception_type").or_else(|| {
17019                exception
17020                    .as_ref()
17021                    .and_then(|value| payload_string(value, "type"))
17022            });
17023            let exception_class = payload_string(payload, "exception_class").or_else(|| {
17024                exception
17025                    .as_ref()
17026                    .and_then(|value| payload_string(value, "class"))
17027            });
17028            outcomes.push(Err(ChildWorkflowFailure {
17029                kind,
17030                reason: reason.to_string(),
17031                message,
17032                parent_workflow_id: parent.workflow_id.clone(),
17033                parent_workflow_run_id: parent.run_id.clone(),
17034                child_workflow_id,
17035                child_workflow_run_id,
17036                child_workflow_type,
17037                failure_id: payload_string(payload, "failure_id"),
17038                failure_category: payload_string(payload, "failure_category"),
17039                exception_type,
17040                exception_class,
17041                non_retryable: payload
17042                    .get("non_retryable")
17043                    .and_then(Value::as_bool)
17044                    .unwrap_or(false),
17045                code: payload
17046                    .get("code")
17047                    .filter(|value| !value.is_null())
17048                    .cloned(),
17049                exception,
17050            }));
17051            continue;
17052        }
17053
17054        let codec = payload
17055            .get("payload_codec")
17056            .and_then(Value::as_str)
17057            .unwrap_or(fallback_codec);
17058        let result = payload
17059            .get("result")
17060            .or_else(|| payload.get("output"))
17061            .unwrap_or(&Value::Null);
17062        outcomes.push(Ok(ChildWorkflowAvroResult {
17063            parent: parent.clone(),
17064            child: WorkflowIdentity {
17065                workflow_id: child_workflow_id,
17066                run_id: child_workflow_run_id,
17067            },
17068            child_workflow_type,
17069            result: decode_wire_avro_value(result, codec)?,
17070        }));
17071    }
17072
17073    Ok(outcomes)
17074}
17075
17076fn payload_string(payload: &Value, key: &str) -> Option<String> {
17077    payload
17078        .get(key)
17079        .and_then(Value::as_str)
17080        .filter(|value| !value.is_empty())
17081        .map(str::to_string)
17082}
17083
17084fn recorded_activity_failure_boundary(
17085    ctx: &WorkflowContext,
17086    error: &Error,
17087) -> Option<(u64, String)> {
17088    let Error::ActivityFailed(failure) = error else {
17089        return None;
17090    };
17091    if failure.kind != ActivityFailureKind::Failed {
17092        return None;
17093    }
17094    let activity_execution_id = failure
17095        .activity_execution_id
17096        .as_deref()
17097        .filter(|value| !value.is_empty())?;
17098    let state = ctx.state.lock().ok()?;
17099    let mut matches = state.recorded_commands.iter().filter_map(|command| {
17100        let RecordedCommand::Activity {
17101            sequence,
17102            outcome: Some(Err(recorded_failure)),
17103            ..
17104        } = command
17105        else {
17106            return None;
17107        };
17108        (*sequence > 0 && recorded_failure == failure)
17109            .then_some((*sequence, activity_execution_id.to_string()))
17110    });
17111    let boundary = matches.next()?;
17112    matches.next().is_none().then_some(boundary)
17113}
17114
17115fn workflow_failure_command(
17116    error: &Error,
17117    failed_activity_boundary: Option<(u64, String)>,
17118) -> Value {
17119    let (exception_type, exception_class, properties) = match error {
17120        Error::ActivityFailed(failure) => (
17121            match failure.kind {
17122                ActivityFailureKind::Failed => "ActivityFailed",
17123                ActivityFailureKind::Cancelled => "ActivityCancelled",
17124                ActivityFailureKind::TimedOut => "ActivityTimedOut",
17125            },
17126            "durable_workflow::ActivityFailure",
17127            json!({
17128                "reason": failure.reason,
17129                "activity_execution_id": failure.activity_execution_id,
17130                "activity_attempt_id": failure.activity_attempt_id,
17131                "activity_type": failure.activity_type,
17132                "activity_class": failure.activity_class,
17133                "attempt_number": failure.attempt_number,
17134                "failure_id": failure.failure_id,
17135                "failure_category": failure.failure_category,
17136                "timeout_kind": failure.timeout_kind,
17137                "activity_non_retryable": failure.non_retryable,
17138                "activity_exception_type": failure.exception_type,
17139                "activity_exception_class": failure.exception_class,
17140                "activity_code": failure.code,
17141                "activity_exception": failure.exception,
17142            }),
17143        ),
17144        Error::ChildWorkflowFailed(failure) => (
17145            match failure.kind {
17146                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17147                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17148                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17149            },
17150            "durable_workflow::ChildWorkflowFailure",
17151            json!({
17152                "reason": failure.reason,
17153                "parent_workflow_id": failure.parent_workflow_id,
17154                "parent_workflow_run_id": failure.parent_workflow_run_id,
17155                "child_workflow_id": failure.child_workflow_id,
17156                "child_workflow_run_id": failure.child_workflow_run_id,
17157                "child_workflow_type": failure.child_workflow_type,
17158                "failure_id": failure.failure_id,
17159                "failure_category": failure.failure_category,
17160                "child_exception_type": failure.exception_type,
17161                "child_exception_class": failure.exception_class,
17162                "child_non_retryable": failure.non_retryable,
17163                "child_code": failure.code,
17164                "child_exception": failure.exception,
17165            }),
17166        ),
17167        Error::ParallelFailed(failure) => (
17168            "ParallelFailed",
17169            "durable_workflow::ParallelFailure",
17170            json!({
17171                "parallel_group_id": failure.group_id,
17172                "parallel_member_path": failure.member_path,
17173                "parallel_group_path": failure.group_path,
17174                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
17175                "cause_type": workflow_error_type(&failure.cause),
17176                "cause_message": failure.cause.to_string(),
17177            }),
17178        ),
17179        Error::SagaCompensationFailed(failure) => (
17180            "SagaCompensationFailed",
17181            "durable_workflow::SagaCompensationFailure",
17182            json!({
17183                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
17184                "initiating_failure_message": failure.initiating_failure.to_string(),
17185                "compensation_activity_type": failure.compensation_activity_type,
17186                "compensation_registration_order": failure.compensation_registration_order,
17187                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
17188                "compensation_failure_message": failure.compensation_failure.to_string(),
17189            }),
17190        ),
17191        Error::WorkflowCancellationRequested(_) => (
17192            "WorkflowCancellationRequested",
17193            "durable_workflow::WorkflowCancellationRequested",
17194            json!({"reason": "cancelled"}),
17195        ),
17196        Error::CooperativeCancellationRequested(cancellation) => (
17197            "WorkflowCancellationRequested",
17198            "durable_workflow::CooperativeCancellationRequested",
17199            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
17200                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
17201        ),
17202        Error::CancellationScopeRequested(cancellation) => (
17203            "WorkflowCancellationRequested",
17204            "durable_workflow::CancellationScopeRequested",
17205            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
17206                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
17207                "cancellation":cancellation.context.to_value()}),
17208        ),
17209        Error::NonDeterministicReplay(_) => (
17210            "NonDeterministicReplay",
17211            "durable_workflow::Error",
17212            Value::Null,
17213        ),
17214        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
17215    };
17216    let non_retryable = match error {
17217        Error::ActivityFailed(failure) => failure.non_retryable,
17218        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17219        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17220        Error::SagaCompensationFailed(failure) => {
17221            workflow_error_non_retryable(&failure.compensation_failure)
17222        }
17223        Error::WorkflowCancellationRequested(_)
17224        | Error::CooperativeCancellationRequested(_)
17225        | Error::CancellationScopeRequested(_) => true,
17226        Error::NonDeterministicReplay(_) => true,
17227        _ => false,
17228    };
17229
17230    let mut command = json!({
17231        "type": "fail_workflow",
17232        "message": error.to_string(),
17233        "exception_type": exception_type,
17234        "exception_class": exception_class,
17235        "non_retryable": non_retryable,
17236        "exception": {
17237            "type": exception_type,
17238            "class": exception_class,
17239            "message": error.to_string(),
17240            "properties": properties,
17241        }
17242    });
17243
17244    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
17245        command["failed_step_sequence"] = json!(sequence);
17246        command["failed_activity_execution_id"] = json!(activity_execution_id);
17247    }
17248
17249    command
17250}
17251
17252fn workflow_error_type(error: &Error) -> &'static str {
17253    match error {
17254        Error::ActivityFailed(failure) => match failure.kind {
17255            ActivityFailureKind::Failed => "ActivityFailed",
17256            ActivityFailureKind::Cancelled => "ActivityCancelled",
17257            ActivityFailureKind::TimedOut => "ActivityTimedOut",
17258        },
17259        Error::ChildWorkflowFailed(failure) => match failure.kind {
17260            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17261            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17262            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17263        },
17264        Error::ParallelFailed(_) => "ParallelFailed",
17265        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
17266        Error::WorkflowCancellationRequested(_)
17267        | Error::CooperativeCancellationRequested(_)
17268        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
17269        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
17270        _ => "RustWorkflowError",
17271    }
17272}
17273
17274fn workflow_error_non_retryable(error: &Error) -> bool {
17275    match error {
17276        Error::ActivityFailed(failure) => failure.non_retryable,
17277        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17278        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17279        Error::SagaCompensationFailed(failure) => {
17280            workflow_error_non_retryable(&failure.compensation_failure)
17281        }
17282        Error::WorkflowCancellationRequested(_)
17283        | Error::CooperativeCancellationRequested(_)
17284        | Error::CancellationScopeRequested(_)
17285        | Error::NonDeterministicReplay(_) => true,
17286        _ => false,
17287    }
17288}
17289
17290fn workflow_task_integrity_error(error: &Error) -> bool {
17291    matches!(
17292        error,
17293        Error::NonDeterministicReplay(_)
17294            | Error::Protocol(_)
17295            | Error::CancellationScopeExecutionUnavailable
17296            | Error::MissingWorkflowCommandIdentity
17297            | Error::WorkflowStatePoisoned
17298    )
17299}
17300
17301fn decode_signal_event_arguments(
17302    event: &HistoryEvent,
17303    fallback_codec: &str,
17304) -> Result<Vec<AvroValue>> {
17305    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17306    validate_payload_codec(codec)?;
17307    let raw = signal_history_payload(&event.payload);
17308    let decoded = match raw.filter(|value| !value.is_null()) {
17309        Some(value) => decode_wire_avro_value(value, codec)?,
17310        None => AvroValue::Array(Vec::new()),
17311    };
17312    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17313        unreachable!("normalize_avro_arguments always returns an array");
17314    };
17315    Ok(arguments)
17316}
17317
17318fn decode_update_event_arguments(
17319    event: &HistoryEvent,
17320    fallback_codec: &str,
17321) -> Result<Vec<AvroValue>> {
17322    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17323    validate_payload_codec(codec)?;
17324    let decoded = match event
17325        .payload
17326        .get("arguments")
17327        .filter(|value| !value.is_null())
17328    {
17329        Some(value) => decode_wire_avro_value(value, codec)?,
17330        None => AvroValue::Array(Vec::new()),
17331    };
17332    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17333        unreachable!("normalize_avro_arguments always returns an array");
17334    };
17335    Ok(arguments)
17336}
17337
17338fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17339    let Some(export_events) = task
17340        .history_export
17341        .as_ref()
17342        .and_then(|export| export.get("history_events"))
17343        .and_then(Value::as_array)
17344    else {
17345        return Ok(());
17346    };
17347
17348    if export_events.len() > task.history_events.len() {
17349        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
17350    }
17351
17352    Ok(())
17353}
17354
17355fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17356    let Some(export) = task.history_export.as_ref() else {
17357        return Ok(());
17358    };
17359    let signals = export
17360        .get("signals")
17361        .and_then(Value::as_array)
17362        .cloned()
17363        .unwrap_or_default();
17364    let activities = export
17365        .get("activities")
17366        .and_then(Value::as_array)
17367        .cloned()
17368        .unwrap_or_default();
17369    let export_codec = export
17370        .get("payloads")
17371        .and_then(|payloads| payloads.get("codec"))
17372        .and_then(Value::as_str)
17373        .unwrap_or(&task.payload_codec)
17374        .to_string();
17375    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
17376
17377    for event in &mut task.history_events {
17378        if event.event_type == "ActivityCompleted" {
17379            let sequence = event
17380                .payload
17381                .get("sequence")
17382                .or_else(|| event.payload.get("workflow_sequence"))
17383                .and_then(value_as_u64);
17384            let Some(activity) = sequence.and_then(|sequence| {
17385                activities.iter().find(|activity| {
17386                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
17387                })
17388            }) else {
17389                continue;
17390            };
17391            let Some(payload) = event.payload.as_object_mut() else {
17392                continue;
17393            };
17394            if missing_payload(payload.get("result")) {
17395                if let Some(result) = activity
17396                    .get("result")
17397                    .filter(|value| !missing_payload(Some(value)))
17398                {
17399                    payload.insert("result".to_string(), result.clone());
17400                }
17401            }
17402            for field in ["payload_codec", "activity_type"] {
17403                if payload
17404                    .get(field)
17405                    .and_then(Value::as_str)
17406                    .unwrap_or_default()
17407                    .is_empty()
17408                {
17409                    if let Some(value) = activity.get(field) {
17410                        payload.insert(field.to_string(), value.clone());
17411                    }
17412                }
17413            }
17414            continue;
17415        }
17416
17417        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
17418            continue;
17419        }
17420        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17421        let command_id = event
17422            .payload
17423            .get("workflow_command_id")
17424            .or_else(|| event.raw.get("workflow_command_id"))
17425            .and_then(Value::as_str);
17426        let signal_name = event
17427            .payload
17428            .get("signal_name")
17429            .and_then(Value::as_str)
17430            .unwrap_or_default()
17431            .to_string();
17432        let matched = signals
17433            .iter()
17434            .find(|signal| {
17435                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
17436            })
17437            .or_else(|| {
17438                signals.iter().find(|signal| {
17439                    command_id.is_some()
17440                        && signal.get("command_id").and_then(Value::as_str) == command_id
17441                })
17442            })
17443            .or_else(|| {
17444                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
17445                let signal = signals
17446                    .iter()
17447                    .filter(|signal| {
17448                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
17449                    })
17450                    .nth(*offset);
17451                if signal.is_some() {
17452                    *offset += 1;
17453                }
17454                signal
17455            });
17456        let Some(signal) = matched else {
17457            continue;
17458        };
17459        let signal_codec = signal
17460            .get("payload_codec")
17461            .and_then(Value::as_str)
17462            .unwrap_or(&export_codec);
17463        let Some(payload) = event.payload.as_object_mut() else {
17464            continue;
17465        };
17466        if missing_payload(payload.get("arguments")) {
17467            if let Some(arguments) = signal
17468                .get("arguments")
17469                .filter(|value| !missing_payload(Some(value)))
17470            {
17471                let envelope = match arguments {
17472                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
17473                    other => other.clone(),
17474                };
17475                payload.insert("arguments".to_string(), envelope);
17476            }
17477        }
17478        if payload
17479            .get("payload_codec")
17480            .and_then(Value::as_str)
17481            .unwrap_or_default()
17482            .is_empty()
17483        {
17484            payload.insert("payload_codec".to_string(), json!(signal_codec));
17485        }
17486    }
17487
17488    Ok(())
17489}
17490
17491fn missing_payload(value: Option<&Value>) -> bool {
17492    match value {
17493        None | Some(Value::Null) => true,
17494        Some(Value::String(value)) => value.is_empty(),
17495        Some(_) => false,
17496    }
17497}
17498
17499fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
17500    history_signal_events(
17501        &task.history_events,
17502        task.history_export.as_ref(),
17503        &task.payload_codec,
17504    )
17505}
17506
17507fn history_signal_events(
17508    history_events: &[HistoryEvent],
17509    history_export: Option<&Value>,
17510    payload_codec: &str,
17511) -> Result<Vec<QuerySignal>> {
17512    let export_signals = history_export
17513        .and_then(|export| export.get("signals"))
17514        .and_then(Value::as_array)
17515        .cloned()
17516        .unwrap_or_default();
17517    let export_codec = history_export
17518        .and_then(|export| export.get("payloads"))
17519        .and_then(|payloads| payloads.get("codec"))
17520        .and_then(Value::as_str)
17521        .unwrap_or(payload_codec);
17522    let mut name_offsets: HashMap<String, usize> = HashMap::new();
17523    let mut signals: Vec<QuerySignal> = Vec::new();
17524    let mut signal_indices = HashMap::new();
17525    let mut command_indices = HashMap::new();
17526
17527    for event in history_events {
17528        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
17529            continue;
17530        }
17531
17532        let name = event
17533            .payload
17534            .get("signal_name")
17535            .and_then(Value::as_str)
17536            .unwrap_or_default();
17537        if name.is_empty() {
17538            continue;
17539        }
17540        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17541        let command_id = event
17542            .payload
17543            .get("workflow_command_id")
17544            .or_else(|| event.raw.get("workflow_command_id"))
17545            .and_then(Value::as_str);
17546        let matched_export = export_signals
17547            .iter()
17548            .find(|candidate| {
17549                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
17550            })
17551            .or_else(|| {
17552                export_signals.iter().find(|candidate| {
17553                    command_id.is_some()
17554                        && candidate.get("command_id").and_then(Value::as_str) == command_id
17555                })
17556            })
17557            .or_else(|| {
17558                let offset = name_offsets.entry(name.to_string()).or_default();
17559                let candidate = export_signals
17560                    .iter()
17561                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
17562                    .nth(*offset);
17563                if candidate.is_some() {
17564                    *offset += 1;
17565                }
17566                candidate
17567            });
17568        let codec = event
17569            .payload
17570            .get("payload_codec")
17571            .and_then(Value::as_str)
17572            .or_else(|| {
17573                matched_export
17574                    .and_then(|signal| signal.get("payload_codec"))
17575                    .and_then(Value::as_str)
17576            })
17577            .unwrap_or(export_codec);
17578        let raw_arguments = signal_history_payload(&event.payload)
17579            .filter(|value| !value.is_null())
17580            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
17581        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
17582        let workflow_sequence = event
17583            .payload
17584            .get("workflow_sequence")
17585            .and_then(value_as_u64)
17586            .or_else(|| {
17587                matched_export
17588                    .and_then(|signal| signal.get("workflow_sequence"))
17589                    .and_then(value_as_u64)
17590            });
17591
17592        let id = signal_id.or_else(|| {
17593            matched_export
17594                .and_then(|signal| signal.get("id"))
17595                .and_then(Value::as_str)
17596        });
17597        let command_id = command_id.or_else(|| {
17598            matched_export
17599                .and_then(|signal| signal.get("command_id"))
17600                .and_then(Value::as_str)
17601        });
17602        let duplicate = id
17603            .and_then(|id| signal_indices.get(id))
17604            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
17605            .copied();
17606        let index = duplicate.unwrap_or(signals.len());
17607        if let Some(index) = duplicate {
17608            let original = &mut signals[index];
17609            let same_arguments = if event.event_type == "SignalApplied" {
17610                if let Some(value) = event.payload.get("value") {
17611                    let expected = match original.avro_arguments.as_slice() {
17612                        [] => AvroValue::Boolean(true),
17613                        [value] => value.clone(),
17614                        values => AvroValue::Array(values.to_vec()),
17615                    };
17616                    let applied = decode_wire_avro_value(value, codec)?;
17617                    applied == expected
17618                        || applied == AvroValue::Array(original.avro_arguments.clone())
17619                } else {
17620                    original.avro_arguments == avro_arguments
17621                }
17622            } else {
17623                original.avro_arguments == avro_arguments
17624            };
17625            if original.name != name
17626                || !same_arguments
17627                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
17628            {
17629                return Err(Error::Codec("conflicting committed signal identity".into()));
17630            }
17631            if original.id.is_none() {
17632                original.id = id.map(str::to_string);
17633            }
17634            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
17635        } else {
17636            signals.push(QuerySignal {
17637                id: id.map(str::to_string),
17638                name: name.to_string(),
17639                arguments,
17640                avro_arguments,
17641                workflow_sequence,
17642            });
17643        }
17644        if let Some(id) = id {
17645            signal_indices.insert(id.to_string(), index);
17646        }
17647        if let Some(id) = command_id {
17648            command_indices.insert(id.to_string(), index);
17649        }
17650    }
17651
17652    if signals.is_empty() {
17653        for signal in export_signals {
17654            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17655                continue;
17656            }
17657            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17658                continue;
17659            };
17660            let codec = signal
17661                .get("payload_codec")
17662                .and_then(Value::as_str)
17663                .unwrap_or(export_codec);
17664            let (arguments, avro_arguments) =
17665                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17666            signals.push(QuerySignal {
17667                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17668                name: name.to_string(),
17669                arguments,
17670                avro_arguments,
17671                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17672            });
17673        }
17674        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17675    }
17676
17677    Ok(signals)
17678}
17679
17680fn decode_query_signal_arguments(
17681    raw: Option<&Value>,
17682    codec: &str,
17683) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17684    validate_payload_codec(codec)?;
17685    let decoded = match raw.filter(|value| !value.is_null()) {
17686        Some(value) => decode_wire_avro_value(value, codec)?,
17687        None => AvroValue::Array(Vec::new()),
17688    };
17689    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17690        unreachable!("normalize_avro_arguments always returns an array");
17691    };
17692    let arguments = avro_arguments
17693        .iter()
17694        .cloned()
17695        .map(AvroValue::into_json)
17696        .collect::<Result<Vec<_>>>()?;
17697    Ok((arguments, avro_arguments))
17698}
17699
17700fn value_as_u64(value: &Value) -> Option<u64> {
17701    value
17702        .as_u64()
17703        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17704}
17705
17706#[cfg(test)]
17707mod tests {
17708    use super::*;
17709    mod activity_cancellation_policies;
17710    mod cancellation_scope_admission;
17711    mod cancellation_scope_authoring;
17712    mod cancellation_scope_history;
17713    mod cancellation_scope_opening;
17714    mod cancellation_scope_replay;
17715    mod child_workflow_policies;
17716    mod cooperative_cancellation;
17717    mod local_activity;
17718    mod runtime_payloads;
17719    mod runtime_uploads;
17720    mod worker_session;
17721    use std::{
17722        fs,
17723        io::{Read, Write},
17724        net::{SocketAddr, TcpListener, TcpStream},
17725        process::Command as ProcessCommand,
17726        sync::atomic::AtomicUsize,
17727        thread,
17728    };
17729
17730    #[derive(Clone, Copy, Debug)]
17731    enum InvalidTaskPayloadCodec {
17732        Missing,
17733        Null,
17734        NonString,
17735    }
17736
17737    impl InvalidTaskPayloadCodec {
17738        fn label(self) -> &'static str {
17739            match self {
17740                Self::Missing => "missing",
17741                Self::Null => "null",
17742                Self::NonString => "non-string",
17743            }
17744        }
17745
17746        fn apply(self, task: &mut Value) {
17747            let task = task.as_object_mut().expect("task fixture object");
17748            match self {
17749                Self::Missing => {
17750                    task.remove("payload_codec");
17751                }
17752                Self::Null => {
17753                    task.insert("payload_codec".to_string(), Value::Null);
17754                }
17755                Self::NonString => {
17756                    task.insert("payload_codec".to_string(), json!(42));
17757                }
17758            }
17759        }
17760    }
17761
17762    fn fixture_envelope(value: Value) -> Value {
17763        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
17764    }
17765
17766    fn fixture_blob(value: Value) -> String {
17767        encode_payload(&value, DEFAULT_CODEC)
17768            .expect("encode Avro test fixture")
17769            .blob
17770    }
17771
17772    #[test]
17773    fn client_builder_rejects_the_sdk_owned_api_suffix() {
17774        for base_url in [
17775            "http://127.0.0.1:8080/api",
17776            "http://localhost:8080/api/",
17777            "https://runtime.example.test/namespaces/orders/api",
17778        ] {
17779            let error = Client::builder(base_url)
17780                .build()
17781                .expect_err("SDK-owned /api suffix must be rejected during build");
17782
17783            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
17784            assert!(
17785                error.to_string().contains("SDK appends /api automatically"),
17786                "the validation error must explain how to fix the endpoint"
17787            );
17788        }
17789    }
17790
17791    #[test]
17792    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
17793        for (base_url, expected) in [
17794            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
17795            (
17796                "http://localhost:8080/durable-workflow/",
17797                "http://localhost:8080/durable-workflow",
17798            ),
17799            (
17800                "https://runtime.example.test/namespaces/orders",
17801                "https://runtime.example.test/namespaces/orders",
17802            ),
17803            (
17804                "https://runtime.example.test/gateway/api/namespaces/orders",
17805                "https://runtime.example.test/gateway/api/namespaces/orders",
17806            ),
17807            (
17808                "https://api.example.test/runtime/orders/",
17809                "https://api.example.test/runtime/orders",
17810            ),
17811        ] {
17812            let client = Client::builder(base_url)
17813                .build()
17814                .expect("Server and Cloud runtime base URL must remain valid");
17815
17816            assert_eq!(client.base_url, expected);
17817        }
17818    }
17819
17820    #[test]
17821    fn workflow_completion_uses_the_additive_command_protocol_floor() {
17822        assert_eq!(
17823            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
17824            MINIMUM_WORKER_PROTOCOL_VERSION
17825        );
17826        assert_eq!(
17827            workflow_completion_protocol_version(&[json!({
17828                "type": "upsert_search_attributes",
17829                "attributes": {"OrderStatus": "waiting"},
17830            })]),
17831            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
17832        );
17833        assert_eq!(
17834            workflow_completion_protocol_version(&[json!({
17835                "type": "upsert_search_attributes",
17836                "attributes": {"OrderStatus": "waiting"},
17837                "attribute_types": {"OrderStatus": "keyword"},
17838            })]),
17839            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
17840        );
17841        assert_eq!(
17842            workflow_completion_protocol_version(&[
17843                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
17844                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17845            ]),
17846            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
17847        );
17848        assert_eq!(
17849            workflow_completion_protocol_version(&[
17850                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
17851                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17852            ]),
17853            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
17854        );
17855        assert_eq!(
17856            workflow_completion_protocol_version(&[json!({
17857                "type": "open_condition_wait",
17858                "condition_wait_occurrence_id": "rust:condition-wait:0",
17859                "condition_key": "ready",
17860            })]),
17861            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17862        );
17863        assert_eq!(
17864            workflow_completion_protocol_version_with_message_streams(
17865                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
17866                true,
17867            ),
17868            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
17869        );
17870        assert_eq!(
17871            workflow_completion_protocol_version_with_message_streams(
17872                &[json!({
17873                    "type": "open_condition_wait",
17874                    "condition_wait_occurrence_id": "rust:condition-wait:0",
17875                    "condition_key": "ready",
17876                })],
17877                true,
17878            ),
17879            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17880        );
17881    }
17882
17883    #[test]
17884    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
17885        let manifest = portable_worker_affinity_capability_manifest();
17886
17887        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
17888            assert_eq!(manifest[capability]["supported"], json!(false));
17889            assert_eq!(
17890                manifest[capability]["minimum_protocol_version"],
17891                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
17892            );
17893            assert!(manifest[capability]["reason"]
17894                .as_str()
17895                .is_some_and(|reason| !reason.is_empty()));
17896        }
17897    }
17898
17899    fn typed_fidelity_probe() -> AvroValue {
17900        AvroValue::Map(BTreeMap::from([
17901            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
17902            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
17903            (
17904                "numeric".to_string(),
17905                AvroValue::Map(BTreeMap::from([
17906                    ("0".to_string(), AvroValue::String("zero".to_string())),
17907                    ("1".to_string(), AvroValue::String("one".to_string())),
17908                ])),
17909            ),
17910            (
17911                "nested".to_string(),
17912                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
17913                    "enabled".to_string(),
17914                    AvroValue::Boolean(true),
17915                )]))]),
17916            ),
17917            (
17918                "projection_collisions".to_string(),
17919                AvroValue::Array(projection_collision_probe()),
17920            ),
17921        ]))
17922    }
17923
17924    fn projection_collision_probe() -> Vec<AvroValue> {
17925        vec![
17926            AvroValue::Map(BTreeMap::from([
17927                ("$type".to_string(), AvroValue::String("bytes".to_string())),
17928                (
17929                    "base64".to_string(),
17930                    AvroValue::String("ordinary user text".to_string()),
17931                ),
17932            ])),
17933            AvroValue::Map(BTreeMap::from([
17934                ("$type".to_string(), AvroValue::String("map".to_string())),
17935                (
17936                    "entries".to_string(),
17937                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
17938                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
17939                        (
17940                            "value".to_string(),
17941                            AvroValue::String("user map".to_string()),
17942                        ),
17943                    ]))]),
17944                ),
17945            ])),
17946        ]
17947    }
17948
17949    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17950    struct TypedContract {
17951        nested: TypedNested,
17952        mode: TypedMode,
17953        optional: Option<String>,
17954        absent: Option<String>,
17955        items: Vec<i64>,
17956        labels: BTreeMap<String, String>,
17957        bytes: serde_bytes::ByteBuf,
17958        signed: i64,
17959        finite: f64,
17960    }
17961
17962    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17963    struct TypedNested {
17964        enabled: bool,
17965    }
17966
17967    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17968    enum TypedMode {
17969        Detailed { label: String },
17970    }
17971
17972    fn typed_contract() -> TypedContract {
17973        TypedContract {
17974            nested: TypedNested { enabled: true },
17975            mode: TypedMode::Detailed {
17976                label: "compiler-checked".to_string(),
17977            },
17978            optional: Some("present".to_string()),
17979            absent: None,
17980            items: vec![i64::MIN, 0, i64::MAX],
17981            labels: BTreeMap::from([
17982                ("language".to_string(), "rust".to_string()),
17983                ("wire".to_string(), "avro".to_string()),
17984            ]),
17985            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
17986            signed: -9_223_372_036_854_775_000,
17987            finite: 12.5,
17988        }
17989    }
17990
17991    #[derive(Clone, Debug, Default, PartialEq)]
17992    struct ReplayCounterState {
17993        loaded: Option<String>,
17994        count: i64,
17995        finished: bool,
17996    }
17997
17998    fn replay_counter_worker() -> Worker {
17999        let client = Client::new("http://127.0.0.1:8080").expect("client");
18000        let mut worker = Worker::new(client, "rust-workers");
18001        worker.register_replayed_workflow(
18002            "replay-counter",
18003            ReplayCounterState::default,
18004            |ctx, _input, state| async move {
18005                let loaded = ctx.activity("load-counter", json!([])).await?;
18006                state.update(|current| {
18007                    current.loaded = loaded.as_str().map(str::to_string);
18008                })?;
18009                for _ in 0..2 {
18010                    let signal = ctx.wait_signal("increment").await?;
18011                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
18012                    state.update(|current| current.count += amount)?;
18013                }
18014                state.update(|current| current.finished = true)?;
18015                state.read(|current| Ok(json!(current.count)))?
18016            },
18017        );
18018        worker.register_replayed_query::<ReplayCounterState, _, _>(
18019            "replay-counter",
18020            "current",
18021            |_ctx, state, _args| async move {
18022                Ok(json!({
18023                    "loaded": state.loaded,
18024                    "count": state.count,
18025                    "finished": state.finished,
18026                }))
18027            },
18028        );
18029        worker.register_replayed_query::<ReplayCounterState, _, _>(
18030            "replay-counter",
18031            "detached-mutation",
18032            |_ctx, state, _args| async move {
18033                let mut detached = (*state).clone();
18034                detached.count = 999;
18035                Ok(json!(detached.count))
18036            },
18037        );
18038        worker.register_replayed_query::<ReplayCounterState, _, _>(
18039            "replay-counter",
18040            "failed-mutation",
18041            |_ctx, state, _args| async move {
18042                let mut detached = (*state).clone();
18043                detached.count = 999;
18044                Err(Error::WorkerLoop("query refused".to_string()))
18045            },
18046        );
18047        worker
18048    }
18049
18050    fn replay_counter_query(
18051        query_name: &str,
18052        history_events: Value,
18053        run_status: &str,
18054    ) -> QueryTask {
18055        let arguments = fixture_envelope(json!([]));
18056        serde_json::from_value(json!({
18057            "query_task_id": format!("query-{query_name}"),
18058            "workflow_type": "replay-counter",
18059            "query_name": query_name,
18060            "payload_codec": DEFAULT_CODEC,
18061            "workflow_arguments": arguments.clone(),
18062            "query_arguments": arguments,
18063            "history_events": history_events,
18064            "run_status": run_status,
18065        }))
18066        .expect("query task")
18067    }
18068
18069    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
18070        workflow_context_with_codec(history, DEFAULT_CODEC)
18071    }
18072
18073    fn workflow_context_with_codec(
18074        history: Vec<HistoryEvent>,
18075        payload_codec: &str,
18076    ) -> WorkflowContext {
18077        WorkflowContext {
18078            cancellation_scope_id: "root".into(),
18079            state: Arc::new(Mutex::new(
18080                WorkflowState::new_with_identity(
18081                    history,
18082                    None,
18083                    None,
18084                    "rust-workers".to_string(),
18085                    payload_codec.to_string(),
18086                    None,
18087                )
18088                .expect("valid workflow history"),
18089            )),
18090        }
18091    }
18092
18093    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
18094        HistoryEvent {
18095            event_type: event_type.to_string(),
18096            payload,
18097            raw: HashMap::new(),
18098        }
18099    }
18100
18101    fn parallel_path_entry(
18102        kind: &str,
18103        base: u64,
18104        size: usize,
18105        index: usize,
18106    ) -> ParallelGroupMetadata {
18107        parallel_group_entry(base, size, index, kind)
18108    }
18109
18110    fn parallel_history_event(
18111        event_type: &str,
18112        sequence: u64,
18113        identity_field: &str,
18114        identity: &str,
18115        path: Vec<ParallelGroupMetadata>,
18116        result: Option<Value>,
18117    ) -> HistoryEvent {
18118        let mut payload = serde_json::Map::from_iter([
18119            ("sequence".to_string(), json!(sequence)),
18120            (identity_field.to_string(), json!(identity)),
18121        ]);
18122        let inner = path.last().expect("parallel history path");
18123        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
18124        payload.insert("parallel_group_path".to_string(), json!(path));
18125        if let Some(result) = result {
18126            let field = if event_type == "ChildRunCompleted" {
18127                "result"
18128            } else {
18129                "result"
18130            };
18131            payload.insert(field.to_string(), fixture_envelope(result));
18132            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
18133        }
18134        history_event(event_type, Value::Object(payload))
18135    }
18136
18137    fn nested_parallel_operations() -> Vec<ParallelOperation> {
18138        vec![
18139            ParallelOperation::activity("first", json!([])),
18140            ParallelOperation::group(vec![
18141                ParallelOperation::child_workflow(
18142                    "second",
18143                    ChildWorkflowOptions::new("child-workers"),
18144                    json!([]),
18145                ),
18146                ParallelOperation::activity("third", json!([])),
18147            ]),
18148        ]
18149    }
18150
18151    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
18152        let outer = [
18153            parallel_path_entry("mixed", 1, 3, 0),
18154            parallel_path_entry("mixed", 1, 3, 1),
18155            parallel_path_entry("mixed", 1, 3, 2),
18156        ];
18157        [
18158            vec![outer[0].clone()],
18159            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
18160            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
18161        ]
18162    }
18163
18164    #[test]
18165    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
18166        let ctx = workflow_context(Vec::new());
18167        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18168        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18169
18170        assert!(matches!(
18171            call.as_mut().poll(&mut task_context),
18172            Poll::Pending
18173        ));
18174        let commands = ctx.take_commands().expect("parallel commands");
18175        assert_eq!(
18176            commands
18177                .iter()
18178                .map(|command| command["type"].as_str().unwrap_or_default())
18179                .collect::<Vec<_>>(),
18180            [
18181                "schedule_activity",
18182                "start_child_workflow",
18183                "schedule_activity"
18184            ]
18185        );
18186        let paths = nested_parallel_paths();
18187        for (command, path) in commands.iter().zip(paths) {
18188            assert_eq!(command["parallel_group_path"], json!(path));
18189            assert_eq!(
18190                command["parallel_group_id"],
18191                json!(path.last().expect("inner group").parallel_group_id)
18192            );
18193        }
18194    }
18195
18196    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
18197        let paths = nested_parallel_paths();
18198        let third = parallel_history_event(
18199            "ActivityCompleted",
18200            3,
18201            "activity_type",
18202            "third",
18203            paths[2].clone(),
18204            Some(json!("three")),
18205        );
18206        vec![
18207            parallel_history_event(
18208                "ActivityCompleted",
18209                1,
18210                "activity_type",
18211                "first",
18212                paths[0].clone(),
18213                Some(json!("one")),
18214            ),
18215            parallel_history_event(
18216                "ChildWorkflowScheduled",
18217                2,
18218                "child_workflow_type",
18219                "second",
18220                paths[1].clone(),
18221                None,
18222            ),
18223            parallel_history_event(
18224                "ChildRunCompleted",
18225                2,
18226                "child_workflow_type",
18227                "second",
18228                paths[1].clone(),
18229                Some(json!("two")),
18230            ),
18231            third.clone(),
18232            third,
18233        ]
18234    }
18235
18236    #[test]
18237    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
18238        for _restart_or_completed_replay in 0..2 {
18239            let ctx = workflow_context(completed_nested_parallel_history());
18240            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18241            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18242            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
18243                panic!("completed nested parallel history must replay");
18244            };
18245            assert_eq!(
18246                results,
18247                vec![
18248                    ParallelResult::Activity(json!("one")),
18249                    ParallelResult::Group(vec![
18250                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
18251                            parent: WorkflowIdentity {
18252                                workflow_id: None,
18253                                run_id: None,
18254                            },
18255                            child: WorkflowIdentity {
18256                                workflow_id: None,
18257                                run_id: None,
18258                            },
18259                            child_workflow_type: Some("second".to_string()),
18260                            result: json!("two"),
18261                        }),
18262                        ParallelResult::Activity(json!("three")),
18263                    ]),
18264                ]
18265            );
18266            assert!(ctx.take_commands().expect("commands").is_empty());
18267            ctx.ensure_history_consumed().expect("history consumed");
18268        }
18269    }
18270
18271    #[test]
18272    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
18273        let paths = nested_parallel_paths();
18274        let history = vec![
18275            parallel_history_event(
18276                "ActivityCompleted",
18277                1,
18278                "activity_type",
18279                "first",
18280                paths[0].clone(),
18281                Some(json!("one")),
18282            ),
18283            parallel_history_event(
18284                "ChildWorkflowScheduled",
18285                2,
18286                "child_workflow_type",
18287                "second",
18288                paths[1].clone(),
18289                None,
18290            ),
18291            parallel_history_event(
18292                "ChildRunFailed",
18293                2,
18294                "child_workflow_type",
18295                "second",
18296                paths[1].clone(),
18297                None,
18298            ),
18299            parallel_history_event(
18300                "ActivityCompleted",
18301                3,
18302                "activity_type",
18303                "third",
18304                paths[2].clone(),
18305                Some(json!("late")),
18306            ),
18307        ];
18308        let ctx = workflow_context(history);
18309        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18310        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18311        let outcome = call.as_mut().poll(&mut task_context);
18312        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
18313            panic!("one failed child must return a typed partial failure: {outcome:?}");
18314        };
18315        assert_eq!(failure.member_path, [1, 0]);
18316        assert_eq!(failure.group_id, "parallel-calls:1:3");
18317        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
18318        assert_eq!(
18319            failure
18320                .completed
18321                .iter()
18322                .map(|completion| completion.member_path.clone())
18323                .collect::<Vec<_>>(),
18324            [vec![0], vec![1, 1]]
18325        );
18326    }
18327
18328    #[test]
18329    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
18330        let paths = nested_parallel_paths();
18331        let history = vec![
18332            parallel_history_event(
18333                "ActivityScheduled",
18334                1,
18335                "activity_type",
18336                "first",
18337                paths[0].clone(),
18338                None,
18339            ),
18340            parallel_history_event(
18341                "ChildWorkflowScheduled",
18342                2,
18343                "child_workflow_type",
18344                "second",
18345                paths[1].clone(),
18346                None,
18347            ),
18348            parallel_history_event(
18349                "ActivityScheduled",
18350                3,
18351                "activity_type",
18352                "third",
18353                paths[2].clone(),
18354                None,
18355            ),
18356        ];
18357        for _restart in 0..2 {
18358            let ctx = workflow_context(history.clone());
18359            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18360            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18361            let outcome = call.as_mut().poll(&mut task_context);
18362            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
18363            assert!(ctx.take_commands().expect("commands").is_empty());
18364        }
18365    }
18366
18367    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
18368        vec![selection_group_entry(
18369            1,
18370            2,
18371            index,
18372            "activity",
18373            &SelectionMemberMetadata {
18374                key: SelectionKey::Name(key.to_string()),
18375                index,
18376                base_sequence: index as u64 + 1,
18377                size: 1,
18378                kind: "activity".to_string(),
18379            },
18380        )]
18381    }
18382
18383    fn selection_activity_event(
18384        event_type: &str,
18385        index: usize,
18386        key: &str,
18387        result: Option<Value>,
18388    ) -> HistoryEvent {
18389        let sequence = index as u64 + 1;
18390        let mut event = parallel_history_event(
18391            event_type,
18392            sequence,
18393            "activity_type",
18394            &format!("{key}-activity"),
18395            selection_path(index, key),
18396            result,
18397        );
18398        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
18399        event.raw.insert(
18400            "id".to_string(),
18401            json!(if event_type == "ActivityCompleted" {
18402                format!("event-{key}")
18403            } else {
18404                format!("{event_type}-{key}")
18405            }),
18406        );
18407        event
18408    }
18409
18410    fn selection_winner_marker() -> HistoryEvent {
18411        history_event(
18412            "SelectionResolved",
18413            json!({
18414                "selection_group_id": "select-calls:1:2",
18415                "selection_group_base_sequence": 1,
18416                "selection_group_size": 2,
18417                "member_key": "fast",
18418                "member_index": 1,
18419                "member_base_sequence": 2,
18420                "member_size": 1,
18421                "operation_kind": "activity",
18422                "operation_identity": "activity-fast",
18423                "outcome": "completed",
18424                "resolution_event_id": "event-fast",
18425                "resolution_event_type": "ActivityCompleted",
18426            }),
18427        )
18428    }
18429
18430    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
18431        ctx.select_keyed(vec![
18432            (
18433                "slow",
18434                ParallelOperation::activity_with_options(
18435                    "slow-activity",
18436                    ActivityOptions::new().task_queue("default"),
18437                    json!([]),
18438                ),
18439            ),
18440            (
18441                "fast",
18442                ParallelOperation::activity_with_options(
18443                    "fast-activity",
18444                    ActivityOptions::new().task_queue("default"),
18445                    json!([]),
18446                ),
18447            ),
18448        ])
18449    }
18450
18451    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
18452        let ctx = workflow_context(history);
18453        let mut call = Box::pin(keyed_activity_selection(&ctx));
18454        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18455        let selected = match call.as_mut().poll(&mut task_context) {
18456            Poll::Ready(Ok(selected)) => selected,
18457            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
18458            Poll::Pending => panic!("persisted selection winner must replay without pending"),
18459        };
18460        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
18461        assert_eq!(
18462            selected.value,
18463            Some(ParallelResult::Activity(json!("winner-value")))
18464        );
18465        let slow = selected
18466            .handle(&SelectionKey::Name("slow".to_string()))
18467            .expect("slow handle")
18468            .clone();
18469        let mut await_slow = Box::pin(slow.await_result());
18470        assert!(matches!(
18471            await_slow.as_mut().poll(&mut task_context),
18472            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
18473        ));
18474        assert!(ctx.take_commands().expect("commands").is_empty());
18475    }
18476
18477    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
18478
18479    fn canonical_selection_history() -> Vec<HistoryEvent> {
18480        const FIXTURE: &[u8] =
18481            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
18482        assert_eq!(
18483            format!("{:x}", Sha256::digest(FIXTURE)),
18484            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18485        );
18486        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
18487
18488        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
18489    }
18490
18491    #[test]
18492    fn selection_fresh_process_entrypoint() {
18493        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
18494            return;
18495        };
18496        let persisted = fs::read(path).expect("persisted selection history");
18497        assert_eq!(
18498            format!("{:x}", Sha256::digest(&persisted)),
18499            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18500        );
18501        let fixture: Value =
18502            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
18503        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
18504            .expect("valid persisted selection history");
18505
18506        assert_persisted_selection_replay(history);
18507    }
18508
18509    #[test]
18510    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
18511        let ctx = workflow_context(Vec::new());
18512        let mut call = Box::pin(keyed_activity_selection(&ctx));
18513        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18514
18515        assert!(matches!(
18516            call.as_mut().poll(&mut task_context),
18517            Poll::Pending
18518        ));
18519        let commands = ctx.take_commands().expect("selection commands");
18520        assert_eq!(commands.len(), 2);
18521        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
18522        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
18523        assert!(commands.iter().all(|command| {
18524            command["parallel_group_id"] == json!("select-calls:1:2")
18525                && command["parallel_group_mode"] == json!("select")
18526        }));
18527    }
18528
18529    #[test]
18530    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
18531        let ctx = workflow_context(Vec::new());
18532        let mut invalid = Box::pin(ctx.select_keyed(vec![(
18533            "",
18534            ParallelOperation::activity("invalid", json!([])),
18535        )]));
18536        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18537        assert!(matches!(
18538            invalid.as_mut().poll(&mut task_context),
18539            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
18540                reason: "selection_key_invalid",
18541                ..
18542            })))
18543        ));
18544
18545        for invalid_key in [json!(""), json!(-1)] {
18546            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
18547            event.payload["selection_member_key"] = invalid_key.clone();
18548            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
18549            assert!(matches!(
18550                WorkflowState::new_with_identity(
18551                    vec![event],
18552                    None,
18553                    None,
18554                    "rust-workers".to_string(),
18555                    DEFAULT_CODEC.to_string(),
18556                    None,
18557                ),
18558                Err(Error::NonDeterministicReplay(_))
18559            ));
18560        }
18561    }
18562
18563    #[test]
18564    fn selection_preserves_valid_named_and_numeric_keys() {
18565        let ctx = workflow_context(Vec::new());
18566        let mut selection = Box::pin(ctx.select_keyed(vec![
18567            (
18568                SelectionKey::Index(0),
18569                ParallelOperation::activity("numeric", json!([])),
18570            ),
18571            (
18572                SelectionKey::Name("named".to_string()),
18573                ParallelOperation::timer(Duration::from_secs(1)),
18574            ),
18575        ]));
18576        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18577
18578        assert!(matches!(
18579            selection.as_mut().poll(&mut task_context),
18580            Poll::Pending
18581        ));
18582        let commands = ctx.take_commands().expect("selection commands");
18583        assert_eq!(commands[0]["selection_member_key"], json!(0));
18584        assert_eq!(commands[1]["selection_member_key"], json!("named"));
18585    }
18586
18587    #[test]
18588    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
18589        let history = canonical_selection_history();
18590        assert_persisted_selection_replay(history.clone());
18591
18592        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18593            .join("tests/fixtures/durable_selection_runtime_history.json");
18594        let output =
18595            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
18596                .args([
18597                    "--exact",
18598                    "tests::selection_fresh_process_entrypoint",
18599                    "--nocapture",
18600                ])
18601                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
18602                .output()
18603                .expect("run fresh selection replay process");
18604
18605        assert!(
18606            output.status.success(),
18607            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
18608            String::from_utf8_lossy(&output.stdout),
18609            String::from_utf8_lossy(&output.stderr),
18610        );
18611    }
18612
18613    #[test]
18614    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
18615        let mut history = canonical_selection_history();
18616        history.retain(|event| event.event_type != "SelectionResolved");
18617        let ctx = workflow_context(history);
18618        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18619        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18620
18621        assert!(matches!(
18622            selection.as_mut().poll(&mut task_context),
18623            Poll::Pending
18624        ));
18625        assert!(ctx.take_commands().expect("commands").is_empty());
18626        assert!(
18627            ctx.matched_recorded_pending()
18628                .expect("selection pending state"),
18629            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
18630        );
18631    }
18632
18633    #[test]
18634    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
18635        for (terminal_event, predicate_satisfied, timeout_seconds) in [
18636            ("ConditionWaitSatisfied", true, None),
18637            ("ConditionWaitTimedOut", false, Some(0)),
18638        ] {
18639            let member = SelectionMemberMetadata {
18640                key: SelectionKey::Name("condition".to_string()),
18641                index: 0,
18642                base_sequence: 1,
18643                size: 1,
18644                kind: "condition".to_string(),
18645            };
18646            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
18647            let mut payload = json!({
18648                "sequence": 1,
18649                "condition_wait_id": "condition-1",
18650                "condition_wait_occurrence_id": "rust:condition-wait:0",
18651                "condition_key": "ready",
18652                "condition_definition_fingerprint": "sha256:ready-v1",
18653                "parallel_group_path": path,
18654            });
18655            payload
18656                .as_object_mut()
18657                .expect("condition history payload")
18658                .extend(
18659                    serde_json::to_value(&path[0])
18660                        .expect("condition selection metadata")
18661                        .as_object()
18662                        .expect("condition selection metadata object")
18663                        .clone(),
18664                );
18665            if let Some(timeout_seconds) = timeout_seconds {
18666                payload["timeout_seconds"] = json!(timeout_seconds);
18667            }
18668            let history = vec![
18669                history_event("ConditionWaitOpened", payload.clone()),
18670                history_event(terminal_event, payload),
18671            ];
18672            let ctx = workflow_context(history);
18673            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18674            if timeout_seconds.is_some() {
18675                options = options.timeout(Duration::ZERO);
18676            }
18677            let mut selection = Box::pin(ctx.select_keyed(vec![(
18678                "condition",
18679                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18680            )]));
18681            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18682
18683            assert!(matches!(
18684                selection.as_mut().poll(&mut task_context),
18685                Poll::Pending
18686            ));
18687            assert!(ctx.take_commands().expect("commands").is_empty());
18688            assert!(
18689                ctx.matched_recorded_pending()
18690                    .expect("condition selection pending state"),
18691                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18692            );
18693        }
18694    }
18695
18696    #[test]
18697    fn selection_immediate_condition_members_open_a_durable_wait() {
18698        for predicate_satisfied in [true, false] {
18699            let ctx = workflow_context(Vec::new());
18700            let mut selection = Box::pin(ctx.select_keyed(vec![(
18701                "condition",
18702                ParallelOperation::condition(
18703                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
18704                    move || Ok(predicate_satisfied),
18705                ),
18706            )]));
18707            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18708
18709            assert!(matches!(
18710                selection.as_mut().poll(&mut task_context),
18711                Poll::Pending
18712            ));
18713            let commands = ctx.take_commands().expect("condition selection command");
18714            assert_eq!(commands.len(), 1);
18715            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
18716            assert_eq!(commands[0]["timeout_seconds"], json!(0));
18717            assert_eq!(
18718                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
18719                json!("select")
18720            );
18721        }
18722    }
18723
18724    #[test]
18725    fn selection_loser_cancellation_is_explicit_and_idempotent() {
18726        let history = vec![
18727            selection_activity_event("ActivityScheduled", 0, "slow", None),
18728            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18729            selection_winner_marker(),
18730        ];
18731        let ctx = workflow_context(history.clone());
18732        let mut call = Box::pin(keyed_activity_selection(&ctx));
18733        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18734        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18735            panic!("winner must replay");
18736        };
18737        let slow = selected
18738            .handle(&SelectionKey::Name("slow".to_string()))
18739            .expect("slow handle")
18740            .clone();
18741        let mut cancel = Box::pin(slow.cancel());
18742        assert!(matches!(
18743            cancel.as_mut().poll(&mut task_context),
18744            Poll::Pending
18745        ));
18746        assert!(matches!(
18747            cancel.as_mut().poll(&mut task_context),
18748            Poll::Pending
18749        ));
18750        let commands = ctx.take_commands().expect("cancel command");
18751        assert_eq!(commands.len(), 1);
18752        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
18753        assert_eq!(commands[0]["member_key"], json!("slow"));
18754
18755        let mut cancelled_history = history;
18756        cancelled_history.push(history_event(
18757            "SelectionOperationCancelled",
18758            json!({
18759                "selection_group_id": "select-calls:1:2",
18760                "member_key": "slow",
18761                "member_index": 0,
18762                "member_base_sequence": 1,
18763                "member_size": 1,
18764                "operation_kind": "activity",
18765                "operation_identity": "activity-slow",
18766                "cancelled_at": "2026-08-27T00:00:00Z",
18767            }),
18768        ));
18769        let replayed = workflow_context(cancelled_history);
18770        let mut call = Box::pin(keyed_activity_selection(&replayed));
18771        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18772            panic!("winner must replay after cancellation");
18773        };
18774        let slow = selected
18775            .handle(&SelectionKey::Name("slow".to_string()))
18776            .expect("slow handle")
18777            .clone();
18778        let mut cancel = Box::pin(slow.cancel());
18779        assert!(matches!(
18780            cancel.as_mut().poll(&mut task_context),
18781            Poll::Ready(Ok(()))
18782        ));
18783        assert!(replayed.take_commands().expect("commands").is_empty());
18784    }
18785
18786    #[test]
18787    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
18788        let base_history = vec![
18789            selection_activity_event("ActivityScheduled", 0, "slow", None),
18790            selection_activity_event("ActivityScheduled", 1, "fast", None),
18791            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18792            selection_winner_marker(),
18793        ];
18794        for (field, corrupt) in [
18795            ("member_key", json!("fast")),
18796            ("member_index", json!(1)),
18797            ("member_base_sequence", json!(3)),
18798            ("member_size", json!(2)),
18799            ("operation_kind", json!("timer")),
18800            ("operation_identity", json!("forged")),
18801        ] {
18802            let mut cancellation = json!({
18803                "selection_group_id": "select-calls:1:2",
18804                "member_key": "slow",
18805                "member_index": 0,
18806                "member_base_sequence": 1,
18807                "member_size": 1,
18808                "operation_kind": "activity",
18809                "operation_identity": "activity-slow",
18810            });
18811            cancellation[field] = corrupt;
18812            let mut history = base_history.clone();
18813            history.push(history_event("SelectionOperationCancelled", cancellation));
18814            let ctx = workflow_context(history);
18815            let mut selection = Box::pin(keyed_activity_selection(&ctx));
18816            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18817
18818            assert!(matches!(
18819                selection.as_mut().poll(&mut task_context),
18820                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18821            ));
18822        }
18823    }
18824
18825    #[test]
18826    fn selection_child_identity_prefers_the_durable_run_id() {
18827        let ctx = workflow_context(vec![history_event(
18828            "ChildWorkflowScheduled",
18829            json!({
18830                "sequence": 1,
18831                "child_workflow_type": "child",
18832                "child_workflow_instance_id": "child-instance",
18833                "child_workflow_run_id": "child-run",
18834            }),
18835        )]);
18836        let state = ctx.state.lock().expect("workflow state");
18837
18838        assert_eq!(
18839            selection_operation_identity(&state, "child", 1, 1),
18840            "child-run"
18841        );
18842    }
18843
18844    #[test]
18845    fn selection_activity_identity_requires_canonical_execution_id() {
18846        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
18847        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
18848        let mut fast_completed =
18849            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
18850        for event in [&mut fast_open, &mut fast_completed] {
18851            event
18852                .payload
18853                .as_object_mut()
18854                .expect("activity payload")
18855                .remove("activity_execution_id");
18856            event.payload["activity_id"] = json!("forged-activity-id");
18857        }
18858        let mut marker = selection_winner_marker();
18859        marker.payload["operation_identity"] = json!("forged-activity-id");
18860        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
18861        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18862        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18863
18864        assert!(matches!(
18865            selection.as_mut().poll(&mut task_context),
18866            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18867        ));
18868    }
18869
18870    #[test]
18871    fn selection_completion_before_cancellation_remains_awaitable() {
18872        let history = vec![
18873            selection_activity_event("ActivityScheduled", 0, "slow", None),
18874            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18875            selection_winner_marker(),
18876            selection_activity_event(
18877                "ActivityCompleted",
18878                0,
18879                "slow",
18880                Some(json!("completed-first")),
18881            ),
18882        ];
18883        let ctx = workflow_context(history);
18884        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18885        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18886        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18887            panic!("winner must replay");
18888        };
18889        let slow = selected
18890            .handle(&SelectionKey::Name("slow".to_string()))
18891            .expect("slow handle")
18892            .clone();
18893        let mut cancel = Box::pin(slow.cancel());
18894        assert!(matches!(
18895            cancel.as_mut().poll(&mut task_context),
18896            Poll::Ready(Ok(()))
18897        ));
18898        let mut await_slow = Box::pin(slow.await_result());
18899        assert!(matches!(
18900            await_slow.as_mut().poll(&mut task_context),
18901            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
18902        ));
18903        let commands = ctx.take_commands().expect("commands");
18904        assert!(commands.is_empty());
18905    }
18906
18907    #[test]
18908    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
18909        let nested_member = SelectionMemberMetadata {
18910            key: SelectionKey::Name("nested".to_string()),
18911            index: 0,
18912            base_sequence: 1,
18913            size: 2,
18914            kind: "group".to_string(),
18915        };
18916        let deadline_member = SelectionMemberMetadata {
18917            key: SelectionKey::Name("deadline".to_string()),
18918            index: 1,
18919            base_sequence: 3,
18920            size: 1,
18921            kind: "timer".to_string(),
18922        };
18923        let nested_paths = [
18924            vec![
18925                selection_group_entry(1, 3, 0, "mixed", &nested_member),
18926                parallel_group_entry(1, 2, 0, "activity"),
18927            ],
18928            vec![
18929                selection_group_entry(1, 3, 1, "mixed", &nested_member),
18930                parallel_group_entry(1, 2, 1, "activity"),
18931            ],
18932        ];
18933        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
18934        let mut timer_fired = parallel_history_event(
18935            "TimerFired",
18936            3,
18937            "timer_id",
18938            "timer-3",
18939            deadline_path.clone(),
18940            None,
18941        );
18942        timer_fired.payload["delay_seconds"] = json!(0);
18943        timer_fired
18944            .raw
18945            .insert("id".to_string(), json!("timer-fired"));
18946        let mut timer_scheduled = parallel_history_event(
18947            "TimerScheduled",
18948            3,
18949            "timer_id",
18950            "timer-3",
18951            deadline_path,
18952            None,
18953        );
18954        timer_scheduled.payload["delay_seconds"] = json!(0);
18955        let history = vec![
18956            parallel_history_event(
18957                "ActivityScheduled",
18958                1,
18959                "activity_type",
18960                "nested-first",
18961                nested_paths[0].clone(),
18962                None,
18963            ),
18964            parallel_history_event(
18965                "ActivityScheduled",
18966                2,
18967                "activity_type",
18968                "nested-second",
18969                nested_paths[1].clone(),
18970                None,
18971            ),
18972            timer_scheduled,
18973            timer_fired,
18974            history_event(
18975                "SelectionResolved",
18976                json!({
18977                    "selection_group_id": "select-calls:1:3",
18978                    "selection_group_base_sequence": 1,
18979                    "selection_group_size": 3,
18980                    "member_key": "deadline",
18981                    "member_index": 1,
18982                    "member_base_sequence": 3,
18983                    "member_size": 1,
18984                    "operation_kind": "timer",
18985                    "operation_identity": "timer-3",
18986                    "outcome": "completed",
18987                    "resolution_event_id": "timer-fired",
18988                    "resolution_event_type": "TimerFired",
18989                }),
18990            ),
18991            parallel_history_event(
18992                "ActivityFailed",
18993                2,
18994                "activity_type",
18995                "nested-second",
18996                nested_paths[1].clone(),
18997                None,
18998            ),
18999        ];
19000        let ctx = workflow_context(history);
19001        let mut selection = Box::pin(ctx.select_keyed(vec![
19002            (
19003                "nested",
19004                ParallelOperation::group(vec![
19005                    ParallelOperation::activity("nested-first", json!([])),
19006                    ParallelOperation::activity("nested-second", json!([])),
19007                ]),
19008            ),
19009            ("deadline", ParallelOperation::timer(Duration::ZERO)),
19010        ]));
19011        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19012        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19013            panic!("deadline winner must replay");
19014        };
19015        let nested = selected
19016            .handle(&SelectionKey::Name("nested".to_string()))
19017            .expect("nested handle")
19018            .clone();
19019        let mut cancel = Box::pin(nested.cancel());
19020        assert!(matches!(
19021            cancel.as_mut().poll(&mut task_context),
19022            Poll::Ready(Ok(()))
19023        ));
19024        let mut await_nested = Box::pin(nested.await_result());
19025
19026        assert!(matches!(
19027            await_nested.as_mut().poll(&mut task_context),
19028            Poll::Ready(Err(Error::ActivityFailed(_)))
19029        ));
19030        assert!(ctx.take_commands().expect("commands").is_empty());
19031    }
19032
19033    #[test]
19034    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
19035        let ctx = workflow_context(Vec::new());
19036        let mut call = Box::pin(ctx.select(vec![
19037            ParallelOperation::child_workflow(
19038                "child",
19039                ChildWorkflowOptions::new("children"),
19040                json!([]),
19041            ),
19042            ParallelOperation::timer(Duration::from_secs(30)),
19043            ParallelOperation::signal("approval"),
19044            ParallelOperation::condition(
19045                ConditionWaitOptions::new("ready", "sha256:ready"),
19046                || Ok(false),
19047            ),
19048            ParallelOperation::group(vec![
19049                ParallelOperation::activity("nested-one", json!([])),
19050                ParallelOperation::activity("nested-two", json!([])),
19051            ]),
19052        ]));
19053        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19054        assert!(matches!(
19055            call.as_mut().poll(&mut task_context),
19056            Poll::Pending
19057        ));
19058        let commands = ctx.take_commands().expect("selection commands");
19059        assert_eq!(
19060            commands
19061                .iter()
19062                .map(|command| command["type"].as_str().unwrap_or_default())
19063                .collect::<Vec<_>>(),
19064            [
19065                "start_child_workflow",
19066                "start_timer",
19067                "open_signal_wait",
19068                "open_condition_wait",
19069                "schedule_activity",
19070                "schedule_activity",
19071            ]
19072        );
19073        assert!(commands.iter().all(|command| {
19074            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
19075        }));
19076        assert_eq!(
19077            commands[4]["parallel_group_path"].as_array().map(Vec::len),
19078            Some(2)
19079        );
19080        assert_eq!(
19081            commands[4]["parallel_group_path"][0]["selection_member_kind"],
19082            json!("group")
19083        );
19084        assert_eq!(
19085            commands[5]["parallel_group_path"][0]["selection_member_kind"],
19086            json!("group")
19087        );
19088
19089        let one_leaf_ctx = workflow_context(Vec::new());
19090        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
19091            ParallelOperation::activity("nested-only", json!([])),
19092        ])]));
19093        assert!(matches!(
19094            one_leaf.as_mut().poll(&mut task_context),
19095            Poll::Pending
19096        ));
19097        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
19098        assert_eq!(one_leaf_commands.len(), 1);
19099        assert_eq!(
19100            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
19101            json!("group")
19102        );
19103        assert_eq!(
19104            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
19105            json!(1)
19106        );
19107    }
19108
19109    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
19110        let mut saga = ctx.saga();
19111        let outcome = async {
19112            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19113            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19114            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
19115            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
19116            ctx.activity("trip.charge", json!([])).await?;
19117            Ok(json!({"status": "booked"}))
19118        }
19119        .await;
19120        saga.finish(outcome).await
19121    }
19122
19123    fn saga_activity(
19124        event_type: &str,
19125        sequence: u64,
19126        activity_type: &str,
19127        result: Option<Value>,
19128    ) -> HistoryEvent {
19129        let mut payload = json!({
19130            "sequence": sequence,
19131            "activity_type": activity_type,
19132            "message": format!("{activity_type} failed"),
19133            "exception_type": "PlannedFailure",
19134            "non_retryable": true,
19135        });
19136        if let Some(result) = result {
19137            payload["result"] = fixture_envelope(result);
19138        }
19139        history_event(event_type, payload)
19140    }
19141
19142    #[test]
19143    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
19144        let completed_hotel_compensation = saga_activity(
19145            "ActivityCompleted",
19146            4,
19147            "trip.cancel-hotel",
19148            Some(Value::Null),
19149        );
19150        let history = vec![
19151            saga_activity(
19152                "ActivityCompleted",
19153                1,
19154                "trip.reserve-flight",
19155                Some(json!("flight-1")),
19156            ),
19157            saga_activity(
19158                "ActivityCompleted",
19159                2,
19160                "trip.reserve-hotel",
19161                Some(json!("hotel-1")),
19162            ),
19163            saga_activity("ActivityFailed", 3, "trip.charge", None),
19164            completed_hotel_compensation.clone(),
19165            completed_hotel_compensation,
19166        ];
19167
19168        for _restart in 0..2 {
19169            let ctx = workflow_context(history.clone());
19170            let mut future = Box::pin(trip_saga(ctx.clone()));
19171            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19172            assert!(matches!(
19173                future.as_mut().poll(&mut task_context),
19174                Poll::Pending
19175            ));
19176            let commands = ctx.take_commands().expect("compensation command");
19177            assert_eq!(commands.len(), 1);
19178            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19179        }
19180    }
19181
19182    #[test]
19183    fn saga_compensation_failure_preserves_both_typed_failures() {
19184        let history = vec![
19185            saga_activity(
19186                "ActivityCompleted",
19187                1,
19188                "trip.reserve-flight",
19189                Some(json!("flight-1")),
19190            ),
19191            saga_activity(
19192                "ActivityCompleted",
19193                2,
19194                "trip.reserve-hotel",
19195                Some(json!("hotel-1")),
19196            ),
19197            saga_activity("ActivityFailed", 3, "trip.charge", None),
19198            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
19199        ];
19200        let ctx = workflow_context(history);
19201        let mut future = Box::pin(trip_saga(ctx));
19202        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19203        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
19204            future.as_mut().poll(&mut task_context)
19205        else {
19206            panic!("compensation failure must remain structured");
19207        };
19208        assert!(matches!(
19209            *failure.initiating_failure,
19210            Error::ActivityFailed(_)
19211        ));
19212        assert!(matches!(
19213            *failure.compensation_failure,
19214            Error::ActivityFailed(_)
19215        ));
19216        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
19217        assert_eq!(failure.compensation_registration_order, 2);
19218    }
19219
19220    #[test]
19221    fn saga_compensates_cooperative_cancellation() {
19222        let ctx = workflow_context(vec![saga_activity(
19223            "ActivityCompleted",
19224            1,
19225            "trip.reserve-flight",
19226            Some(json!("flight-1")),
19227        )]);
19228        ctx.state.lock().expect("state").cancel_requested = true;
19229        let run = {
19230            let ctx = ctx.clone();
19231            async move {
19232                let mut saga = ctx.saga();
19233                let outcome = async {
19234                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19235                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19236                    ctx.throw_if_cancellation_requested()?;
19237                    Ok(json!("unexpected"))
19238                }
19239                .await;
19240                saga.finish(outcome).await
19241            }
19242        };
19243        let mut future = Box::pin(run);
19244        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19245        assert!(matches!(
19246            future.as_mut().poll(&mut task_context),
19247            Poll::Pending
19248        ));
19249        let commands = ctx.take_commands().expect("cancellation compensation");
19250        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19251    }
19252
19253    fn workflow_task(
19254        workflow_type: &str,
19255        history_events: Vec<HistoryEvent>,
19256        payload_codec: &str,
19257    ) -> WorkflowTask {
19258        WorkflowTask {
19259            task_id: format!("wft-{workflow_type}"),
19260            workflow_command_id: None,
19261            workflow_id: Some(format!("wf-{workflow_type}")),
19262            run_id: Some(format!("run-{workflow_type}")),
19263            workflow_type: workflow_type.to_string(),
19264            cancel_requested: false,
19265            payload_codec: payload_codec.to_string(),
19266            arguments: Some(
19267                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
19268            ),
19269            total_history_events: Some(history_events.len() as u64),
19270            history_size_bytes: None,
19271            continue_as_new_recommended: None,
19272            history_budget_pressure: None,
19273            history_events,
19274            next_history_page_token: None,
19275            workflow_task_attempt: 1,
19276            workflow_signal_id: None,
19277            signal_name: None,
19278            signal_arguments: None,
19279            workflow_update_id: None,
19280            update_name: None,
19281            lease_owner: Some("rust-worker".to_string()),
19282        }
19283    }
19284
19285    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19286    struct SideEffectProbe {
19287        request_id: String,
19288        attempt: u32,
19289    }
19290
19291    #[test]
19292    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
19293        let calls = AtomicUsize::new(0);
19294        let ctx = workflow_context(Vec::new());
19295        let value = ctx
19296            .side_effect(|| {
19297                calls.fetch_add(1, Ordering::SeqCst);
19298                SideEffectProbe {
19299                    request_id: "request-42".to_string(),
19300                    attempt: 3,
19301                }
19302            })
19303            .expect("first side effect");
19304        assert_eq!(value.attempt, 3);
19305        assert_eq!(calls.load(Ordering::SeqCst), 1);
19306        let commands = ctx.take_commands().expect("commands");
19307        assert_eq!(commands.len(), 1);
19308        assert_eq!(commands[0]["type"], "record_side_effect");
19309        assert_eq!(
19310            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19311            serde_json::to_value(&value).expect("value")
19312        );
19313
19314        let replay = workflow_context(vec![history_event(
19315            "SideEffectRecorded",
19316            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19317        )]);
19318        let replayed: SideEffectProbe = replay
19319            .side_effect(|| {
19320                calls.fetch_add(1, Ordering::SeqCst);
19321                panic!("committed side-effect callbacks must not run during replay")
19322            })
19323            .expect("replayed side effect");
19324        assert_eq!(replayed, value);
19325        assert_eq!(calls.load(Ordering::SeqCst), 1);
19326        assert!(replay.take_commands().expect("commands").is_empty());
19327        replay.ensure_history_consumed().expect("history consumed");
19328    }
19329
19330    #[test]
19331    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
19332        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19333        let value = ctx
19334            .side_effect(|| SideEffectProbe {
19335                request_id: "avro-request".to_string(),
19336                attempt: 1,
19337            })
19338            .expect("Avro side effect");
19339        let uuid = ctx.uuid_v4().expect("deterministic UUID");
19340        let commands = ctx.take_commands().expect("commands");
19341        assert_eq!(commands.len(), 2);
19342        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
19343        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
19344        assert_eq!(
19345            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19346            serde_json::to_value(&value).expect("value")
19347        );
19348
19349        let replay = workflow_context_with_codec(
19350            vec![
19351                history_event(
19352                    "SideEffectRecorded",
19353                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19354                ),
19355                history_event(
19356                    "SideEffectRecorded",
19357                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
19358                ),
19359            ],
19360            DEFAULT_CODEC,
19361        );
19362        let replayed: SideEffectProbe = replay
19363            .side_effect(|| panic!("Avro callback must not run"))
19364            .expect("replayed Avro value");
19365        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
19366        assert_eq!(replayed, value);
19367        assert_eq!(replayed_uuid, uuid);
19368        assert!(replay.take_commands().expect("commands").is_empty());
19369    }
19370
19371    #[test]
19372    fn typed_side_effect_replay_preserves_bytes_and_maps() {
19373        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19374        let value = ctx
19375            .side_effect_avro_value(typed_fidelity_probe)
19376            .expect("typed side effect");
19377        let commands = ctx.take_commands().expect("side-effect command");
19378        assert_eq!(
19379            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19380                .expect("recorded side effect"),
19381            value
19382        );
19383
19384        let replay = workflow_context_with_codec(
19385            vec![history_event(
19386                "SideEffectRecorded",
19387                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19388            )],
19389            DEFAULT_CODEC,
19390        );
19391        assert_eq!(
19392            replay
19393                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
19394                .expect("replayed typed side effect"),
19395            value
19396        );
19397    }
19398
19399    #[test]
19400    fn ordered_side_effects_share_the_durable_command_stream() {
19401        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
19402        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
19403        let ctx = workflow_context(vec![
19404            history_event(
19405                "SideEffectRecorded",
19406                json!({"sequence": 1, "result": first}),
19407            ),
19408            history_event(
19409                "SideEffectRecorded",
19410                json!({"sequence": 2, "result": second}),
19411            ),
19412        ]);
19413        let first: String = ctx
19414            .side_effect(|| panic!("first callback must not run"))
19415            .expect("first replay");
19416        let second: i32 = ctx
19417            .side_effect(|| panic!("second callback must not run"))
19418            .expect("second replay");
19419        assert_eq!(first, "first");
19420        assert_eq!(second, 29);
19421        ctx.ensure_history_consumed().expect("ordered history");
19422
19423        let reordered = workflow_context(vec![history_event(
19424            "VersionMarkerRecorded",
19425            json!({
19426                "sequence": 1,
19427                "change_id": "before-side-effect",
19428                "version": 1,
19429                "min_supported": 1,
19430                "max_supported": 1,
19431            }),
19432        )]);
19433        let error = reordered
19434            .side_effect(|| "new".to_string())
19435            .expect_err("command reordering must fail");
19436        assert!(matches!(
19437            error,
19438            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19439                if reason == "recorded_command_mismatch"
19440        ));
19441    }
19442
19443    #[test]
19444    fn legacy_patch_preserves_pending_and_completed_activity_history() {
19445        for completed in [false, true] {
19446            let mut history = vec![history_event(
19447                "ActivityScheduled",
19448                json!({"sequence": 1, "activity_type": "old"}),
19449            )];
19450            if completed {
19451                history.push(history_event(
19452                    "ActivityCompleted",
19453                    json!({
19454                        "sequence": 1,
19455                        "activity_type": "old",
19456                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
19457                    }),
19458                ));
19459            }
19460            for _cold_replay in 0..2 {
19461                let ctx = workflow_context(history.clone());
19462                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
19463                assert!(!ctx.patched("added-step").expect("same frozen decision"));
19464                ctx.deprecate_patch("added-step")
19465                    .expect("retained boundary");
19466                let mut activity = Box::pin(ctx.activity("old", json!([])));
19467                let mut context = TaskContext::from_waker(noop_waker_ref());
19468                match activity.as_mut().poll(&mut context) {
19469                    Poll::Ready(result) => {
19470                        assert!(completed);
19471                        assert_eq!(result.expect("recorded result"), json!(41));
19472                        ctx.ensure_history_consumed().expect("old command retained");
19473                    }
19474                    Poll::Pending => assert!(!completed),
19475                }
19476                assert!(ctx.take_commands().expect("commands").is_empty());
19477            }
19478        }
19479    }
19480
19481    #[test]
19482    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
19483        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
19484        assert!(!ctx.patched("added-step").expect("legacy completed run"));
19485        ctx.deprecate_patch("added-step")
19486            .expect("same legacy decision");
19487        assert!(ctx.take_commands().expect("commands").is_empty());
19488        ctx.ensure_history_consumed().expect("completed history");
19489    }
19490
19491    #[test]
19492    fn legacy_patch_rejects_a_range_without_the_original_branch() {
19493        let ctx = workflow_context(vec![history_event(
19494            "ActivityScheduled",
19495            json!({"sequence": 1, "activity_type": "old"}),
19496        )]);
19497        let error = ctx
19498            .get_version("added-step", 0, 1)
19499            .expect_err("legacy is unsupported");
19500        assert!(matches!(
19501            error,
19502            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19503                if reason == "version_marker_incompatible_range"
19504        ));
19505        assert!(!ctx
19506            .patched("supported-step")
19507            .expect("failed check did not consume history"));
19508        assert!(ctx.take_commands().expect("commands").is_empty());
19509    }
19510
19511    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
19512        let mut event = history_event(
19513            "VersionMarkerRecorded",
19514            json!({
19515                "sequence": sequence,
19516                "change_id": "retained-patch",
19517                "version": version,
19518                "min_supported": -1,
19519                "max_supported": 1,
19520            }),
19521        );
19522        event.raw.insert("timestamp".into(), json!(time));
19523        event
19524    }
19525
19526    #[test]
19527    fn retained_patch_markers_preserve_each_original_boundary() {
19528        for completed in [false, true] {
19529            let mut history = vec![
19530                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19531                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19532                history_event(
19533                    "ActivityScheduled",
19534                    json!({"sequence": 3, "activity_type": "old"}),
19535                ),
19536            ];
19537            if completed {
19538                history.push(history_event(
19539                    "ActivityCompleted",
19540                    json!({
19541                        "sequence": 3,
19542                        "activity_type": "old",
19543                        "result": fixture_envelope(json!(41)),
19544                    }),
19545                ));
19546            }
19547            for _cold_replay in 0..2 {
19548                let ctx = workflow_context(history.clone());
19549                assert!(ctx.patched("retained-patch").unwrap());
19550                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19551                assert!(ctx.patched("retained-patch").unwrap());
19552                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19553                ctx.deprecate_patch("retained-patch").unwrap();
19554                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19555                let mut activity = Box::pin(ctx.activity("old", json!([])));
19556                let mut context = TaskContext::from_waker(noop_waker_ref());
19557                match activity.as_mut().poll(&mut context) {
19558                    Poll::Ready(result) => {
19559                        assert!(completed);
19560                        assert_eq!(result.unwrap(), json!(41));
19561                        ctx.ensure_history_consumed().unwrap();
19562                    }
19563                    Poll::Pending => assert!(!completed),
19564                }
19565                assert!(ctx.take_commands().unwrap().is_empty());
19566                let state = ctx.state.lock().unwrap();
19567                for (actual, original) in state.history_events.iter().zip(&history) {
19568                    assert_eq!(actual.payload, original.payload);
19569                    assert_eq!(actual.raw, original.raw);
19570                }
19571            }
19572        }
19573    }
19574
19575    #[test]
19576    fn retained_patch_aliases_do_not_skip_intervening_operations() {
19577        let ctx = workflow_context(vec![
19578            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19579            history_event(
19580                "SideEffectRecorded",
19581                json!({
19582                    "sequence": 2, "result": fixture_envelope(json!("between")),
19583                }),
19584            ),
19585            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
19586            history_event(
19587                "VersionMarkerRecorded",
19588                json!({
19589                    "sequence": 4, "change_id": "other-patch", "version": 1,
19590                    "min_supported": -1, "max_supported": 1,
19591                }),
19592            ),
19593        ]);
19594        assert!(ctx.patched("retained-patch").unwrap());
19595        assert!(ctx.patched("retained-patch").unwrap());
19596        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19597        assert_eq!(
19598            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19599            "between"
19600        );
19601        ctx.deprecate_patch("retained-patch").unwrap();
19602        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19603        ctx.deprecate_patch("retained-patch").unwrap();
19604        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19605        assert!(ctx.patched("other-patch").unwrap());
19606        ctx.ensure_history_consumed().unwrap();
19607        assert!(ctx.take_commands().unwrap().is_empty());
19608    }
19609
19610    #[test]
19611    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
19612        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19613        alias.payload["max_supported"] = json!(3);
19614        let ctx = workflow_context(vec![
19615            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19616            alias,
19617        ]);
19618        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
19619        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
19620        assert!(matches!(error,
19621            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19622                if reason == "version_marker_incompatible_range"));
19623        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19624        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
19625        ctx.ensure_history_consumed().unwrap();
19626        assert!(ctx.take_commands().unwrap().is_empty());
19627    }
19628
19629    #[test]
19630    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
19631        let ctx = workflow_context(Vec::new());
19632        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
19633        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
19634        assert!(ctx.patched("new-search").expect("patch"));
19635        ctx.deprecate_patch("new-search").expect("deprecate patch");
19636        let commands = ctx.take_commands().expect("commands");
19637        assert_eq!(commands.len(), 2);
19638        assert_eq!(commands[0]["type"], "record_version_marker");
19639        assert_eq!(commands[0]["version"], 2);
19640        assert_eq!(commands[1]["change_id"], "new-search");
19641
19642        let replay = workflow_context(vec![history_event(
19643            "VersionMarkerRecorded",
19644            json!({
19645                "sequence": 1,
19646                "change_id": "checkout-v2",
19647                "version": 2,
19648                "min_supported": 1,
19649                "max_supported": 2,
19650            }),
19651        )]);
19652        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
19653        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
19654        assert!(replay.take_commands().expect("commands").is_empty());
19655        replay.ensure_history_consumed().expect("history consumed");
19656    }
19657
19658    #[test]
19659    fn version_markers_reject_incompatible_or_malformed_history() {
19660        let incompatible = workflow_context(vec![history_event(
19661            "VersionMarkerRecorded",
19662            json!({
19663                "sequence": 1,
19664                "change_id": "checkout-v2",
19665                "version": 1,
19666                "min_supported": 1,
19667                "max_supported": 2,
19668            }),
19669        )]);
19670        let error = incompatible
19671            .get_version("checkout-v2", 2, 3)
19672            .expect_err("old version is unsupported");
19673        assert!(matches!(
19674            error,
19675            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19676                if reason == "version_marker_incompatible_range"
19677        ));
19678
19679        for (history, reason) in [
19680            (
19681                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
19682                "side_effect_result_missing",
19683            ),
19684            (
19685                vec![history_event(
19686                    "SideEffectRecorded",
19687                    json!({
19688                        "sequence": 1,
19689                        "result": {"codec": "avro", "blob": "not-base64"},
19690                    }),
19691                )],
19692                "side_effect_payload_incompatible",
19693            ),
19694            (
19695                vec![history_event(
19696                    "SideEffectRecorded",
19697                    json!({"sequence": 1, "result": {"unwrapped": true}}),
19698                )],
19699                "side_effect_payload_malformed",
19700            ),
19701            (
19702                vec![history_event(
19703                    "VersionMarkerRecorded",
19704                    json!({
19705                        "sequence": 1,
19706                        "change_id": "change",
19707                        "version": 1,
19708                        "min_supported": 2,
19709                        "max_supported": 1,
19710                    }),
19711                )],
19712                "version_marker_history_range_invalid",
19713            ),
19714        ] {
19715            let error = WorkflowState::new(
19716                history,
19717                "rust-workers".to_string(),
19718                DEFAULT_CODEC.to_string(),
19719                None,
19720            )
19721            .expect_err("malformed history must fail");
19722            assert!(matches!(
19723                error,
19724                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
19725                    if actual == reason
19726            ));
19727        }
19728    }
19729
19730    #[test]
19731    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
19732        let history = vec![history_event(
19733            "SearchAttributesUpserted",
19734            json!({
19735                "sequence": 1,
19736                "attributes": {"customer_tier": "gold"},
19737                "attribute_types": {"customer_tier": "keyword"},
19738                "merged": {"customer_tier": "gold"}
19739            }),
19740        )];
19741
19742        let matching = workflow_context(history.clone());
19743        matching
19744            .upsert_search_attributes(
19745                SearchAttributeUpdate::new()
19746                    .keyword("customer_tier", "gold")
19747                    .expect("keyword update"),
19748            )
19749            .expect("matching typed update must replay");
19750        matching
19751            .ensure_history_consumed()
19752            .expect("history consumed");
19753
19754        let changed_type = workflow_context(history.clone());
19755        let error = changed_type
19756            .upsert_search_attributes(
19757                SearchAttributeUpdate::new()
19758                    .string("customer_tier", "gold")
19759                    .expect("string update"),
19760            )
19761            .expect_err("same JSON value with a different declaration must be nondeterministic");
19762        let Error::NonDeterministicReplay(failure) = error else {
19763            panic!("typed identity drift must be a replay failure");
19764        };
19765        assert_eq!(failure.reason, "search_attribute_type_mismatch");
19766        assert_eq!(failure.sequence, Some(1));
19767
19768        let changed_value = workflow_context(history);
19769        let error = changed_value
19770            .upsert_search_attributes(
19771                SearchAttributeUpdate::new()
19772                    .keyword("customer_tier", "platinum")
19773                    .expect("keyword update"),
19774            )
19775            .expect_err("changed values must be nondeterministic");
19776        let Error::NonDeterministicReplay(failure) = error else {
19777            panic!("value drift must be a replay failure");
19778        };
19779        assert_eq!(failure.reason, "search_attribute_value_mismatch");
19780    }
19781
19782    #[test]
19783    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
19784        let history = vec![history_event(
19785            "SearchAttributesUpserted",
19786            json!({
19787                "sequence": 1,
19788                "attributes": {"customer_tier": "gold"},
19789                "merged": {"customer_tier": "gold"}
19790            }),
19791        )];
19792
19793        for update in [
19794            SearchAttributeUpdate::new()
19795                .keyword("customer_tier", "gold")
19796                .expect("keyword update"),
19797            SearchAttributeUpdate::new()
19798                .string("customer_tier", "gold")
19799                .expect("string update"),
19800        ] {
19801            let restarted = workflow_context(history.clone());
19802            restarted
19803                .upsert_search_attributes(update)
19804                .expect("legacy history constrains values but has unknown type identity");
19805            restarted
19806                .ensure_history_consumed()
19807                .expect("history consumed");
19808        }
19809    }
19810
19811    #[test]
19812    fn search_attribute_command_emits_canonical_types() {
19813        let ctx = workflow_context(Vec::new());
19814        ctx.upsert_search_attributes(
19815            SearchAttributeUpdate::new()
19816                .keyword("customer_tier", "gold")
19817                .expect("keyword update")
19818                .int("attempts", 3)
19819                .expect("int update")
19820                .delete("obsolete")
19821                .expect("delete update"),
19822        )
19823        .expect("valid search attributes");
19824
19825        assert_eq!(
19826            ctx.take_commands().expect("commands"),
19827            vec![json!({
19828                "type": "upsert_search_attributes",
19829                "attributes": {
19830                    "attempts": 3,
19831                    "customer_tier": "gold",
19832                    "obsolete": null
19833                },
19834                "attribute_types": {
19835                    "attempts": "int",
19836                    "customer_tier": "keyword"
19837                }
19838            })]
19839        );
19840    }
19841
19842    #[test]
19843    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
19844        let duplicate_side_effect = WorkflowState::new(
19845            vec![
19846                history_event(
19847                    "SideEffectRecorded",
19848                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
19849                ),
19850                history_event(
19851                    "SideEffectRecorded",
19852                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
19853                ),
19854            ],
19855            "rust-workers".to_string(),
19856            DEFAULT_CODEC.to_string(),
19857            None,
19858        )
19859        .expect_err("duplicate side effect");
19860        assert!(matches!(
19861            duplicate_side_effect,
19862            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19863                if reason == "duplicate_side_effect_record"
19864        ));
19865
19866        let marker = |sequence, version| {
19867            history_event(
19868                "VersionMarkerRecorded",
19869                json!({
19870                    "sequence": sequence,
19871                    "change_id": "same-change",
19872                    "version": version,
19873                    "min_supported": -1,
19874                    "max_supported": 1,
19875                }),
19876            )
19877        };
19878        let duplicate_marker = WorkflowState::new(
19879            vec![marker(1, 1), marker(3, -1)],
19880            "rust-workers".to_string(),
19881            DEFAULT_CODEC.to_string(),
19882            None,
19883        )
19884        .expect_err("conflicting marker");
19885        assert!(matches!(
19886            duplicate_marker,
19887            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19888                if reason == "version_marker_conflict"
19889        ));
19890    }
19891
19892    #[test]
19893    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
19894        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
19895        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19896        invalid_alias.payload["max_supported"] = json!(0);
19897        for (history, expected_reason) in [
19898            (
19899                vec![marker.clone(), marker.clone()],
19900                "duplicate_version_marker_record",
19901            ),
19902            (
19903                vec![marker, invalid_alias],
19904                "version_marker_history_range_invalid",
19905            ),
19906        ] {
19907            let error =
19908                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
19909                    .expect_err("invalid historical alias");
19910            assert!(matches!(error,
19911                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
19912                    if reason == expected_reason));
19913        }
19914    }
19915
19916    #[test]
19917    fn retained_patch_aliases_require_the_original_call_boundary() {
19918        let ctx = workflow_context(vec![
19919            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19920            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19921        ]);
19922        assert!(ctx.patched("retained-patch").unwrap());
19923        assert!(ctx.ensure_history_consumed().is_err());
19924        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19925        ctx.deprecate_patch("retained-patch").unwrap();
19926        ctx.ensure_history_consumed().unwrap();
19927        assert!(ctx.take_commands().unwrap().is_empty());
19928    }
19929
19930    #[test]
19931    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
19932        let ctx = workflow_context(vec![
19933            history_event(
19934                "SideEffectRecorded",
19935                json!({
19936                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
19937                }),
19938            ),
19939            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19940        ]);
19941        assert!(!ctx.patched("retained-patch").unwrap());
19942        assert_eq!(
19943            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19944            "old-operation"
19945        );
19946        let error = ctx.patched("retained-patch").unwrap_err();
19947        assert!(matches!(error,
19948            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19949                if reason == "version_marker_conflict"));
19950        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19951        assert!(ctx.take_commands().unwrap().is_empty());
19952    }
19953
19954    #[test]
19955    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
19956        let mut state = WorkflowState::new(
19957            Vec::new(),
19958            "rust-workers".to_string(),
19959            DEFAULT_CODEC.to_string(),
19960            None,
19961        )
19962        .expect("workflow state");
19963        state.workflow_command_identity = "command-7".to_string();
19964        let context = WorkflowContext {
19965            state: Arc::new(Mutex::new(state)),
19966            cancellation_scope_id: "root".into(),
19967        };
19968        let item =
19969            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
19970
19971        context
19972            .append_workflow_stream("output", &[item], Some(10))
19973            .expect("append command");
19974        context
19975            .error_workflow_stream("output", "producer failed", None)
19976            .expect("error command");
19977        let commands = context.take_commands().expect("commands");
19978
19979        assert_eq!(commands[0]["type"], "record_side_effect");
19980        assert_eq!(
19981            commands[0]["workflow_stream"]["command_identity"],
19982            "command-7"
19983        );
19984        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
19985        assert_eq!(
19986            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
19987            "dw-stream:command-7:0:0"
19988        );
19989        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
19990
19991        let recorded = history_event(
19992            "SideEffectRecorded",
19993            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
19994        );
19995        let mut replay_state = WorkflowState::new(
19996            vec![recorded],
19997            "rust-workers".to_string(),
19998            DEFAULT_CODEC.to_string(),
19999            None,
20000        )
20001        .expect("replay state");
20002        replay_state.workflow_command_identity = "command-7".to_string();
20003        let replay_context = WorkflowContext {
20004            state: Arc::new(Mutex::new(replay_state)),
20005            cancellation_scope_id: "root".into(),
20006        };
20007        replay_context
20008            .append_workflow_stream(
20009                "output",
20010                &[WorkflowStreamAppendItem::from_reference(
20011                    "s3://bucket/item.avro",
20012                )],
20013                Some(10),
20014            )
20015            .expect("replayed append");
20016        assert!(replay_context
20017            .take_commands()
20018            .expect("replayed commands")
20019            .is_empty());
20020    }
20021
20022    #[test]
20023    fn workflow_stream_authoring_requires_server_durable_command_identity() {
20024        let context = workflow_context(Vec::new());
20025        let error = context
20026            .append_workflow_stream(
20027                "output",
20028                &[WorkflowStreamAppendItem::from_reference(
20029                    "s3://bucket/item.avro",
20030                )],
20031                None,
20032            )
20033            .expect_err("stream append without durable command identity must fail closed");
20034
20035        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
20036        assert!(context.take_commands().expect("commands").is_empty());
20037    }
20038
20039    #[test]
20040    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
20041        let client = Client::builder("http://localhost:8080").build().unwrap();
20042        let mut worker = Worker::new(client, "rust-workers");
20043        worker.register_workflow("streams.worker", |ctx, _| async move {
20044            ctx.append_workflow_stream(
20045                "output",
20046                &[WorkflowStreamAppendItem::new(json!("hello"))?],
20047                None,
20048            )?;
20049            ctx.close_workflow_stream("output", None)?;
20050            Ok(json!("done"))
20051        });
20052        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
20053            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20054            task.workflow_command_id = command_id.clone();
20055            let expected_identity = command_id
20056                .as_deref()
20057                .filter(|id| !id.is_empty())
20058                .unwrap_or(&task.task_id)
20059                .to_string();
20060            let commands = worker
20061                .execute_workflow_task(task)
20062                .expect("ordinary worker stream output");
20063            assert_eq!(commands.len(), 3);
20064            assert_eq!(
20065                commands[0]["workflow_stream"]["command_identity"],
20066                expected_identity
20067            );
20068            assert_eq!(
20069                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20070                format!("dw-stream:{expected_identity}:0:0")
20071            );
20072            assert_eq!(
20073                commands[1]["workflow_stream"]["command_identity"],
20074                expected_identity
20075            );
20076            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
20077            let history = commands[..2]
20078                .iter()
20079                .enumerate()
20080                .map(|(index, command)| {
20081                    history_event(
20082                        "SideEffectRecorded",
20083                        json!({"sequence":index + 1,"result":command["result"]}),
20084                    )
20085                })
20086                .collect();
20087            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
20088            replay.task_id = "replacement-task".to_string();
20089            let replayed = worker
20090                .execute_workflow_task(replay)
20091                .expect("replacement worker consumes recorded stream effects");
20092            assert_eq!(replayed.len(), 1);
20093            assert_eq!(replayed[0]["type"], "complete_workflow");
20094        }
20095        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20096        missing.task_id.clear();
20097        assert!(matches!(
20098            worker.execute_workflow_task(missing),
20099            Err(Error::MissingWorkflowCommandIdentity)
20100        ));
20101    }
20102
20103    #[test]
20104    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
20105        fn worker(calls: Arc<AtomicUsize>) -> Worker {
20106            let client = Client::new("http://127.0.0.1:8080").expect("client");
20107            let mut worker = Worker::new(client, "rust-workers");
20108            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
20109                let calls = Arc::clone(&calls);
20110                async move {
20111                    let captured = ctx.side_effect(|| {
20112                        calls.fetch_add(1, Ordering::SeqCst);
20113                        "captured-once".to_string()
20114                    })?;
20115                    let version = ctx.get_version("cold-restart", 1, 2)?;
20116                    Ok(json!({"captured": captured, "version": version}))
20117                }
20118            });
20119            worker
20120        }
20121
20122        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
20123            WorkflowTask {
20124                task_id: "wft-side-effect-version".to_string(),
20125                workflow_command_id: None,
20126                workflow_id: Some("wf-side-effect-version".to_string()),
20127                run_id: Some("run-side-effect-version".to_string()),
20128                workflow_type: "rust.side-effect-version".to_string(),
20129                cancel_requested: false,
20130                payload_codec: DEFAULT_CODEC.to_string(),
20131                arguments: Some(
20132                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
20133                ),
20134                history_events,
20135                total_history_events: None,
20136                history_size_bytes: None,
20137                continue_as_new_recommended: None,
20138                history_budget_pressure: None,
20139                next_history_page_token: None,
20140                workflow_task_attempt: 1,
20141                workflow_signal_id: None,
20142                signal_name: None,
20143                signal_arguments: None,
20144                workflow_update_id: None,
20145                update_name: None,
20146                lease_owner: Some("rust-worker".to_string()),
20147            }
20148        }
20149
20150        let calls = Arc::new(AtomicUsize::new(0));
20151        let initial = worker(Arc::clone(&calls))
20152            .execute_workflow_task(task(Vec::new()))
20153            .expect("initial execution");
20154        assert_eq!(
20155            initial
20156                .iter()
20157                .map(|command| &command["type"])
20158                .collect::<Vec<_>>(),
20159            vec![
20160                "record_side_effect",
20161                "record_version_marker",
20162                "complete_workflow"
20163            ]
20164        );
20165        assert_eq!(calls.load(Ordering::SeqCst), 1);
20166
20167        let restarted = worker(Arc::clone(&calls));
20168        let replayed = restarted
20169            .execute_workflow_task(task(vec![
20170                history_event(
20171                    "SideEffectRecorded",
20172                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
20173                ),
20174                history_event(
20175                    "VersionMarkerRecorded",
20176                    json!({
20177                        "sequence": 2,
20178                        "change_id": "cold-restart",
20179                        "version": 2,
20180                        "min_supported": 1,
20181                        "max_supported": 2,
20182                    }),
20183                ),
20184            ]))
20185            .expect("cold replay");
20186        assert_eq!(replayed.len(), 1);
20187        assert_eq!(replayed[0]["type"], "complete_workflow");
20188        assert_eq!(calls.load(Ordering::SeqCst), 1);
20189    }
20190
20191    #[test]
20192    fn side_effect_replay_rejects_changed_rust_value_type() {
20193        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
20194        let ctx = workflow_context(vec![history_event(
20195            "SideEffectRecorded",
20196            json!({"sequence": 1, "result": result}),
20197        )]);
20198        let error = ctx
20199            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
20200            .expect_err("changed type must fail replay");
20201        assert!(matches!(
20202            error,
20203            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20204                if reason == "side_effect_type_mismatch"
20205        ));
20206    }
20207
20208    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
20209        vec![
20210            history_event(
20211                "ActivityScheduled",
20212                json!({
20213                    "sequence": 1,
20214                    "activity_type": "flaky",
20215                    "activity_execution_id": "act-1",
20216                    "activity": {
20217                        "id": "act-1",
20218                        "sequence": 1,
20219                        "type": "flaky",
20220                        "queue": "critical-activities",
20221                        "execution_mode": null,
20222                        "retry_policy": {
20223                            "snapshot_version": 1,
20224                            "max_attempts": 3,
20225                            "backoff_seconds": [2, 4],
20226                            "start_to_close_timeout": 30,
20227                            "schedule_to_start_timeout": 5,
20228                            "schedule_to_close_timeout": 90,
20229                            "heartbeat_timeout": 10,
20230                            "non_retryable_error_types": ["PermanentError"]
20231                        }
20232                    }
20233                }),
20234            ),
20235            history_event(
20236                "ActivityStarted",
20237                json!({
20238                    "sequence": 1,
20239                    "activity_type": "flaky",
20240                    "activity_execution_id": "act-1",
20241                    "activity_attempt_id": "attempt-1",
20242                    "attempt_number": 1
20243                }),
20244            ),
20245            history_event(
20246                "ActivityRetryScheduled",
20247                json!({
20248                    "sequence": 1,
20249                    "activity_type": "flaky",
20250                    "activity_execution_id": "act-1",
20251                    "activity_attempt_id": "attempt-1",
20252                    "attempt_number": 1,
20253                    "retry_after_attempt": 1,
20254                    "retry_backoff_seconds": 2,
20255                    "failure_category": "activity",
20256                    "exception_type": "TransientError"
20257                }),
20258            ),
20259            history_event(
20260                "ActivityStarted",
20261                json!({
20262                    "sequence": 1,
20263                    "activity_type": "flaky",
20264                    "activity_execution_id": "act-1",
20265                    "activity_attempt_id": "attempt-2",
20266                    "attempt_number": 2
20267                }),
20268            ),
20269            history_event(
20270                "ActivityCompleted",
20271                json!({
20272                    "sequence": 1,
20273                    "activity_type": "flaky",
20274                    "activity_execution_id": "act-1",
20275                    "activity_attempt_id": "attempt-2",
20276                    "attempt_number": 2,
20277                    "payload_codec": DEFAULT_CODEC,
20278                    "result": fixture_envelope(json!({"status":"recovered"}))
20279                }),
20280            ),
20281        ]
20282    }
20283
20284    fn retry_activity_options() -> ActivityOptions {
20285        ActivityOptions::new()
20286            .task_queue("critical-activities")
20287            .retry_policy(
20288                ActivityRetryPolicy::new(3)
20289                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
20290                    .non_retryable_error_type("PermanentError"),
20291            )
20292            .start_to_close_timeout(Duration::from_secs(30))
20293            .schedule_to_start_timeout(Duration::from_secs(5))
20294            .schedule_to_close_timeout(Duration::from_secs(90))
20295            .heartbeat_timeout(Duration::from_secs(10))
20296    }
20297
20298    #[test]
20299    fn fixed_avro_value_round_trips_json_values() {
20300        let value = json!({"greeting": "hello", "count": 3, "ok": true});
20301        let envelope = PayloadEnvelope::avro(&value).expect("encode");
20302        assert_eq!(envelope.codec, DEFAULT_CODEC);
20303        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
20304    }
20305
20306    #[tokio::test]
20307    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
20308        let client = Client::new("http://127.0.0.1:8080").expect("client");
20309        let mut worker = Worker::new(client, "rust-workers");
20310        worker.register_typed_workflow(
20311            "typed.contract.workflow",
20312            |_ctx, input: TypedContract| async move { Ok(input) },
20313        );
20314        worker.register_typed_activity(
20315            "typed.contract.activity",
20316            |_ctx, input: TypedContract| async move { Ok(input) },
20317        );
20318
20319        let expected = typed_contract();
20320        let arguments = AvroValue::Array(vec![
20321            AvroValue::from_serialize(&expected).expect("typed request")
20322        ]);
20323        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
20324        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
20325        workflow.arguments = Some(envelope.clone());
20326        let commands = worker
20327            .execute_workflow_task(workflow)
20328            .expect("typed workflow task");
20329        let workflow_result: TypedContract =
20330            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20331                .expect("workflow result envelope")
20332                .deserialize()
20333                .expect("workflow result type");
20334        assert_eq!(workflow_result, expected);
20335
20336        let activity = ActivityTask {
20337            task_id: "typed-contract-activity".to_string(),
20338            activity_attempt_id: Some("typed-contract-attempt".to_string()),
20339            attempt_id: None,
20340            activity_type: "typed.contract.activity".to_string(),
20341            payload_codec: DEFAULT_CODEC.to_string(),
20342            arguments: Some(envelope),
20343            attempt_number: 1,
20344            lease_owner: Some("rust-worker".to_string()),
20345        };
20346        let activity_result: TypedContract = worker
20347            .execute_activity_task(activity)
20348            .await
20349            .expect("typed activity task")
20350            .deserialize()
20351            .expect("activity result type");
20352        assert_eq!(activity_result, expected);
20353    }
20354
20355    #[tokio::test]
20356    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
20357        let client = Client::new("http://127.0.0.1:8080").expect("client");
20358        let mut worker = Worker::new(client, "rust-workers");
20359        worker.register_typed_workflow(
20360            "typed.shape.workflow",
20361            |_ctx, input: TypedContract| async move { Ok(input) },
20362        );
20363        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
20364            Ok(f64::NAN)
20365        });
20366
20367        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
20368        workflow.arguments = Some(
20369            encode_typed_envelope(
20370                &AvroValue::Array(vec![
20371                    AvroValue::String("first".to_string()),
20372                    AvroValue::String("second".to_string()),
20373                ]),
20374                DEFAULT_CODEC,
20375            )
20376            .expect("malformed typed arguments"),
20377        );
20378        let commands = worker
20379            .execute_workflow_task(workflow)
20380            .expect("shape mismatch becomes a workflow failure");
20381        let message = commands[0]["message"].as_str().expect("failure message");
20382        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
20383        assert!(message.contains(type_name::<TypedContract>()));
20384        assert!(message.contains("task carried 2 arguments"));
20385
20386        let activity = ActivityTask {
20387            task_id: "typed-unsupported-activity".to_string(),
20388            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
20389            attempt_id: None,
20390            activity_type: "typed.unsupported.activity".to_string(),
20391            payload_codec: DEFAULT_CODEC.to_string(),
20392            arguments: Some(
20393                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20394                    .expect("unit arguments"),
20395            ),
20396            attempt_number: 1,
20397            lease_owner: Some("rust-worker".to_string()),
20398        };
20399        let Error::HandlerType {
20400            handler_kind,
20401            handler_name,
20402            value_kind,
20403            rust_type,
20404            message,
20405        } = worker
20406            .execute_activity_task(activity)
20407            .await
20408            .expect_err("non-finite handler output must fail")
20409        else {
20410            panic!("expected contextual handler type failure");
20411        };
20412        assert_eq!(handler_kind, HandlerKind::Activity);
20413        assert_eq!(handler_name, "typed.unsupported.activity");
20414        assert_eq!(value_kind, HandlerValueKind::Result);
20415        assert_eq!(rust_type, type_name::<f64>());
20416        assert!(message.contains("non_finite_float"));
20417    }
20418
20419    #[tokio::test]
20420    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
20421        #[derive(Clone, Default)]
20422        struct State {
20423            observed: Option<TypedContract>,
20424        }
20425
20426        let client = Client::new("http://127.0.0.1:8080").expect("client");
20427        let mut worker = Worker::new(client, "rust-workers");
20428        worker.register_typed_replayed_workflow(
20429            "typed.contract.replayed",
20430            State::default,
20431            |ctx, input: TypedContract, state| async move {
20432                let result: TypedContract =
20433                    ctx.activity_typed("typed.contract.activity", input).await?;
20434                state.update(|current| current.observed = Some(result.clone()))?;
20435                Ok(result)
20436            },
20437        );
20438        worker.register_replayed_query::<State, _, _>(
20439            "typed.contract.replayed",
20440            "observed",
20441            |_ctx, state, _args| async move {
20442                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
20443            },
20444        );
20445
20446        let expected = typed_contract();
20447        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
20448        let workflow_arguments =
20449            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
20450                .expect("workflow arguments");
20451        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
20452        let task = QueryTask {
20453            query_task_id: "typed-replay-query".to_string(),
20454            query_task_attempt: 1,
20455            lease_owner: Some("rust-worker".to_string()),
20456            workflow_id: Some("typed-replay".to_string()),
20457            run_id: Some("typed-replay-run".to_string()),
20458            workflow_type: "typed.contract.replayed".to_string(),
20459            query_name: "observed".to_string(),
20460            payload_codec: DEFAULT_CODEC.to_string(),
20461            workflow_arguments: Some(workflow_arguments),
20462            query_arguments: Some(
20463                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20464                    .expect("query arguments"),
20465            ),
20466            history_events: vec![
20467                history_event(
20468                    "ActivityScheduled",
20469                    json!({
20470                        "sequence": 1,
20471                        "activity_type": "typed.contract.activity"
20472                    }),
20473                ),
20474                history_event(
20475                    "ActivityCompleted",
20476                    json!({
20477                        "sequence": 1,
20478                        "activity_type": "typed.contract.activity",
20479                        "payload_codec": DEFAULT_CODEC,
20480                        "result": result
20481                    }),
20482                ),
20483            ],
20484            history_export: None,
20485            run_status: Some("completed".to_string()),
20486        };
20487
20488        assert_eq!(
20489            worker
20490                .execute_query_task(task)
20491                .await
20492                .expect("typed replay query")
20493                .deserialize::<i64>()
20494                .expect("query result"),
20495            expected.signed
20496        );
20497    }
20498
20499    #[tokio::test]
20500    async fn update_context_preserves_workflow_input_and_committed_signals() {
20501        let client = Client::new("http://127.0.0.1:8080").expect("client");
20502        let mut worker = Worker::new(client, "rust-workers");
20503        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20504        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
20505        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
20506        let expected_input = workflow_input.clone();
20507        let expected_signals = signal_arguments.clone();
20508        let handler = move |context: QueryContext, arguments: AvroValue| {
20509            let expected_input = expected_input.clone();
20510            let expected_signals = expected_signals.clone();
20511            async move {
20512                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
20513                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
20514                assert_eq!(context.workflow_input_avro_value(), &expected_input);
20515                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
20516                assert_eq!(
20517                    context.signals_avro_value("changed"),
20518                    vec![expected_signals.clone()]
20519                );
20520                assert_eq!(
20521                    context.signals("changed"),
20522                    vec![expected_signals
20523                        .into_iter()
20524                        .map(AvroValue::into_json)
20525                        .collect::<Result<Vec<_>>>()?]
20526                );
20527                assert_eq!(
20528                    context.signal_events()[0].id.as_deref(),
20529                    Some("signal-original")
20530                );
20531                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
20532                Ok(arguments)
20533            }
20534        };
20535        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
20536        worker.register_update_avro_value("snapshot", "inspect", handler);
20537        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
20538        let update_envelope =
20539            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
20540        let mut task = workflow_task(
20541            "snapshot",
20542            vec![
20543                history_event(
20544                    "SignalReceived",
20545                    json!({
20546                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
20547                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
20548                    }),
20549                ),
20550                history_event(
20551                    "UpdateAccepted",
20552                    json!({
20553                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
20554                    }),
20555                ),
20556            ],
20557            DEFAULT_CODEC,
20558        );
20559        task.arguments =
20560            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
20561        task.workflow_update_id = Some("update-original".into());
20562        task.update_name = Some("inspect".into());
20563        let query = QueryTask {
20564            query_task_id: "query-snapshot".into(),
20565            query_task_attempt: 1,
20566            lease_owner: None,
20567            workflow_id: task.workflow_id.clone(),
20568            run_id: task.run_id.clone(),
20569            workflow_type: task.workflow_type.clone(),
20570            query_name: "inspect".into(),
20571            payload_codec: DEFAULT_CODEC.into(),
20572            workflow_arguments: task.arguments.clone(),
20573            query_arguments: Some(update_envelope),
20574            history_events: task.history_events.clone(),
20575            history_export: None,
20576            run_status: Some("running".into()),
20577        };
20578        assert_eq!(
20579            worker
20580                .execute_query_task(query)
20581                .await
20582                .expect("query snapshot"),
20583            update_arguments
20584        );
20585        for _ in 0..2 {
20586            let commands = worker
20587                .execute_workflow_task(task.clone())
20588                .expect("cold update snapshot");
20589            assert_eq!(commands[0]["type"], "complete_update");
20590            assert_eq!(commands[0]["update_id"], "update-original");
20591            assert_eq!(
20592                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20593                    .expect("update result"),
20594                update_arguments
20595            );
20596        }
20597    }
20598
20599    #[test]
20600    fn committed_signal_snapshot_counts_identities_once() {
20601        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
20602        let received = history_event(
20603            "SignalReceived",
20604            json!({
20605                "signal_id": "signal-first", "workflow_command_id": "command-first",
20606                "signal_name": "changed", "arguments": arguments.clone(),
20607            }),
20608        );
20609        let applied = history_event(
20610            "SignalApplied",
20611            json!({
20612                "signal_id": "signal-first", "workflow_command_id": "command-first",
20613                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
20614            }),
20615        );
20616        let distinct = history_event(
20617            "SignalReceived",
20618            json!({
20619                "signal_id": "signal-second", "workflow_command_id": "command-second",
20620                "signal_name": "changed", "arguments": arguments,
20621            }),
20622        );
20623        let history = vec![received.clone(), applied.clone(), distinct];
20624        let signals =
20625            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
20626        assert_eq!(signals.len(), 2);
20627        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20628        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
20629        assert_eq!(signals[0].workflow_sequence, Some(1));
20630        assert_eq!(signals[0].arguments, signals[1].arguments);
20631        let mut command_only = received.clone();
20632        command_only
20633            .payload
20634            .as_object_mut()
20635            .expect("payload")
20636            .remove("signal_id");
20637        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
20638            .expect("command identity");
20639        assert_eq!(signals.len(), 1);
20640        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20641        let mut conflicting = applied;
20642        conflicting.payload["value"] =
20643            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
20644        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
20645    }
20646
20647    #[test]
20648    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
20649        for arguments in [
20650            vec![],
20651            vec![AvroValue::Array(vec![
20652                AvroValue::Long(1),
20653                AvroValue::Long(2),
20654            ])],
20655            vec![AvroValue::Bytes(vec![0, 255])],
20656            vec![AvroValue::Null],
20657            vec![AvroValue::Boolean(false)],
20658            vec![
20659                AvroValue::Long(1),
20660                AvroValue::Array(vec![AvroValue::Long(2)]),
20661            ],
20662        ] {
20663            let applied = match arguments.as_slice() {
20664                [] => AvroValue::Boolean(true),
20665                [value] => value.clone(),
20666                values => AvroValue::Array(values.to_vec()),
20667            };
20668            for applied in [applied, AvroValue::Array(arguments.clone())] {
20669                let events = vec![
20670                    history_event(
20671                        "SignalReceived",
20672                        json!({
20673                            "signal_id": "original", "signal_name": "changed",
20674                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
20675                        }),
20676                    ),
20677                    history_event(
20678                        "SignalApplied",
20679                        json!({
20680                            "signal_id": "original", "signal_name": "changed",
20681                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
20682                        }),
20683                    ),
20684                ];
20685                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
20686                    .expect("canonical signal snapshot");
20687                assert_eq!(signals.len(), 1);
20688                assert_eq!(signals[0].avro_arguments, arguments);
20689            }
20690        }
20691    }
20692
20693    #[tokio::test]
20694    async fn update_context_rejects_malformed_snapshot_before_handler() {
20695        let client = Client::new("http://127.0.0.1:8080").expect("client");
20696        let mut worker = Worker::new(client, "rust-workers");
20697        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20698        let calls = Arc::new(AtomicUsize::new(0));
20699        let observed = Arc::clone(&calls);
20700        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
20701            observed.fetch_add(1, Ordering::SeqCst);
20702            async { Ok(Value::Null) }
20703        });
20704        let mut task = workflow_task(
20705            "snapshot",
20706            vec![history_event(
20707                "UpdateAccepted",
20708                json!({
20709                    "update_id": "update-original", "update_name": "inspect",
20710                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
20711                }),
20712            )],
20713            DEFAULT_CODEC,
20714        );
20715        task.workflow_update_id = Some("update-original".into());
20716        task.update_name = Some("inspect".into());
20717        let mut bad_input = task.clone();
20718        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
20719        assert!(worker.execute_workflow_task(bad_input).is_err());
20720        task.history_events.insert(0, history_event("SignalReceived", json!({
20721            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
20722        })));
20723        assert!(worker.execute_workflow_task(task).is_err());
20724        assert_eq!(calls.load(Ordering::SeqCst), 0);
20725    }
20726
20727    #[tokio::test]
20728    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
20729        let client = Client::new("http://127.0.0.1:8080").expect("client");
20730        let mut worker = Worker::new(client, "rust-workers");
20731        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
20732        worker
20733            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
20734        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
20735            Ok(input)
20736        });
20737        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
20738            Ok(input)
20739        });
20740        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
20741            Ok(AvroValue::Array(
20742                ctx.wait_signal_avro_value("changed").await?,
20743            ))
20744        });
20745
20746        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
20747        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
20748
20749        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
20750        workflow.arguments = Some(envelope.clone());
20751        let commands = worker
20752            .execute_workflow_task(workflow)
20753            .expect("typed workflow task");
20754        assert_eq!(commands[0]["type"], "complete_workflow");
20755        assert_eq!(
20756            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20757                .expect("typed workflow result"),
20758            arguments
20759        );
20760
20761        let activity = ActivityTask {
20762            task_id: "activity-typed".to_string(),
20763            activity_attempt_id: Some("attempt-typed".to_string()),
20764            attempt_id: None,
20765            activity_type: "typed.activity".to_string(),
20766            payload_codec: DEFAULT_CODEC.to_string(),
20767            arguments: Some(envelope.clone()),
20768            attempt_number: 1,
20769            lease_owner: Some("rust-worker".to_string()),
20770        };
20771        assert_eq!(
20772            worker
20773                .execute_activity_task(activity)
20774                .await
20775                .expect("typed activity result"),
20776            arguments
20777        );
20778
20779        let query = QueryTask {
20780            query_task_id: "query-typed".to_string(),
20781            query_task_attempt: 1,
20782            lease_owner: Some("rust-worker".to_string()),
20783            workflow_id: Some("typed-1".to_string()),
20784            run_id: Some("run-typed".to_string()),
20785            workflow_type: "typed.echo".to_string(),
20786            query_name: "inspect".to_string(),
20787            payload_codec: DEFAULT_CODEC.to_string(),
20788            workflow_arguments: Some(
20789                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20790                    .expect("workflow input"),
20791            ),
20792            query_arguments: Some(envelope.clone()),
20793            history_events: Vec::new(),
20794            history_export: None,
20795            run_status: Some("running".to_string()),
20796        };
20797        assert_eq!(
20798            worker
20799                .execute_query_task(query)
20800                .await
20801                .expect("typed query result"),
20802            arguments
20803        );
20804
20805        let mut update = workflow_task(
20806            "typed.echo",
20807            vec![history_event(
20808                "UpdateAccepted",
20809                json!({
20810                    "update_id": "update-typed",
20811                    "update_name": "replace",
20812                    "arguments": envelope.clone(),
20813                }),
20814            )],
20815            DEFAULT_CODEC,
20816        );
20817        update.workflow_update_id = Some("update-typed".to_string());
20818        update.update_name = Some("replace".to_string());
20819        let commands = worker
20820            .execute_workflow_task(update)
20821            .expect("typed update task");
20822        assert_eq!(commands[0]["type"], "complete_update");
20823        assert_eq!(
20824            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20825                .expect("typed update result"),
20826            arguments
20827        );
20828
20829        let mut signal = workflow_task(
20830            "typed.signal",
20831            vec![history_event(
20832                "SignalReceived",
20833                json!({
20834                    "signal_id": "signal-typed",
20835                    "signal_name": "changed",
20836                    "arguments": envelope.clone(),
20837                }),
20838            )],
20839            DEFAULT_CODEC,
20840        );
20841        signal.workflow_signal_id = Some("signal-typed".to_string());
20842        signal.signal_name = Some("changed".to_string());
20843        signal.signal_arguments = Some(envelope);
20844        let commands = worker
20845            .execute_workflow_task(signal)
20846            .expect("typed signal resume");
20847        assert_eq!(
20848            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20849                .expect("typed signal result"),
20850            arguments
20851        );
20852    }
20853
20854    #[tokio::test]
20855    async fn typed_helpers_never_parse_json_inspection_projection() {
20856        let collision_values = projection_collision_probe();
20857        let expected = AvroValue::Array(collision_values.clone());
20858        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
20859
20860        let activity_context = workflow_context_with_codec(
20861            vec![history_event(
20862                "ActivityCompleted",
20863                json!({
20864                    "sequence": 1,
20865                    "activity_type": "collision.activity",
20866                    "payload_codec": DEFAULT_CODEC,
20867                    "result": envelope.clone(),
20868                }),
20869            )],
20870            DEFAULT_CODEC,
20871        );
20872        assert_eq!(
20873            activity_context
20874                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
20875                .await
20876                .expect("typed activity collision result"),
20877            expected
20878        );
20879
20880        let signal_context = workflow_context_with_codec(
20881            vec![
20882                history_event(
20883                    "SignalWaitOpened",
20884                    json!({"sequence": 1, "signal_name": "collision"}),
20885                ),
20886                history_event(
20887                    "SignalApplied",
20888                    json!({
20889                        "sequence": 1,
20890                        "signal_name": "collision",
20891                        "payload_codec": DEFAULT_CODEC,
20892                        "value": envelope.clone(),
20893                    }),
20894                ),
20895            ],
20896            DEFAULT_CODEC,
20897        );
20898        assert_eq!(
20899            signal_context
20900                .wait_signal_avro_value("collision")
20901                .await
20902                .expect("typed signal collision arguments"),
20903            collision_values
20904        );
20905
20906        let child_context = workflow_context_with_codec(
20907            vec![
20908                history_event(
20909                    "ChildWorkflowScheduled",
20910                    json!({
20911                        "sequence": 1,
20912                        "child_workflow_instance_id": "collision-child",
20913                        "child_workflow_run_id": "collision-run",
20914                        "child_workflow_type": "collision.child",
20915                    }),
20916                ),
20917                history_event(
20918                    "ChildRunCompleted",
20919                    json!({
20920                        "sequence": 1,
20921                        "child_workflow_instance_id": "collision-child",
20922                        "child_workflow_run_id": "collision-run",
20923                        "child_workflow_type": "collision.child",
20924                        "payload_codec": DEFAULT_CODEC,
20925                        "result": envelope,
20926                    }),
20927                ),
20928            ],
20929            DEFAULT_CODEC,
20930        );
20931        let child = child_context
20932            .start_child_workflow_avro_value(
20933                "collision.child",
20934                ChildWorkflowOptions::new("collision-workers"),
20935                AvroValue::Array(Vec::new()),
20936            )
20937            .await
20938            .expect("typed child collision result");
20939        assert_eq!(child.result, expected);
20940    }
20941
20942    #[tokio::test]
20943    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
20944        let client = Client::new("http://127.0.0.1:8080").expect("client");
20945        let mut worker = Worker::new(client, "rust-workers");
20946        worker.register_replayed_workflow_avro_value(
20947            "typed.replayed",
20948            || (),
20949            |_ctx, input, _state| async move { Ok(input) },
20950        );
20951        worker.register_replayed_query_avro_value::<(), _, _>(
20952            "typed.replayed",
20953            "inspect",
20954            |ctx, _state, args| async move {
20955                let mut signals = ctx.signals_avro_value("collision");
20956                let signal = signals
20957                    .pop()
20958                    .map(AvroValue::Array)
20959                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
20960                Ok(AvroValue::Array(vec![
20961                    ctx.workflow_input_avro_value().clone(),
20962                    signal,
20963                    args,
20964                ]))
20965            },
20966        );
20967        let arguments = AvroValue::Array(projection_collision_probe());
20968        let signal_arguments =
20969            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
20970        let task = QueryTask {
20971            query_task_id: "query-typed-replay".to_string(),
20972            query_task_attempt: 1,
20973            lease_owner: Some("rust-worker".to_string()),
20974            workflow_id: Some("typed-replay".to_string()),
20975            run_id: Some("run-typed-replay".to_string()),
20976            workflow_type: "typed.replayed".to_string(),
20977            query_name: "inspect".to_string(),
20978            payload_codec: DEFAULT_CODEC.to_string(),
20979            workflow_arguments: Some(
20980                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
20981            ),
20982            query_arguments: Some(
20983                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
20984            ),
20985            history_events: vec![history_event(
20986                "SignalReceived",
20987                json!({
20988                    "signal_id": "collision-signal",
20989                    "signal_name": "collision",
20990                    "workflow_sequence": 1,
20991                    "payload_codec": DEFAULT_CODEC,
20992                    "arguments": signal_arguments,
20993                }),
20994            )],
20995            history_export: None,
20996            run_status: Some("completed".to_string()),
20997        };
20998
20999        assert_eq!(
21000            worker
21001                .execute_query_task(task)
21002                .await
21003                .expect("typed replay query"),
21004            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
21005        );
21006    }
21007
21008    #[test]
21009    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
21010        let value = BTreeMap::from([(1_i32, "integer key")]);
21011        let error = PayloadEnvelope::avro(&value)
21012            .expect_err("integer map keys must fail")
21013            .to_string();
21014
21015        assert!(error.contains("invalid_map_key"));
21016    }
21017
21018    #[test]
21019    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
21020        let envelope = PayloadEnvelope {
21021            codec: "json".to_string(),
21022            blob: r#"{"greeting":"hello"}"#.to_string(),
21023        };
21024
21025        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
21026        let diagnostic = error.to_string();
21027        assert!(diagnostic.contains("unsupported_payload_codec"));
21028        assert!(diagnostic.contains("codec=\"avro\""));
21029        assert!(diagnostic.contains("HTTP document transport"));
21030    }
21031
21032    #[test]
21033    fn untagged_json_payload_value_fails_closed() {
21034        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
21035            .expect_err("untagged JSON payload values must fail");
21036        let diagnostic = error.to_string();
21037        assert!(diagnostic.contains("unsupported_payload_codec"));
21038        assert!(diagnostic.contains("untagged durable payload"));
21039        assert!(diagnostic.contains("HTTP document transport"));
21040    }
21041
21042    #[test]
21043    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
21044        let envelope = PayloadEnvelope {
21045            codec: DEFAULT_CODEC.to_string(),
21046            blob: BASE64.encode([0x01]),
21047        };
21048
21049        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
21050        assert!(error.to_string().contains("invalid_payload_framing"));
21051    }
21052
21053    #[tokio::test]
21054    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
21055        let server = MockWorkerServer::start();
21056        let client = Client::builder(server.base_url())
21057            .timeout(Duration::from_secs(2))
21058            .build()
21059            .expect("client");
21060        let invalid_commands = [
21061            json!({
21062                "type": "complete_workflow",
21063                "result": {"codec": "json", "blob": null}
21064            }),
21065            json!({
21066                "type": "schedule_activity",
21067                "arguments": {"codec": "yaml", "blob": "ignored"}
21068            }),
21069            json!({
21070                "type": "start_child_workflow",
21071                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
21072            }),
21073            json!({"type": "continue_as_new", "arguments": []}),
21074            json!({"type": "complete_update"}),
21075            json!({"type": "record_side_effect", "result": null}),
21076            json!({
21077                "type": "start_service_operation",
21078                "payload_codec": DEFAULT_CODEC,
21079                "request_payload": "raw-avro-bytes"
21080            }),
21081        ];
21082
21083        for command in invalid_commands {
21084            let error = client
21085                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
21086                .await
21087                .expect_err("invalid durable payload must fail locally");
21088            let diagnostic = error.to_string();
21089            assert!(
21090                diagnostic.contains("unsupported_payload_codec")
21091                    || diagnostic.contains("invalid_payload_envelope")
21092                    || diagnostic.contains("untagged durable payload"),
21093                "unexpected validation diagnostic: {diagnostic}"
21094            );
21095        }
21096
21097        assert_eq!(
21098            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
21099            0,
21100            "invalid command payloads must not reach HTTP transport"
21101        );
21102    }
21103
21104    #[test]
21105    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
21106        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
21107        let commands = [
21108            json!({"type": "complete_workflow", "result": envelope.clone()}),
21109            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
21110            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
21111            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
21112            json!({"type": "complete_update", "result": envelope.clone()}),
21113            json!({"type": "record_side_effect", "result": envelope.clone()}),
21114            json!({
21115                "type": "start_service_operation",
21116                "payload_codec": DEFAULT_CODEC,
21117                "request_payload": envelope.clone()
21118            }),
21119            json!({
21120                "type": "complete_workflow",
21121                "result": envelope,
21122                "metadata": {
21123                    "codec": "json",
21124                    "payload_codec": "customer-codec",
21125                    "result": {"codec": "yaml", "blob": null}
21126                }
21127            }),
21128        ];
21129
21130        validate_workflow_task_commands(&commands)
21131            .expect("customer metadata must not become a protocol codec declaration");
21132    }
21133
21134    #[test]
21135    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
21136        assert_eq!(
21137            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
21138            AvroValue::Array(Vec::new())
21139        );
21140        assert_eq!(
21141            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
21142            AvroValue::Array(Vec::new())
21143        );
21144
21145        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21146        signal.signal_name = Some("empty-signal".to_string());
21147        signal.signal_arguments = None;
21148        let decoded = decode_resume_signal(&signal)
21149            .expect("valid Avro signal")
21150            .expect("named signal resumes the workflow");
21151        assert!(decoded.arguments.is_empty());
21152    }
21153
21154    #[tokio::test]
21155    async fn malformed_task_level_codecs_become_pre_handler_failures() {
21156        let client = Client::new("http://127.0.0.1:8080").expect("client");
21157        let mut worker = Worker::new(client, "rust-workers");
21158        let handler_calls = Arc::new(AtomicUsize::new(0));
21159
21160        let calls = Arc::clone(&handler_calls);
21161        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21162            calls.fetch_add(1, Ordering::SeqCst);
21163            async move { Ok(Value::Null) }
21164        });
21165        let calls = Arc::clone(&handler_calls);
21166        worker.register_activity("codec.activity", move |_ctx, _args| {
21167            calls.fetch_add(1, Ordering::SeqCst);
21168            async move { Ok(Value::Null) }
21169        });
21170        let calls = Arc::clone(&handler_calls);
21171        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21172            calls.fetch_add(1, Ordering::SeqCst);
21173            async move { Ok(Value::Null) }
21174        });
21175
21176        let mut failures = Vec::new();
21177        for codec_case in [
21178            InvalidTaskPayloadCodec::Missing,
21179            InvalidTaskPayloadCodec::Null,
21180            InvalidTaskPayloadCodec::NonString,
21181        ] {
21182            let mut workflow = json!({
21183                "task_id": format!("workflow-{}", codec_case.label()),
21184                "workflow_type": "codec.workflow"
21185            });
21186            codec_case.apply(&mut workflow);
21187            match serde_json::from_value::<WorkflowTask>(workflow) {
21188                Ok(task) => match worker.execute_workflow_task(task) {
21189                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21190                    outcome => failures.push(format!(
21191                        "workflow {} codec returned {outcome:?}",
21192                        codec_case.label()
21193                    )),
21194                },
21195                Err(error) => failures.push(format!(
21196                    "workflow {} codec failed transport deserialization: {error}",
21197                    codec_case.label()
21198                )),
21199            }
21200
21201            let mut activity = json!({
21202                "task_id": format!("activity-{}", codec_case.label()),
21203                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
21204                "activity_type": "codec.activity",
21205                "attempt_number": 1
21206            });
21207            codec_case.apply(&mut activity);
21208            match serde_json::from_value::<ActivityTask>(activity) {
21209                Ok(task) => match worker.execute_activity_task(task).await {
21210                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21211                    outcome => failures.push(format!(
21212                        "activity {} codec returned {outcome:?}",
21213                        codec_case.label()
21214                    )),
21215                },
21216                Err(error) => failures.push(format!(
21217                    "activity {} codec failed transport deserialization: {error}",
21218                    codec_case.label()
21219                )),
21220            }
21221
21222            let mut query = json!({
21223                "query_task_id": format!("query-{}", codec_case.label()),
21224                "workflow_type": "codec.workflow",
21225                "query_name": "known"
21226            });
21227            codec_case.apply(&mut query);
21228            match serde_json::from_value::<QueryTask>(query) {
21229                Ok(task) => match worker.execute_query_task(task).await {
21230                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
21231                    outcome => failures.push(format!(
21232                        "query {} codec returned {outcome:?}",
21233                        codec_case.label()
21234                    )),
21235                },
21236                Err(error) => failures.push(format!(
21237                    "query {} codec failed transport deserialization: {error}",
21238                    codec_case.label()
21239                )),
21240            }
21241        }
21242
21243        assert!(failures.is_empty(), "{}", failures.join("\n"));
21244        assert_eq!(
21245            handler_calls.load(Ordering::SeqCst),
21246            0,
21247            "invalid task codecs must not invoke a handler"
21248        );
21249    }
21250
21251    #[tokio::test]
21252    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
21253        for codec_case in [
21254            InvalidTaskPayloadCodec::Missing,
21255            InvalidTaskPayloadCodec::Null,
21256            InvalidTaskPayloadCodec::NonString,
21257        ] {
21258            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
21259            let client = Client::builder(server.base_url())
21260                .timeout(Duration::from_secs(2))
21261                .build()
21262                .expect("client");
21263            let mut worker = Worker::new(client, "rust-workers")
21264                .worker_id("codec-worker")
21265                .poll_timeout(Duration::from_millis(10));
21266            let handler_calls = Arc::new(AtomicUsize::new(0));
21267
21268            let calls = Arc::clone(&handler_calls);
21269            worker.register_workflow("codec.workflow", move |_ctx, _args| {
21270                calls.fetch_add(1, Ordering::SeqCst);
21271                async move { Ok(Value::Null) }
21272            });
21273            let calls = Arc::clone(&handler_calls);
21274            worker.register_activity("codec.activity", move |_ctx, _args| {
21275                calls.fetch_add(1, Ordering::SeqCst);
21276                async move { Ok(Value::Null) }
21277            });
21278            let calls = Arc::clone(&handler_calls);
21279            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21280                calls.fetch_add(1, Ordering::SeqCst);
21281                async move { Ok(Value::Null) }
21282            });
21283
21284            assert_eq!(
21285                worker.run_once().await.expect("invalid tasks are settled"),
21286                3,
21287                "all {} codec tasks must be handled",
21288                codec_case.label()
21289            );
21290            assert_eq!(
21291                handler_calls.load(Ordering::SeqCst),
21292                0,
21293                "{} task codecs must fail before every handler",
21294                codec_case.label()
21295            );
21296
21297            for path in [
21298                "/api/worker/workflow-tasks/codec-workflow/fail",
21299                "/api/worker/activity-tasks/codec-activity/fail",
21300                "/api/worker/query-tasks/codec-query/fail",
21301            ] {
21302                let body = server.request_body(path);
21303                assert!(
21304                    body["failure"]["message"]
21305                        .as_str()
21306                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
21307                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
21308                    codec_case.label()
21309                );
21310            }
21311            assert_eq!(
21312                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
21313                    ["reason"],
21314                "query_payload_decode_failed"
21315            );
21316            for path in [
21317                "/api/worker/workflow-tasks/codec-workflow/complete",
21318                "/api/worker/activity-tasks/codec-activity/complete",
21319                "/api/worker/query-tasks/codec-query/complete",
21320            ] {
21321                assert_eq!(
21322                    server.request_count(path),
21323                    0,
21324                    "invalid {} codec task reached {path}",
21325                    codec_case.label()
21326                );
21327            }
21328        }
21329    }
21330
21331    #[tokio::test]
21332    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
21333        let client = Client::new("http://127.0.0.1:8080").expect("client");
21334        let mut worker = Worker::new(client, "rust-workers");
21335        let handler_calls = Arc::new(AtomicUsize::new(0));
21336
21337        let calls = Arc::clone(&handler_calls);
21338        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21339            calls.fetch_add(1, Ordering::SeqCst);
21340            async move { Ok(Value::Null) }
21341        });
21342        let calls = Arc::clone(&handler_calls);
21343        worker.register_activity("codec.activity", move |_ctx, _args| {
21344            calls.fetch_add(1, Ordering::SeqCst);
21345            async move { Ok(Value::Null) }
21346        });
21347        let calls = Arc::clone(&handler_calls);
21348        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
21349            calls.fetch_add(1, Ordering::SeqCst);
21350            async move { Ok(Value::Null) }
21351        });
21352        let calls = Arc::clone(&handler_calls);
21353        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21354            calls.fetch_add(1, Ordering::SeqCst);
21355            async move { Ok(Value::Null) }
21356        });
21357
21358        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21359        workflow.payload_codec = "json".to_string();
21360        workflow.arguments = None;
21361        let error = worker
21362            .execute_workflow_task(workflow)
21363            .expect_err("task codec must be checked before workflow invocation");
21364        assert!(error.to_string().contains("unsupported_payload_codec"));
21365
21366        let activity = ActivityTask {
21367            task_id: "activity-invalid-codec".to_string(),
21368            activity_attempt_id: None,
21369            attempt_id: None,
21370            activity_type: "codec.activity".to_string(),
21371            payload_codec: "unknown".to_string(),
21372            arguments: None,
21373            attempt_number: 1,
21374            lease_owner: None,
21375        };
21376        let error = worker
21377            .execute_activity_task(activity)
21378            .await
21379            .expect_err("task codec must be checked before activity invocation");
21380        assert!(error.to_string().contains("unsupported_payload_codec"));
21381
21382        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21383        update.workflow_update_id = Some("update-invalid-codec".to_string());
21384        update.update_name = Some("known".to_string());
21385        update.history_events.push(history_event(
21386            "UpdateAccepted",
21387            json!({
21388                "update_id": "update-invalid-codec",
21389                "update_name": "known",
21390                "arguments": {"codec": "json", "blob": null}
21391            }),
21392        ));
21393        let error = worker
21394            .execute_workflow_task(update)
21395            .expect_err("nested update codec must be checked before handler lookup");
21396        assert!(error.to_string().contains("unsupported_payload_codec"));
21397
21398        let query: QueryTask = serde_json::from_value(json!({
21399            "query_task_id": "query-invalid-codec",
21400            "workflow_type": "codec.workflow",
21401            "query_name": "known",
21402            "payload_codec": DEFAULT_CODEC,
21403            "workflow_arguments": null,
21404            "query_arguments": null,
21405            "history_export": {
21406                "payloads": {"codec": DEFAULT_CODEC},
21407                "signals": [{
21408                    "name": "empty",
21409                    "payload_codec": "json",
21410                    "arguments": null
21411                }]
21412            }
21413        }))
21414        .expect("query task");
21415        let failure = worker
21416            .execute_query_task(query)
21417            .await
21418            .expect_err("exported signal codec must be checked before query invocation");
21419        assert_eq!(failure.reason, "query_payload_decode_failed");
21420        assert!(failure.message.contains("unsupported_payload_codec"));
21421
21422        let exported_history: QueryTask = serde_json::from_value(json!({
21423            "query_task_id": "query-invalid-history-codec",
21424            "workflow_type": "codec.workflow",
21425            "query_name": "known",
21426            "payload_codec": DEFAULT_CODEC,
21427            "history_export": {
21428                "payloads": {"codec": DEFAULT_CODEC},
21429                "history_events": [{
21430                    "type": "ActivityCompleted",
21431                    "payload": {"payload_codec": "unknown", "result": null}
21432                }]
21433            }
21434        }))
21435        .expect("query task");
21436        let failure = worker
21437            .execute_query_task(exported_history)
21438            .await
21439            .expect_err("exported history codec must be checked before query invocation");
21440        assert_eq!(failure.reason, "query_payload_decode_failed");
21441        assert!(failure.message.contains("unsupported_payload_codec"));
21442        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
21443
21444        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21445        unknown_workflow.arguments = None;
21446        unknown_workflow.history_events.push(history_event(
21447            "SignalReceived",
21448            json!({
21449                "signal_name": "empty",
21450                "payload_codec": "json",
21451                "arguments": null
21452            }),
21453        ));
21454        let error = worker
21455            .execute_workflow_task(unknown_workflow)
21456            .expect_err("history codec must precede unknown workflow outcome");
21457        assert!(error.to_string().contains("unsupported_payload_codec"));
21458
21459        let unknown_activity = ActivityTask {
21460            task_id: "activity-unknown".to_string(),
21461            activity_attempt_id: None,
21462            attempt_id: None,
21463            activity_type: "missing".to_string(),
21464            payload_codec: "json".to_string(),
21465            arguments: None,
21466            attempt_number: 1,
21467            lease_owner: None,
21468        };
21469        let error = worker
21470            .execute_activity_task(unknown_activity)
21471            .await
21472            .expect_err("codec must precede unknown activity outcome");
21473        assert!(error.to_string().contains("unsupported_payload_codec"));
21474
21475        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21476        unknown_update.payload_codec = "json".to_string();
21477        unknown_update.arguments = None;
21478        unknown_update.workflow_update_id = Some("update-unknown".to_string());
21479        unknown_update.update_name = Some("missing".to_string());
21480        let error = worker
21481            .execute_workflow_task(unknown_update)
21482            .expect_err("codec must precede fail_update shortcut");
21483        assert!(error.to_string().contains("unsupported_payload_codec"));
21484
21485        let unknown_query: QueryTask = serde_json::from_value(json!({
21486            "query_task_id": "query-unknown",
21487            "workflow_type": "missing",
21488            "query_name": "missing",
21489            "payload_codec": "json",
21490            "workflow_arguments": null,
21491            "query_arguments": null
21492        }))
21493        .expect("query task");
21494        let failure = worker
21495            .execute_query_task(unknown_query)
21496            .await
21497            .expect_err("codec must precede unknown query outcome");
21498        assert_eq!(failure.reason, "query_payload_decode_failed");
21499        assert!(failure.message.contains("unsupported_payload_codec"));
21500    }
21501
21502    #[tokio::test]
21503    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
21504        let client = Client::new("http://127.0.0.1:8080").expect("client");
21505        let worker = Worker::new(client, "rust-workers");
21506
21507        for event_type in ["SignalReceived", "SignalApplied"] {
21508            for (payload_field, codec) in [
21509                ("value", "json"),
21510                ("input", "unknown"),
21511                ("arguments", "json"),
21512            ] {
21513                let payload = json!({
21514                    "signal_name": "empty",
21515                    payload_field: {"codec": codec, "blob": null}
21516                });
21517                let workflow = workflow_task(
21518                    "missing",
21519                    vec![history_event(event_type, payload.clone())],
21520                    DEFAULT_CODEC,
21521                );
21522                let error = worker
21523                    .execute_workflow_task(workflow)
21524                    .expect_err("signal payload codec must precede unknown workflow outcome");
21525                assert!(
21526                    error.to_string().contains("unsupported_payload_codec"),
21527                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
21528                );
21529
21530                let query: QueryTask = serde_json::from_value(json!({
21531                    "query_task_id": format!("query-{event_type}-{payload_field}"),
21532                    "workflow_type": "missing",
21533                    "query_name": "missing",
21534                    "payload_codec": DEFAULT_CODEC,
21535                    "workflow_arguments": null,
21536                    "query_arguments": null,
21537                    "history_events": [{
21538                        "event_type": event_type,
21539                        "payload": payload
21540                    }]
21541                }))
21542                .expect("query task");
21543                let failure = worker
21544                    .execute_query_task(query)
21545                    .await
21546                    .expect_err("signal payload codec must precede unknown query outcome");
21547                assert_eq!(
21548                    failure.reason, "query_payload_decode_failed",
21549                    "{event_type}.{payload_field} returned an unrelated query outcome"
21550                );
21551                assert!(
21552                    failure.message.contains("unsupported_payload_codec"),
21553                    "{event_type}.{payload_field} returned an unrelated query error: {}",
21554                    failure.message
21555                );
21556            }
21557        }
21558    }
21559
21560    #[test]
21561    fn workflow_context_schedules_activity_until_completion_is_in_history() {
21562        let ctx = WorkflowContext {
21563            cancellation_scope_id: "root".into(),
21564            state: Arc::new(Mutex::new(
21565                WorkflowState::new_with_identity(
21566                    Vec::new(),
21567                    Some("wf-parent".to_string()),
21568                    Some("run-parent".to_string()),
21569                    "rust-workers".to_string(),
21570                    DEFAULT_CODEC.to_string(),
21571                    None,
21572                )
21573                .expect("workflow state"),
21574            )),
21575        };
21576
21577        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
21578        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21579        assert!(matches!(
21580            call.as_mut().poll(&mut task_context),
21581            Poll::Pending
21582        ));
21583
21584        let commands = ctx.take_commands().expect("commands");
21585        assert_eq!(commands[0]["type"], "schedule_activity");
21586        assert_eq!(commands[0]["activity_type"], "hello.activity");
21587    }
21588
21589    #[test]
21590    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
21591        let ctx = workflow_context(Vec::new());
21592        let options = ActivityOptions::new()
21593            .task_queue("payments")
21594            .retry_policy(
21595                ActivityRetryPolicy::new(4)
21596                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
21597                    .non_retryable_error_type("ValidationError"),
21598            )
21599            .start_to_close_timeout(Duration::from_secs(120))
21600            .schedule_to_start_timeout(Duration::from_secs(10))
21601            .schedule_to_close_timeout(Duration::from_secs(300))
21602            .heartbeat_timeout(Duration::from_secs(15));
21603        let mut call = Box::pin(ctx.activity_with_options(
21604            "charge-card",
21605            options,
21606            json!([{"order_id": "o-1"}]),
21607        ));
21608        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21609
21610        assert!(matches!(
21611            call.as_mut().poll(&mut task_context),
21612            Poll::Pending
21613        ));
21614        assert!(matches!(
21615            call.as_mut().poll(&mut task_context),
21616            Poll::Pending
21617        ));
21618
21619        let commands = ctx.take_commands().expect("activity command");
21620        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
21621        assert_eq!(commands[0]["queue"], "payments");
21622        assert_eq!(
21623            commands[0]["retry_policy"],
21624            json!({
21625                "max_attempts": 4,
21626                "backoff_seconds": [1, 3, 9],
21627                "non_retryable_error_types": ["ValidationError"],
21628            })
21629        );
21630        assert_eq!(commands[0]["start_to_close_timeout"], 120);
21631        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
21632        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
21633        assert_eq!(commands[0]["heartbeat_timeout"], 15);
21634    }
21635
21636    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
21637        vec![
21638            history_event(
21639                "ActivityScheduled",
21640                json!({"sequence":1,"activity_type":"render",
21641                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
21642            ),
21643            history_event(
21644                "ActivityCompleted",
21645                json!({"sequence":1,"activity_type":"render",
21646                "payload_codec":DEFAULT_CODEC,
21647                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
21648            ),
21649        ]
21650    }
21651
21652    #[test]
21653    fn worker_session_activity_routes_to_session_queue_once() {
21654        let ctx = workflow_context(Vec::new());
21655        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21656        let mut call = Box::pin(
21657            ctx.activity("render", json!([]))
21658                .in_worker_session(session.clone()),
21659        );
21660        let mut cx = TaskContext::from_waker(noop_waker_ref());
21661        assert!(call.as_mut().poll(&mut cx).is_pending());
21662        assert!(call.as_mut().poll(&mut cx).is_pending());
21663        let commands = ctx.take_commands().unwrap();
21664        assert_eq!(commands.len(), 1);
21665        assert_eq!(commands[0]["queue"], "gpu-workers");
21666        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
21667    }
21668
21669    #[tokio::test]
21670    async fn worker_session_cold_replay_uses_recorded_avro_result() {
21671        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21672        for _replacement in 0..2 {
21673            let ctx = workflow_context(completed_worker_session_history(&session));
21674            let result: i64 = ctx
21675                .activity("render", json!([]))
21676                .in_worker_session(session.clone())
21677                .typed()
21678                .await
21679                .unwrap();
21680            assert_eq!(result, 42);
21681            assert!(ctx.take_commands().unwrap().is_empty());
21682        }
21683    }
21684
21685    #[test]
21686    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
21687        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21688        for changed in [
21689            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
21690            Some(original.clone().ttl_seconds(60)),
21691            Some(original.clone().requirements(["gpu:l4"])),
21692            None,
21693        ] {
21694            let ctx = workflow_context(completed_worker_session_history(&original));
21695            let mut call = ctx.activity_with_options(
21696                "render",
21697                ActivityOptions::new().task_queue("gpu-workers"),
21698                json!([]),
21699            );
21700            if let Some(changed) = changed {
21701                call = call.in_worker_session(changed);
21702            }
21703            let mut call = Box::pin(call);
21704            let mut cx = TaskContext::from_waker(noop_waker_ref());
21705            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21706                call.as_mut().poll(&mut cx)
21707            else {
21708                panic!("changed session must fail replay");
21709            };
21710            assert_eq!(failure.reason, "activity_worker_session_mismatch");
21711            assert!(ctx.take_commands().unwrap().is_empty());
21712        }
21713    }
21714
21715    #[test]
21716    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
21717        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21718        let ctx = workflow_context(Vec::new());
21719        let mut local = Box::pin(
21720            ctx.local_activity("render", json!([]))
21721                .in_worker_session(session.clone()),
21722        );
21723        let mut cx = TaskContext::from_waker(noop_waker_ref());
21724        assert!(matches!(
21725            local.as_mut().poll(&mut cx),
21726            Poll::Ready(Err(Error::WorkerLoop(_)))
21727        ));
21728        assert!(ctx.take_commands().unwrap().is_empty());
21729        let mut remote = Box::pin(
21730            ctx.activity_with_options(
21731                "render",
21732                ActivityOptions::new().task_queue("other"),
21733                json!([]),
21734            )
21735            .in_worker_session(session),
21736        );
21737        assert!(matches!(
21738            remote.as_mut().poll(&mut cx),
21739            Poll::Ready(Err(Error::WorkerLoop(_)))
21740        ));
21741        assert!(ctx.take_commands().unwrap().is_empty());
21742    }
21743
21744    #[test]
21745    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
21746        let ctx = workflow_context(Vec::new());
21747        let options = ActivityOptions::new().retry_policy(
21748            ActivityRetryPolicy::new(3)
21749                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
21750        );
21751        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21752        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21753
21754        assert!(matches!(
21755            call.as_mut().poll(&mut task_context),
21756            Poll::Pending
21757        ));
21758        assert_eq!(
21759            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
21760            json!([1, 2])
21761        );
21762    }
21763
21764    #[test]
21765    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
21766        let cases = [
21767            (
21768                ActivityOptions::new().task_queue("  "),
21769                ActivityOptionsErrorKind::EmptyTaskQueue,
21770            ),
21771            (
21772                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
21773                ActivityOptionsErrorKind::EmptyRetryPolicy,
21774            ),
21775            (
21776                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
21777                ActivityOptionsErrorKind::InvalidMaxAttempts,
21778            ),
21779            (
21780                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
21781                    max_attempts: None,
21782                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
21783                    non_retryable_error_types: Vec::new(),
21784                }),
21785                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
21786            ),
21787            (
21788                ActivityOptions::new().retry_policy(
21789                    ActivityRetryPolicy::new(2)
21790                        .backoff_intervals([Duration::from_secs(1), Duration::from_secs(2)]),
21791                ),
21792                ActivityOptionsErrorKind::TooManyBackoffIntervals,
21793            ),
21794            (
21795                ActivityOptions::new().retry_policy(
21796                    ActivityRetryPolicy::new(2).exponential_backoff(
21797                        Duration::from_secs(1),
21798                        0,
21799                        None,
21800                    ),
21801                ),
21802                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
21803            ),
21804            (
21805                ActivityOptions::new()
21806                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
21807                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
21808            ),
21809            (
21810                ActivityOptions::new().retry_policy(
21811                    ActivityRetryPolicy::new(10_002).exponential_backoff(
21812                        Duration::from_secs(1),
21813                        1,
21814                        None,
21815                    ),
21816                ),
21817                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
21818            ),
21819            (
21820                ActivityOptions::new().retry_policy(
21821                    ActivityRetryPolicy::new(2)
21822                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
21823                ),
21824                ActivityOptionsErrorKind::BackoffOverflow,
21825            ),
21826        ];
21827
21828        for (options, expected_kind) in cases {
21829            let ctx = workflow_context(Vec::new());
21830            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21831            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21832            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
21833                call.as_mut().poll(&mut task_context)
21834            else {
21835                panic!("expected typed activity validation error");
21836            };
21837            assert_eq!(error.kind, expected_kind);
21838            assert!(ctx.take_commands().expect("commands").is_empty());
21839        }
21840    }
21841
21842    #[test]
21843    fn activity_options_validate_positive_and_ordered_timeouts() {
21844        let zero_timeout_cases = [
21845            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
21846            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
21847            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
21848            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
21849        ];
21850        for options in zero_timeout_cases {
21851            assert_eq!(
21852                options.validate().expect_err("zero timeout").kind,
21853                ActivityOptionsErrorKind::TimeoutNotPositive
21854            );
21855        }
21856
21857        let ordering_cases = [
21858            ActivityOptions::new()
21859                .heartbeat_timeout(Duration::from_secs(11))
21860                .start_to_close_timeout(Duration::from_secs(10)),
21861            ActivityOptions::new()
21862                .start_to_close_timeout(Duration::from_secs(31))
21863                .schedule_to_close_timeout(Duration::from_secs(30)),
21864            ActivityOptions::new()
21865                .schedule_to_start_timeout(Duration::from_secs(31))
21866                .schedule_to_close_timeout(Duration::from_secs(30)),
21867        ];
21868        for options in ordering_cases {
21869            assert_eq!(
21870                options.validate().expect_err("timeout order").kind,
21871                ActivityOptionsErrorKind::TimeoutOrder
21872            );
21873        }
21874
21875        assert_eq!(
21876            ActivityOptions::new()
21877                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
21878                .validate()
21879                .expect_err("protocol integer overflow")
21880                .kind,
21881            ActivityOptionsErrorKind::TimeoutOverflow
21882        );
21883    }
21884
21885    #[test]
21886    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
21887        let ctx = workflow_context(completed_retry_activity_history());
21888        let mut call =
21889            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21890        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21891
21892        assert!(matches!(
21893            call.as_mut().poll(&mut task_context),
21894            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21895        ));
21896        assert!(ctx.take_commands().expect("commands").is_empty());
21897        ctx.ensure_history_consumed().expect("history consumed");
21898    }
21899
21900    #[test]
21901    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
21902        let mut options = retry_activity_options();
21903        options
21904            .retry_policy
21905            .as_mut()
21906            .expect("retry policy")
21907            .non_retryable_error_types
21908            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
21909
21910        let new_ctx = workflow_context(Vec::new());
21911        let mut new_call =
21912            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
21913        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21914        assert!(matches!(
21915            new_call.as_mut().poll(&mut task_context),
21916            Poll::Pending
21917        ));
21918        let commands = new_ctx.take_commands().expect("commands");
21919        assert_eq!(commands.len(), 1);
21920        assert_eq!(
21921            commands[0]["retry_policy"]["non_retryable_error_types"],
21922            json!(["PermanentError"])
21923        );
21924
21925        let replay_ctx = workflow_context(completed_retry_activity_history());
21926        let mut replay_call =
21927            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
21928        assert!(matches!(
21929            replay_call.as_mut().poll(&mut task_context),
21930            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21931        ));
21932        assert!(replay_ctx.take_commands().expect("commands").is_empty());
21933        replay_ctx
21934            .ensure_history_consumed()
21935            .expect("history consumed");
21936    }
21937
21938    #[test]
21939    fn replayed_intermediate_retry_remains_pending_across_restarts() {
21940        let history = completed_retry_activity_history()
21941            .into_iter()
21942            .take(3)
21943            .collect::<Vec<_>>();
21944
21945        for _restart in 0..2 {
21946            let ctx = workflow_context(history.clone());
21947            let mut call =
21948                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21949            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21950            assert!(matches!(
21951                call.as_mut().poll(&mut task_context),
21952                Poll::Pending
21953            ));
21954            assert!(ctx.take_commands().expect("commands").is_empty());
21955        }
21956    }
21957
21958    #[test]
21959    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
21960        let mut changed_queue = retry_activity_options();
21961        changed_queue.task_queue = Some("different-queue".to_string());
21962
21963        let mut changed_max_attempts = retry_activity_options();
21964        let retry_policy = changed_max_attempts
21965            .retry_policy
21966            .as_mut()
21967            .expect("retry policy");
21968        retry_policy.max_attempts = Some(4);
21969
21970        let mut changed_backoff = retry_activity_options();
21971        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
21972        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
21973            Duration::from_secs(3),
21974            Duration::from_secs(4),
21975        ]));
21976
21977        let mut changed_non_retryable_types = retry_activity_options();
21978        let retry_policy = changed_non_retryable_types
21979            .retry_policy
21980            .as_mut()
21981            .expect("retry policy");
21982        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
21983
21984        let mut changed_start_to_close = retry_activity_options();
21985        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
21986        let mut changed_schedule_to_start = retry_activity_options();
21987        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
21988        let mut changed_schedule_to_close = retry_activity_options();
21989        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
21990        let mut changed_heartbeat = retry_activity_options();
21991        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
21992
21993        let cases = [
21994            (changed_queue, "activity_task_queue_mismatch"),
21995            (changed_max_attempts, "activity_retry_policy_mismatch"),
21996            (changed_backoff, "activity_retry_policy_mismatch"),
21997            (
21998                changed_non_retryable_types,
21999                "activity_retry_policy_mismatch",
22000            ),
22001            (changed_start_to_close, "activity_retry_policy_mismatch"),
22002            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
22003            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
22004            (changed_heartbeat, "activity_retry_policy_mismatch"),
22005        ];
22006
22007        for (options, expected_reason) in cases {
22008            let ctx = workflow_context(completed_retry_activity_history());
22009            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
22010            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22011            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22012                call.as_mut().poll(&mut task_context)
22013            else {
22014                panic!("changed activity options must fail replay");
22015            };
22016            assert_eq!(failure.reason, expected_reason);
22017            assert_eq!(failure.sequence, Some(1));
22018            assert!(ctx.take_commands().expect("commands").is_empty());
22019        }
22020    }
22021
22022    #[test]
22023    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
22024        let cases = [
22025            (
22026                "execution_mode",
22027                json!("local"),
22028                "activity_execution_mode_mismatch",
22029            ),
22030            (
22031                "snapshot_version",
22032                json!(2),
22033                "activity_retry_policy_mismatch",
22034            ),
22035        ];
22036
22037        for (field, value, expected_reason) in cases {
22038            let mut history = completed_retry_activity_history();
22039            let activity = history[0].payload["activity"]
22040                .as_object_mut()
22041                .expect("activity snapshot");
22042            if field == "execution_mode" {
22043                activity.insert(field.to_string(), value);
22044            } else {
22045                activity["retry_policy"]
22046                    .as_object_mut()
22047                    .expect("retry snapshot")
22048                    .insert(field.to_string(), value);
22049            }
22050
22051            let ctx = workflow_context(history);
22052            let mut call =
22053                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22054            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22055            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22056                call.as_mut().poll(&mut task_context)
22057            else {
22058                panic!("changed {field} must fail replay");
22059            };
22060            assert_eq!(failure.reason, expected_reason);
22061            assert_eq!(failure.sequence, Some(1));
22062            assert!(ctx.take_commands().expect("commands").is_empty());
22063        }
22064    }
22065
22066    #[test]
22067    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
22068        for (nested, field, value, terminal_only) in [
22069            (false, "execution_mode", json!("local"), false),
22070            (false, "local_activity", json!(true), false),
22071            (true, "local_activity", json!(true), false),
22072            (false, "local_activity", json!(true), true),
22073        ] {
22074            let mut history = completed_retry_activity_history();
22075            history[0]
22076                .payload
22077                .as_object_mut()
22078                .unwrap()
22079                .remove("activity");
22080            let event = if terminal_only {
22081                history.last_mut().unwrap()
22082            } else {
22083                &mut history[0]
22084            };
22085            if nested {
22086                event.payload["activity"] = json!({(field): value});
22087            } else {
22088                event.payload[field] = value;
22089            }
22090            let ctx = workflow_context(history);
22091            let mut call =
22092                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22093            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22094            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22095                call.as_mut().poll(&mut task_context)
22096            else {
22097                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
22098            };
22099            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
22100            assert_eq!(failure.sequence, Some(1));
22101            assert!(ctx.take_commands().expect("commands").is_empty());
22102        }
22103    }
22104
22105    #[test]
22106    fn activity_history_rejects_conflicting_local_execution_markers() {
22107        let mut history = completed_retry_activity_history();
22108        history.last_mut().unwrap().payload["local_activity"] = json!(true);
22109        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
22110            .expect_err("remote schedule cannot become a local completion");
22111        assert!(
22112            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
22113            if reason == "activity_execution_mode_conflict")
22114        );
22115    }
22116
22117    #[test]
22118    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
22119        let mut history = completed_retry_activity_history();
22120        let activity = history[0].payload["activity"]
22121            .as_object_mut()
22122            .expect("activity snapshot");
22123        activity.remove("execution_mode");
22124        activity.remove("retry_policy");
22125
22126        let mut current = retry_activity_options();
22127        current.start_to_close_timeout = Some(Duration::from_secs(45));
22128        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
22129        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
22130        current.heartbeat_timeout = Some(Duration::from_secs(12));
22131
22132        let ctx = workflow_context(history);
22133        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
22134        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22135        assert!(matches!(
22136            call.as_mut().poll(&mut task_context),
22137            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22138        ));
22139        assert!(ctx.take_commands().expect("commands").is_empty());
22140        ctx.ensure_history_consumed().expect("history consumed");
22141    }
22142
22143    #[test]
22144    fn terminal_activity_failed_after_start_returns_typed_failure() {
22145        let history = vec![
22146            history_event(
22147                "ActivityScheduled",
22148                json!({
22149                    "sequence": 1,
22150                    "activity_type": "flaky",
22151                    "activity_execution_id": "act-terminal",
22152                    "activity": {
22153                        "id": "act-terminal",
22154                        "sequence": 1,
22155                        "type": "flaky",
22156                        "queue": "critical-activities",
22157                        "retry_policy": {
22158                            "snapshot_version": 1,
22159                            "max_attempts": 3,
22160                            "backoff_seconds": [2, 4],
22161                            "non_retryable_error_types": ["PermanentError"]
22162                        }
22163                    }
22164                }),
22165            ),
22166            history_event(
22167                "ActivityStarted",
22168                json!({
22169                    "sequence": 1,
22170                    "activity_type": "flaky",
22171                    "activity_execution_id": "act-terminal",
22172                    "activity_attempt_id": "attempt-1",
22173                    "attempt_number": 1
22174                }),
22175            ),
22176            history_event(
22177                "ActivityFailed",
22178                json!({
22179                    "sequence": 1,
22180                    "activity_type": "flaky",
22181                    "activity_execution_id": "act-terminal",
22182                    "activity_attempt_id": "attempt-1",
22183                    "attempt_number": 1,
22184                    "failure_id": "failure-terminal",
22185                    "failure_category": "activity",
22186                    "exception_type": "PermanentError",
22187                    "message": "cannot retry",
22188                    "non_retryable": true
22189                }),
22190            ),
22191        ];
22192        let ctx = workflow_context(history);
22193        let mut call =
22194            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22195        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22196
22197        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22198            call.as_mut().poll(&mut task_context)
22199        else {
22200            panic!("terminal ActivityFailed must settle the activity future");
22201        };
22202        assert_eq!(failure.kind, ActivityFailureKind::Failed);
22203        assert_eq!(
22204            failure.activity_execution_id.as_deref(),
22205            Some("act-terminal")
22206        );
22207        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
22208        assert!(failure.non_retryable);
22209        assert!(ctx.take_commands().expect("commands").is_empty());
22210        ctx.ensure_history_consumed().expect("history consumed");
22211    }
22212
22213    #[test]
22214    fn activity_terminal_events_return_machine_readable_failures() {
22215        let cases = [
22216            (
22217                "ActivityFailed",
22218                json!({
22219                    "sequence": 1,
22220                    "activity_type": "charge-card",
22221                    "activity_execution_id": "act-1",
22222                    "activity_attempt_id": "attempt-2",
22223                    "attempt_number": 2,
22224                    "failure_id": "failure-1",
22225                    "failure_category": "activity",
22226                    "exception_type": "PaymentDeclined",
22227                    "exception_class": "payments.PaymentDeclined",
22228                    "message": "card declined",
22229                    "non_retryable": true
22230                }),
22231                ActivityFailureKind::Failed,
22232                "activity",
22233            ),
22234            (
22235                "ActivityCancelled",
22236                json!({
22237                    "sequence": 1,
22238                    "activity_type": "charge-card",
22239                    "activity_execution_id": "act-1",
22240                    "activity_attempt_id": "attempt-1"
22241                }),
22242                ActivityFailureKind::Cancelled,
22243                "cancelled",
22244            ),
22245        ];
22246
22247        for (event_type, payload, expected_kind, expected_reason) in cases {
22248            let ctx = workflow_context(vec![history_event(event_type, payload)]);
22249            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
22250            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22251            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22252                call.as_mut().poll(&mut task_context)
22253            else {
22254                panic!("expected terminal activity failure");
22255            };
22256            assert_eq!(failure.kind, expected_kind);
22257            assert_eq!(failure.reason, expected_reason);
22258            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
22259            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
22260        }
22261    }
22262
22263    #[test]
22264    fn every_activity_timeout_class_is_typed() {
22265        for timeout_kind in [
22266            "start_to_close",
22267            "schedule_to_start",
22268            "schedule_to_close",
22269            "heartbeat",
22270        ] {
22271            let ctx = workflow_context(vec![history_event(
22272                "ActivityTimedOut",
22273                json!({
22274                    "sequence": 1,
22275                    "activity_type": "slow",
22276                    "activity_execution_id": "act-timeout",
22277                    "activity_attempt_id": "attempt-timeout",
22278                    "failure_category": "timeout",
22279                    "timeout_kind": timeout_kind,
22280                    "message": "deadline expired"
22281                }),
22282            )]);
22283            let mut call = Box::pin(ctx.activity("slow", json!([])));
22284            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22285            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22286                call.as_mut().poll(&mut task_context)
22287            else {
22288                panic!("expected timeout failure");
22289            };
22290            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
22291            assert_eq!(failure.reason, timeout_kind);
22292            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
22293            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
22294        }
22295    }
22296
22297    #[test]
22298    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
22299        let ctx = workflow_context(Vec::new());
22300        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
22301        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22302
22303        assert!(matches!(
22304            sleep.as_mut().poll(&mut task_context),
22305            Poll::Pending
22306        ));
22307        assert!(matches!(
22308            sleep.as_mut().poll(&mut task_context),
22309            Poll::Pending
22310        ));
22311
22312        let commands = ctx.take_commands().expect("timer command");
22313        assert_eq!(
22314            commands,
22315            vec![json!({
22316                "type": "start_timer",
22317                "delay_seconds": 2,
22318            })]
22319        );
22320    }
22321
22322    #[test]
22323    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
22324        let history = vec![
22325            history_event(
22326                "TimerScheduled",
22327                json!({
22328                    "sequence": 1,
22329                    "timer_id": "timer-1",
22330                    "delay_seconds": 5,
22331                    "fire_at": "2026-07-11T12:00:05Z",
22332                }),
22333            ),
22334            history_event(
22335                "TimerFired",
22336                json!({
22337                    "sequence": 1,
22338                    "timer_id": "timer-1",
22339                    "delay_seconds": 5,
22340                    "fire_at": "2026-07-11T12:00:05Z",
22341                    "fired_at": "2026-07-11T12:00:05Z",
22342                }),
22343            ),
22344        ];
22345
22346        for _restart in 0..2 {
22347            let ctx = workflow_context(history.clone());
22348            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
22349            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22350            assert!(matches!(
22351                sleep.as_mut().poll(&mut task_context),
22352                Poll::Ready(Ok(()))
22353            ));
22354            assert!(ctx.take_commands().expect("commands").is_empty());
22355            ctx.ensure_history_consumed().expect("history consumed");
22356        }
22357    }
22358
22359    #[test]
22360    fn workflow_sleep_rejects_changed_delay_during_replay() {
22361        let ctx = workflow_context(vec![
22362            history_event(
22363                "TimerScheduled",
22364                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22365            ),
22366            history_event(
22367                "TimerFired",
22368                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22369            ),
22370        ]);
22371        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
22372        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22373
22374        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22375            sleep.as_mut().poll(&mut task_context)
22376        else {
22377            panic!("changed timer delay must be rejected");
22378        };
22379        assert_eq!(failure.reason, "timer_delay_mismatch");
22380        assert_eq!(failure.sequence, Some(1));
22381    }
22382
22383    #[test]
22384    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
22385        let ctx = workflow_context(Vec::new());
22386        let mut wait = Box::pin(
22387            ctx.wait_condition(
22388                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
22389                    .timeout(Duration::from_millis(60_001)),
22390                || Ok(false),
22391            ),
22392        );
22393        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22394
22395        assert!(matches!(
22396            wait.as_mut().poll(&mut task_context),
22397            Poll::Pending
22398        ));
22399        assert!(matches!(
22400            wait.as_mut().poll(&mut task_context),
22401            Poll::Pending
22402        ));
22403        assert_eq!(
22404            ctx.take_commands().expect("condition command"),
22405            vec![json!({
22406                "type": "open_condition_wait",
22407                "condition_wait_occurrence_id": "rust:condition-wait:0",
22408                "condition_key": "approval.ready",
22409                "condition_definition_fingerprint": "sha256:approval-v1",
22410                "timeout_seconds": 61,
22411            })]
22412        );
22413    }
22414
22415    #[test]
22416    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
22417        let ctx = workflow_context(Vec::new());
22418        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
22419        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22420        assert!(matches!(
22421            satisfied.as_mut().poll(&mut task_context),
22422            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22423        ));
22424
22425        let mut timed_out = Box::pin(wait_condition!(
22426            ctx,
22427            "no-wait",
22428            timeout: Duration::ZERO,
22429            || Ok(false),
22430        ));
22431        assert!(matches!(
22432            timed_out.as_mut().poll(&mut task_context),
22433            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22434        ));
22435        assert!(ctx.take_commands().expect("commands").is_empty());
22436    }
22437
22438    #[test]
22439    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
22440        let signal_history = vec![
22441            history_event(
22442                "ConditionWaitOpened",
22443                json!({
22444                    "sequence": 4,
22445                    "condition_wait_id": "condition:4",
22446                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22447                    "condition_key": "approval",
22448                    "condition_definition_fingerprint": "sha256:approval-v1",
22449                    "timeout_seconds": 30,
22450                }),
22451            ),
22452            history_event(
22453                "SignalReceived",
22454                json!({
22455                    "workflow_sequence": 4,
22456                    "signal_name": "approve",
22457                    "arguments": fixture_envelope(json!(["Ada"])),
22458                }),
22459            ),
22460        ];
22461        for _worker_before_or_after_restart in 0..2 {
22462            let ctx = workflow_context(signal_history.clone());
22463            let predicate_ctx = ctx.clone();
22464            let mut wait = Box::pin(
22465                ctx.wait_condition(
22466                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
22467                        .timeout(Duration::from_secs(30)),
22468                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
22469                ),
22470            );
22471            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22472            assert!(matches!(
22473                wait.as_mut().poll(&mut task_context),
22474                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22475            ));
22476            assert!(ctx.take_commands().expect("commands").is_empty());
22477            ctx.ensure_history_consumed().expect("condition consumed");
22478        }
22479
22480        let update_history = vec![
22481            history_event(
22482                "ConditionWaitOpened",
22483                json!({
22484                    "sequence": 7,
22485                    "condition_wait_id": "condition:7",
22486                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22487                    "condition_key": "update-approval",
22488                    "condition_definition_fingerprint": "sha256:update-approval-v1",
22489                }),
22490            ),
22491            history_event(
22492                "UpdateApplied",
22493                json!({
22494                    "sequence": 7,
22495                    "update_id": "update-1",
22496                    "update_name": "approve",
22497                    "arguments": fixture_envelope(json!([true])),
22498                }),
22499            ),
22500        ];
22501        let ctx = workflow_context(update_history);
22502        let predicate_ctx = ctx.clone();
22503        let mut wait = Box::pin(ctx.wait_condition(
22504            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
22505            move || {
22506                Ok(predicate_ctx
22507                    .updates("approve")?
22508                    .first()
22509                    .and_then(|arguments| arguments.first())
22510                    .and_then(Value::as_bool)
22511                    == Some(true))
22512            },
22513        ));
22514        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22515        assert!(matches!(
22516            wait.as_mut().poll(&mut task_context),
22517            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22518        ));
22519        assert!(ctx.take_commands().expect("commands").is_empty());
22520        ctx.ensure_history_consumed().expect("condition consumed");
22521    }
22522
22523    #[test]
22524    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
22525        let open_history = vec![
22526            history_event(
22527                "ConditionWaitOpened",
22528                json!({
22529                    "sequence": 3,
22530                    "condition_wait_id": "condition:3",
22531                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22532                    "condition_key": "two-votes",
22533                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22534                    "timeout_seconds": 120,
22535                }),
22536            ),
22537            history_event(
22538                "SignalReceived",
22539                json!({
22540                    "workflow_sequence": 3,
22541                    "signal_name": "vote",
22542                    "arguments": fixture_envelope(json!(["first"])),
22543                }),
22544            ),
22545        ];
22546        for _worker_before_or_after_restart in 0..2 {
22547            let ctx = workflow_context(open_history.clone());
22548            let predicate_ctx = ctx.clone();
22549            let mut wait = Box::pin(
22550                ctx.wait_condition(
22551                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22552                        .timeout(Duration::from_secs(120)),
22553                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
22554                ),
22555            );
22556            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22557            assert!(matches!(
22558                wait.as_mut().poll(&mut task_context),
22559                Poll::Pending
22560            ));
22561            assert_eq!(
22562                ctx.take_commands().expect("reopened condition"),
22563                vec![json!({
22564                    "type": "open_condition_wait",
22565                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22566                    "condition_key": "two-votes",
22567                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22568                    "timeout_seconds": 120,
22569                })]
22570            );
22571        }
22572
22573        let satisfied_ctx = workflow_context(vec![
22574            history_event(
22575                "ConditionWaitOpened",
22576                json!({
22577                    "sequence": 5,
22578                    "condition_wait_id": "condition:5",
22579                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22580                    "condition_key": "approval",
22581                    "condition_definition_fingerprint": "sha256:approval-v1",
22582                }),
22583            ),
22584            history_event(
22585                "ConditionWaitSatisfied",
22586                json!({
22587                    "sequence": 5,
22588                    "condition_wait_id": "condition:5",
22589                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22590                    "condition_key": "approval",
22591                    "condition_definition_fingerprint": "sha256:approval-v1",
22592                }),
22593            ),
22594        ]);
22595        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
22596            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
22597            || Ok(false),
22598        ));
22599        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22600        assert!(matches!(
22601            satisfied.as_mut().poll(&mut task_context),
22602            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22603        ));
22604
22605        let timed_out_ctx = workflow_context(vec![
22606            history_event(
22607                "ConditionWaitOpened",
22608                json!({
22609                    "sequence": 8,
22610                    "condition_wait_id": "condition:8",
22611                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22612                    "condition_key": "approval-timeout",
22613                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
22614                    "timeout_seconds": 5,
22615                }),
22616            ),
22617            history_event(
22618                "TimerScheduled",
22619                json!({
22620                    "sequence": 9,
22621                    "timer_id": "condition-timer:9",
22622                    "timer_kind": "condition_timeout",
22623                    "condition_wait_id": "condition:8",
22624                    "delay_seconds": 5,
22625                }),
22626            ),
22627            history_event(
22628                "TimerFired",
22629                json!({
22630                    "sequence": 9,
22631                    "timer_id": "condition-timer:9",
22632                    "timer_kind": "condition_timeout",
22633                    "condition_wait_id": "condition:8",
22634                    "delay_seconds": 5,
22635                }),
22636            ),
22637        ]);
22638        let mut timed_out = Box::pin(
22639            timed_out_ctx.wait_condition(
22640                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
22641                    .timeout(Duration::from_secs(5)),
22642                || Ok(true),
22643            ),
22644        );
22645        assert!(matches!(
22646            timed_out.as_mut().poll(&mut task_context),
22647            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22648        ));
22649    }
22650
22651    #[test]
22652    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
22653        let ctx = workflow_context(reopened_selection_condition_history());
22654        {
22655            let state = ctx.state.lock().unwrap();
22656            assert!(matches!(
22657                selection_member_recorded_command(&state, 2),
22658                Some(RecordedCommand::ConditionWait {
22659                    sequence: 3,
22660                    result: None,
22661                    ..
22662                })
22663            ));
22664        }
22665        let mut selected = Box::pin(ctx.select_keyed(vec![
22666            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22667            (
22668                "votes",
22669                ParallelOperation::condition(
22670                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
22671                    || Ok(true),
22672                ),
22673            ),
22674        ]));
22675        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22676        assert!(selected.as_mut().poll(&mut task_context).is_pending());
22677        assert!(
22678            ctx.take_commands().unwrap().is_empty(),
22679            "true predicate must not reopen the recorded wait"
22680        );
22681        ctx.ensure_history_consumed()
22682            .expect("physical reopens are consumed while canonical selection is pending");
22683    }
22684
22685    #[test]
22686    fn reopened_selection_condition_replays_its_latest_physical_winner() {
22687        for (terminal_type, acknowledge_timeout) in [
22688            ("ConditionWaitSatisfied", false),
22689            ("ConditionWaitTimedOut", false),
22690            ("TimerFired", false),
22691            ("TimerFired", true),
22692        ] {
22693            let mut history = reopened_selection_condition_history();
22694            let original_identity = history[1].payload["condition_wait_id"].clone();
22695            let uses_timer = terminal_type == "TimerFired";
22696            let mut resolution_payload = history[3].payload.clone();
22697            if uses_timer {
22698                for event in &mut history[1..] {
22699                    event.payload["timeout_seconds"] = json!(3);
22700                }
22701                resolution_payload = history[3].payload.clone();
22702                resolution_payload["timer_kind"] = json!("condition_timeout");
22703                resolution_payload["timer_id"] = json!("condition-timeout-3");
22704                resolution_payload["delay_seconds"] = json!(3);
22705                history.push(history_event("TimerScheduled", resolution_payload.clone()));
22706            }
22707            let mut resolution = history_event(terminal_type, resolution_payload.clone());
22708            resolution
22709                .raw
22710                .insert("id".into(), json!("latest-condition-resolution"));
22711            history.push(resolution);
22712            history.push(history_event(
22713                "SelectionResolved",
22714                json!({
22715                    "selection_group_id": "select-calls:1:2",
22716                    "selection_group_base_sequence": 1,
22717                    "selection_group_size": 2,
22718                    "member_key": "votes",
22719                    "member_index": 1,
22720                    "member_base_sequence": 2,
22721                    "member_size": 1,
22722                    "operation_kind": "condition",
22723                    "operation_identity": original_identity,
22724                    "outcome": "completed",
22725                    "resolution_event_id": "latest-condition-resolution",
22726                    "resolution_event_type": terminal_type,
22727                }),
22728            ));
22729            if acknowledge_timeout {
22730                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
22731            }
22732            let ctx = workflow_context(history);
22733            let mut selected = Box::pin(ctx.select_keyed(vec![
22734                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22735                (
22736                    "votes",
22737                    ParallelOperation::condition(
22738                        if uses_timer {
22739                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22740                                .timeout(Duration::from_secs(3))
22741                        } else {
22742                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22743                        },
22744                        || Ok(true),
22745                    ),
22746                ),
22747            ]));
22748            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22749            match selected.as_mut().poll(&mut task_context) {
22750                Poll::Ready(Ok(result)) => {
22751                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
22752                    let expected = if terminal_type == "ConditionWaitSatisfied" {
22753                        ConditionWaitResult::Satisfied
22754                    } else {
22755                        ConditionWaitResult::TimedOut
22756                    };
22757                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
22758                }
22759                other => panic!("latest physical winner must replay: {other:?}"),
22760            }
22761            assert!(ctx.take_commands().unwrap().is_empty());
22762            ctx.ensure_history_consumed()
22763                .expect("winner history consumed");
22764        }
22765    }
22766
22767    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
22768        let fixture: Value = serde_json::from_str(include_str!(
22769            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
22770        ))
22771        .expect("grouped condition fixture");
22772        fixture["history"]
22773            .as_array()
22774            .unwrap()
22775            .iter()
22776            .map(|event| {
22777                let mut payload = event["payload"].clone();
22778                let index = payload["parallel_group_index"].as_u64().unwrap();
22779                payload["parallel_group_id"] = json!("select-calls:1:2");
22780                payload["parallel_group_mode"] = json!("select");
22781                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
22782                payload["selection_member_index"] = json!(index);
22783                payload["selection_member_base_sequence"] = json!(index + 1);
22784                payload["selection_member_size"] = json!(1);
22785                payload["selection_member_kind"] =
22786                    json!(if index == 0 { "timer" } else { "condition" });
22787                history_event(event["event_type"].as_str().unwrap(), payload)
22788            })
22789            .collect()
22790    }
22791
22792    #[test]
22793    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
22794        let fixture: Value = serde_json::from_str(include_str!(
22795            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
22796        ))
22797        .expect("grouped condition fixture");
22798        let original = fixture["history"].as_array().expect("fixture history");
22799        let decode = |events: &[Value]| {
22800            let history = events
22801                .iter()
22802                .map(|event| {
22803                    history_event(
22804                        event["event_type"].as_str().unwrap(),
22805                        event["payload"].clone(),
22806                    )
22807                })
22808                .collect::<Vec<_>>();
22809            recorded_commands(
22810                &history,
22811                DEFAULT_CODEC,
22812                WorkflowIdentity {
22813                    workflow_id: None,
22814                    run_id: None,
22815                },
22816            )
22817        };
22818        assert!(decode(original).is_ok());
22819        for field in [
22820            "condition_wait_occurrence_id",
22821            "condition_key",
22822            "condition_definition_fingerprint",
22823            "timeout_seconds",
22824            "parallel_group_id",
22825            "parallel_group_size",
22826            "parallel_group_index",
22827        ] {
22828            let mut changed = original.clone();
22829            changed[3]["payload"][field] = match field {
22830                "timeout_seconds" | "parallel_group_size" => json!(30),
22831                "parallel_group_index" => json!(0),
22832                _ => json!("changed"),
22833            };
22834            assert!(
22835                decode(&changed).is_err(),
22836                "reopen must reject changed {field}"
22837            );
22838        }
22839        let mut unsettled = original.clone();
22840        unsettled.remove(2);
22841        assert!(
22842            decode(&unsettled).is_err(),
22843            "physical predecessor must be resolved"
22844        );
22845        let mut timed_out = original.clone();
22846        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
22847        assert!(decode(&timed_out).is_err(), "timeout is terminal");
22848        let mut late_resolution = original.clone();
22849        late_resolution.swap(2, 3);
22850        assert!(
22851            decode(&late_resolution).is_err(),
22852            "later history cannot authorize a reopen"
22853        );
22854    }
22855
22856    #[test]
22857    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
22858        let history = vec![
22859            history_event(
22860                "ConditionWaitOpened",
22861                json!({
22862                    "sequence": 3,
22863                    "condition_wait_id": "condition:3",
22864                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22865                    "condition_key": "two-votes",
22866                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22867                }),
22868            ),
22869            history_event(
22870                "SignalReceived",
22871                json!({
22872                    "workflow_sequence": 3,
22873                    "signal_name": "vote",
22874                    "arguments": fixture_envelope(json!(["first"])),
22875                }),
22876            ),
22877            history_event(
22878                "ConditionWaitSatisfied",
22879                json!({
22880                    "sequence": 3,
22881                    "condition_wait_id": "condition:3",
22882                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22883                    "condition_key": "two-votes",
22884                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22885                }),
22886            ),
22887            history_event(
22888                "ConditionWaitOpened",
22889                json!({
22890                    "sequence": 5,
22891                    "condition_wait_id": "condition:5",
22892                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22893                    "condition_key": "two-votes",
22894                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22895                }),
22896            ),
22897            history_event(
22898                "SignalReceived",
22899                json!({
22900                    "workflow_sequence": 5,
22901                    "signal_name": "vote",
22902                    "arguments": fixture_envelope(json!(["second"])),
22903                }),
22904            ),
22905            history_event(
22906                "ConditionWaitSatisfied",
22907                json!({
22908                    "sequence": 5,
22909                    "condition_wait_id": "condition:5",
22910                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22911                    "condition_key": "two-votes",
22912                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22913                }),
22914            ),
22915        ];
22916        for _cold_worker_or_restart in 0..2 {
22917            let ctx = workflow_context(history.clone());
22918            let predicate_ctx = ctx.clone();
22919            let mut wait = Box::pin(ctx.wait_condition(
22920                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
22921                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
22922            ));
22923            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22924
22925            assert!(matches!(
22926                wait.as_mut().poll(&mut task_context),
22927                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22928            ));
22929            assert!(ctx.take_commands().expect("commands").is_empty());
22930            ctx.ensure_history_consumed()
22931                .expect("every physical wait-open is consumed");
22932        }
22933    }
22934
22935    #[test]
22936    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
22937        let history = vec![
22938            history_event(
22939                "ConditionWaitOpened",
22940                json!({
22941                    "sequence": 3,
22942                    "condition_wait_id": "condition:3",
22943                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22944                    "condition_key": "approved",
22945                    "condition_definition_fingerprint": "sha256:approved-v1",
22946                }),
22947            ),
22948            history_event(
22949                "UpdateApplied",
22950                json!({
22951                    "sequence": 3,
22952                    "update_id": "update-1",
22953                    "update_name": "approve",
22954                    "arguments": fixture_envelope(json!([false])),
22955                }),
22956            ),
22957            history_event(
22958                "ConditionWaitOpened",
22959                json!({
22960                    "sequence": 5,
22961                    "condition_wait_id": "condition:5",
22962                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22963                    "condition_key": "approved",
22964                    "condition_definition_fingerprint": "sha256:approved-v1",
22965                }),
22966            ),
22967            history_event(
22968                "UpdateApplied",
22969                json!({
22970                    "sequence": 5,
22971                    "update_id": "update-2",
22972                    "update_name": "approve",
22973                    "arguments": fixture_envelope(json!([true])),
22974                }),
22975            ),
22976        ];
22977
22978        for _cold_worker_or_restart in 0..2 {
22979            let ctx = workflow_context(history.clone());
22980            let predicate_ctx = ctx.clone();
22981            let mut wait = Box::pin(ctx.wait_condition(
22982                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
22983                move || {
22984                    Ok(predicate_ctx
22985                        .updates("approve")?
22986                        .last()
22987                        .and_then(|arguments| arguments.first())
22988                        .and_then(Value::as_bool)
22989                        == Some(true))
22990                },
22991            ));
22992            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22993
22994            assert!(matches!(
22995                wait.as_mut().poll(&mut task_context),
22996                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22997            ));
22998            assert!(ctx.take_commands().expect("commands").is_empty());
22999            ctx.ensure_history_consumed()
23000                .expect("every update-driven reopen is consumed");
23001        }
23002    }
23003
23004    #[test]
23005    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
23006        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
23007            ("shared", "sha256:first", "shared", "sha256:second"),
23008            ("first", "sha256:shared", "second", "sha256:shared"),
23009            ("shared", "sha256:shared", "shared", "sha256:shared"),
23010            ("first", "sha256:first", "second", "sha256:second"),
23011        ] {
23012            let history = vec![
23013                history_event(
23014                    "ConditionWaitOpened",
23015                    json!({
23016                        "sequence": 3,
23017                        "condition_wait_id": "condition:3",
23018                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23019                        "condition_key": first_key,
23020                        "condition_definition_fingerprint": first_fingerprint,
23021                    }),
23022                ),
23023                history_event(
23024                    "ConditionWaitSatisfied",
23025                    json!({
23026                        "sequence": 3,
23027                        "condition_wait_id": "condition:3",
23028                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23029                        "condition_key": first_key,
23030                        "condition_definition_fingerprint": first_fingerprint,
23031                    }),
23032                ),
23033                history_event(
23034                    "ConditionWaitOpened",
23035                    json!({
23036                        "sequence": 4,
23037                        "condition_wait_id": "condition:4",
23038                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23039                        "condition_key": second_key,
23040                        "condition_definition_fingerprint": second_fingerprint,
23041                    }),
23042                ),
23043                history_event(
23044                    "ConditionWaitSatisfied",
23045                    json!({
23046                        "sequence": 4,
23047                        "condition_wait_id": "condition:4",
23048                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23049                        "condition_key": second_key,
23050                        "condition_definition_fingerprint": second_fingerprint,
23051                    }),
23052                ),
23053            ];
23054            for _cold_worker_or_restart in 0..2 {
23055                let ctx = workflow_context(history.clone());
23056                let mut task_context = TaskContext::from_waker(noop_waker_ref());
23057                let mut first = Box::pin(ctx.wait_condition(
23058                    ConditionWaitOptions::new(first_key, first_fingerprint),
23059                    || Ok(false),
23060                ));
23061                assert!(matches!(
23062                    first.as_mut().poll(&mut task_context),
23063                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23064                ));
23065
23066                let mut second = Box::pin(ctx.wait_condition(
23067                    ConditionWaitOptions::new(second_key, second_fingerprint),
23068                    || Ok(false),
23069                ));
23070                assert!(matches!(
23071                    second.as_mut().poll(&mut task_context),
23072                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23073                ));
23074                assert!(ctx.take_commands().expect("commands").is_empty());
23075                ctx.ensure_history_consumed()
23076                    .expect("each authored wait consumes one occurrence");
23077            }
23078        }
23079    }
23080
23081    #[test]
23082    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
23083        fn worker() -> Worker {
23084            let client = Client::new("http://127.0.0.1:8080").expect("client");
23085            let mut worker = Worker::new(client, "rust-workers");
23086            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
23087                let mut outcomes = Vec::new();
23088                for _ in 0..2 {
23089                    outcomes.push(
23090                        ctx.wait_condition(
23091                            ConditionWaitOptions::new("shared", "sha256:shared"),
23092                            || Ok(false),
23093                        )
23094                        .await?,
23095                    );
23096                }
23097                Ok(json!(outcomes))
23098            });
23099            worker
23100        }
23101
23102        let task = workflow_task(
23103            "rust.condition-loop",
23104            vec![
23105                history_event(
23106                    "ConditionWaitOpened",
23107                    json!({
23108                        "sequence": 1,
23109                        "condition_wait_id": "condition:1",
23110                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23111                        "condition_key": "shared",
23112                        "condition_definition_fingerprint": "sha256:shared",
23113                    }),
23114                ),
23115                history_event(
23116                    "ConditionWaitSatisfied",
23117                    json!({
23118                        "sequence": 1,
23119                        "condition_wait_id": "condition:1",
23120                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23121                        "condition_key": "shared",
23122                        "condition_definition_fingerprint": "sha256:shared",
23123                    }),
23124                ),
23125                history_event(
23126                    "ConditionWaitOpened",
23127                    json!({
23128                        "sequence": 2,
23129                        "condition_wait_id": "condition:2",
23130                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23131                        "condition_key": "shared",
23132                        "condition_definition_fingerprint": "sha256:shared",
23133                    }),
23134                ),
23135                history_event(
23136                    "ConditionWaitSatisfied",
23137                    json!({
23138                        "sequence": 2,
23139                        "condition_wait_id": "condition:2",
23140                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23141                        "condition_key": "shared",
23142                        "condition_definition_fingerprint": "sha256:shared",
23143                    }),
23144                ),
23145            ],
23146            DEFAULT_CODEC,
23147        );
23148
23149        for _cold_worker_or_restart in 0..2 {
23150            let commands = worker()
23151                .execute_workflow_task(task.clone())
23152                .expect("adjacent loop waits replay deterministically");
23153            assert_eq!(commands.len(), 1);
23154            assert_eq!(commands[0]["type"], "complete_workflow");
23155            assert_eq!(
23156                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23157                json!(["satisfied", "satisfied"])
23158            );
23159        }
23160    }
23161
23162    #[test]
23163    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
23164        let history = vec![history_event(
23165            "ConditionWaitOpened",
23166            json!({
23167                "sequence": 12,
23168                "condition_wait_id": "condition:12",
23169                "condition_wait_occurrence_id": "rust:condition-wait:0",
23170                "condition_key": "approval",
23171                "condition_definition_fingerprint": "sha256:approval-v1",
23172                "timeout_seconds": 30,
23173            }),
23174        )];
23175        for (options, expected_reason) in [
23176            (
23177                ConditionWaitOptions::new("changed", "sha256:approval-v1")
23178                    .timeout(Duration::from_secs(30)),
23179                "condition_wait_key_mismatch",
23180            ),
23181            (
23182                ConditionWaitOptions::new("approval", "sha256:approval-v2")
23183                    .timeout(Duration::from_secs(30)),
23184                "condition_wait_predicate_mismatch",
23185            ),
23186            (
23187                ConditionWaitOptions::new("approval", "sha256:approval-v1")
23188                    .timeout(Duration::from_secs(29)),
23189                "condition_wait_timeout_mismatch",
23190            ),
23191        ] {
23192            let ctx = workflow_context(history.clone());
23193            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
23194            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23195            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23196                wait.as_mut().poll(&mut task_context)
23197            else {
23198                panic!("changed condition definition must fail replay");
23199            };
23200            assert_eq!(failure.reason, expected_reason);
23201            assert_eq!(failure.sequence, Some(12));
23202        }
23203    }
23204
23205    #[test]
23206    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
23207        let error = WorkflowState::new(
23208            vec![history_event(
23209                "ConditionWaitOpened",
23210                json!({
23211                    "sequence": 12,
23212                    "condition_wait_id": "condition:12",
23213                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23214                    "condition_key": "approval",
23215                }),
23216            )],
23217            "rust-workers".to_string(),
23218            DEFAULT_CODEC.to_string(),
23219            None,
23220        )
23221        .expect_err("condition history without a predicate fingerprint must fail");
23222
23223        assert!(matches!(
23224            error,
23225            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23226                if reason == "condition_wait_predicate_fingerprint_missing"
23227        ));
23228    }
23229
23230    #[test]
23231    fn condition_wait_history_requires_authored_occurrence_identity() {
23232        let error = WorkflowState::new(
23233            vec![history_event(
23234                "ConditionWaitOpened",
23235                json!({
23236                    "sequence": 12,
23237                    "condition_wait_id": "condition:12",
23238                    "condition_key": "approval",
23239                    "condition_definition_fingerprint": "sha256:approval-v1",
23240                }),
23241            )],
23242            "rust-workers".to_string(),
23243            DEFAULT_CODEC.to_string(),
23244            None,
23245        )
23246        .expect_err("condition history without occurrence identity must fail");
23247
23248        assert!(matches!(
23249            error,
23250            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23251                if reason == "condition_wait_occurrence_id_missing"
23252        ));
23253    }
23254
23255    #[test]
23256    fn typed_search_attribute_updates_validate_emit_and_replay() {
23257        let update = SearchAttributeUpdate::new()
23258            .keyword("OrderStatus", " waiting ")
23259            .expect("keyword")
23260            .int("Attempt", 3)
23261            .expect("int")
23262            .bool("Escalated", false)
23263            .expect("bool")
23264            .keyword_list("Regions", ["us-east", "eu-west"])
23265            .expect("list")
23266            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
23267            .expect("datetime")
23268            .delete("LegacyStatus")
23269            .expect("delete");
23270        let ctx = workflow_context(Vec::new());
23271        ctx.upsert_search_attributes(update.clone())
23272            .expect("typed update");
23273        assert_eq!(
23274            ctx.take_commands().expect("search-attribute command"),
23275            vec![json!({
23276                "type": "upsert_search_attributes",
23277                "attributes": {
23278                    "Attempt": 3,
23279                    "Escalated": false,
23280                    "LegacyStatus": null,
23281                    "OrderStatus": "waiting",
23282                    "Regions": ["us-east", "eu-west"],
23283                    "UpdatedAt": "2026-08-22T04:00:00Z",
23284                },
23285                "attribute_types": {
23286                    "Attempt": "int",
23287                    "Escalated": "bool",
23288                    "OrderStatus": "keyword",
23289                    "Regions": "keyword_list",
23290                    "UpdatedAt": "datetime",
23291                },
23292            })]
23293        );
23294
23295        let replay = workflow_context(vec![history_event(
23296            "SearchAttributesUpserted",
23297            json!({
23298                "sequence": 6,
23299                "attributes": {
23300                    "Attempt": 3,
23301                    "Escalated": false,
23302                    "LegacyStatus": null,
23303                    "OrderStatus": "waiting",
23304                    "Regions": ["us-east", "eu-west"],
23305                    "UpdatedAt": "2026-08-22T04:00:00Z",
23306                },
23307                "attribute_types": {
23308                    "Attempt": "int",
23309                    "Escalated": "bool",
23310                    "OrderStatus": "keyword",
23311                    "Regions": "keyword_list",
23312                    "UpdatedAt": "datetime",
23313                },
23314                "merged": {},
23315            }),
23316        )]);
23317        replay
23318            .upsert_search_attributes(update)
23319            .expect("matching update replays");
23320        assert!(replay.take_commands().expect("commands").is_empty());
23321        replay.ensure_history_consumed().expect("history consumed");
23322
23323        let type_drift = workflow_context(vec![history_event(
23324            "SearchAttributesUpserted",
23325            json!({
23326                "sequence": 7,
23327                "attributes": {"OrderStatus": "waiting"},
23328                "attribute_types": {"OrderStatus": "keyword"},
23329                "merged": {"OrderStatus": "waiting"},
23330            }),
23331        )]);
23332        let error = type_drift
23333            .upsert_search_attributes(
23334                SearchAttributeUpdate::new()
23335                    .string("OrderStatus", "waiting")
23336                    .expect("string update"),
23337            )
23338            .expect_err("same JSON value with a changed type must fail replay");
23339        assert!(matches!(
23340            error,
23341            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23342                if reason == "search_attribute_type_mismatch"
23343        ));
23344
23345        let malformed_types = WorkflowState::new(
23346            vec![history_event(
23347                "SearchAttributesUpserted",
23348                json!({
23349                    "sequence": 8,
23350                    "attributes": {"OrderStatus": "waiting"},
23351                    "attribute_types": {"OrderStatus": "unsupported"},
23352                    "merged": {"OrderStatus": "waiting"},
23353                }),
23354            )],
23355            "rust-workers".to_string(),
23356            DEFAULT_CODEC.to_string(),
23357            None,
23358        )
23359        .expect_err("unsupported search-attribute type metadata must fail");
23360        assert!(matches!(
23361            malformed_types,
23362            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23363                if reason == "search_attribute_types_malformed"
23364        ));
23365
23366        assert!(matches!(
23367            SearchAttributeUpdate::new().keyword("bad key", "value"),
23368            Err(SearchAttributeUpdateError::InvalidKey(_))
23369        ));
23370        assert!(matches!(
23371            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
23372            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
23373        ));
23374        assert!(matches!(
23375            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
23376            Err(SearchAttributeUpdateError::ValueTooLong { .. })
23377        ));
23378        assert!(matches!(
23379            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
23380            Err(SearchAttributeUpdateError::InvalidDateTime(_))
23381        ));
23382        assert!(matches!(
23383            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
23384            Err(Error::InvalidSearchAttributeUpdate(
23385                SearchAttributeUpdateError::Empty
23386            ))
23387        ));
23388    }
23389
23390    #[test]
23391    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
23392        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
23393        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
23394
23395        assert!(SearchAttributeUpdate::new()
23396            .string("AsciiDescription", ascii)
23397            .is_ok());
23398        assert!(SearchAttributeUpdate::new()
23399            .string("Utf8Description", utf8)
23400            .is_ok());
23401        assert!(matches!(
23402            SearchAttributeUpdate::new().string(
23403                "TooLongDescription",
23404                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
23405            ),
23406            Err(SearchAttributeUpdateError::ValueTooLong {
23407                kind: "string",
23408                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
23409                ..
23410            })
23411        ));
23412    }
23413
23414    #[test]
23415    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
23416        let lone_fire = WorkflowState::new(
23417            vec![history_event(
23418                "TimerFired",
23419                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23420            )],
23421            "rust-workers".to_string(),
23422            DEFAULT_CODEC.to_string(),
23423            None,
23424        )
23425        .expect_err("TimerFired requires TimerScheduled");
23426        assert!(matches!(
23427            lone_fire,
23428            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23429                if reason == "timer_schedule_missing_or_duplicate"
23430        ));
23431
23432        let wrong_identity = WorkflowState::new(
23433            vec![
23434                history_event(
23435                    "TimerScheduled",
23436                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23437                ),
23438                history_event(
23439                    "TimerFired",
23440                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23441                ),
23442            ],
23443            "rust-workers".to_string(),
23444            DEFAULT_CODEC.to_string(),
23445            None,
23446        )
23447        .expect_err("fire must match scheduled timer identity");
23448        assert!(matches!(
23449            wrong_identity,
23450            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23451                if reason == "timer_identity_mismatch"
23452        ));
23453
23454        let duplicate_fire = WorkflowState::new(
23455            vec![
23456                history_event(
23457                    "TimerScheduled",
23458                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23459                ),
23460                history_event(
23461                    "TimerFired",
23462                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23463                ),
23464                history_event(
23465                    "TimerFired",
23466                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23467                ),
23468            ],
23469            "rust-workers".to_string(),
23470            DEFAULT_CODEC.to_string(),
23471            None,
23472        )
23473        .expect_err("a durable timer cannot fire twice");
23474        assert!(matches!(
23475            duplicate_fire,
23476            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23477                if reason == "duplicate_timer_fire"
23478        ));
23479
23480        let wrong_fired_delay = WorkflowState::new(
23481            vec![
23482                history_event(
23483                    "TimerScheduled",
23484                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23485                ),
23486                history_event(
23487                    "TimerFired",
23488                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
23489                ),
23490            ],
23491            "rust-workers".to_string(),
23492            DEFAULT_CODEC.to_string(),
23493            None,
23494        )
23495        .expect_err("timer schedule and fire delays must agree");
23496        assert!(matches!(
23497            wrong_fired_delay,
23498            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23499                if reason == "timer_history_delay_mismatch"
23500        ));
23501    }
23502
23503    #[test]
23504    fn replay_rejects_activity_moved_before_recorded_timer() {
23505        let ctx = workflow_context(vec![
23506            history_event(
23507                "TimerScheduled",
23508                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23509            ),
23510            history_event(
23511                "TimerFired",
23512                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23513            ),
23514            history_event(
23515                "ActivityCompleted",
23516                json!({
23517                    "sequence": 2,
23518                    "activity_type": "after-timer",
23519                    "payload_codec": DEFAULT_CODEC,
23520                    "result": fixture_envelope(json!("done")),
23521                }),
23522            ),
23523        ]);
23524        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
23525        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23526
23527        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23528            activity.as_mut().poll(&mut task_context)
23529        else {
23530            panic!("reordered durable command must be rejected");
23531        };
23532        assert_eq!(failure.reason, "recorded_command_mismatch");
23533        assert_eq!(failure.sequence, Some(1));
23534        assert_eq!(failure.expected.as_deref(), Some("timer"));
23535        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
23536    }
23537
23538    #[test]
23539    fn workflow_context_emits_a_typed_named_signal_wait() {
23540        let ctx = workflow_context(Vec::new());
23541        let mut signal = Box::pin(ctx.wait_signal("finish"));
23542        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23543
23544        assert!(matches!(
23545            signal.as_mut().poll(&mut task_context),
23546            Poll::Pending
23547        ));
23548        assert_eq!(
23549            ctx.take_commands().expect("signal-wait command"),
23550            vec![json!({
23551                "type": "open_signal_wait",
23552                "signal_name": "finish",
23553            })]
23554        );
23555    }
23556
23557    #[test]
23558    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
23559        let ctx = workflow_context(Vec::new());
23560        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
23561        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23562
23563        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
23564        else {
23565            panic!("runtime-reserved signal should be rejected");
23566        };
23567        assert!(message.contains("reserved by the workflow runtime"));
23568        assert!(ctx.take_commands().expect("commands").is_empty());
23569    }
23570
23571    #[tokio::test]
23572    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
23573        let client = Client::builder("http://127.0.0.1:9")
23574            .build()
23575            .expect("client");
23576        let error = client
23577            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
23578            .await
23579            .expect_err("runtime-reserved signal should be rejected before transport");
23580
23581        assert!(
23582            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
23583        );
23584    }
23585
23586    #[test]
23587    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
23588        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23589            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23590                value.to_string(),
23591            )]))
23592            .expect("message payload");
23593            json!({
23594                "schema": MESSAGE_STREAM_SCHEMA,
23595                "stream_name": "orders",
23596                "message_id": message_id,
23597                "position": position,
23598                "payload_envelope": payload,
23599            })
23600        }
23601
23602        fn opened(sequence: u64) -> HistoryEvent {
23603            history_event(
23604                "SignalWaitOpened",
23605                json!({
23606                    "sequence": sequence,
23607                    "signal_name": MESSAGE_STREAM_SIGNAL,
23608                }),
23609            )
23610        }
23611
23612        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23613            history_event(
23614                "SignalApplied",
23615                json!({
23616                    "sequence": sequence,
23617                    "signal_name": MESSAGE_STREAM_SIGNAL,
23618                    "value": fixture_envelope(json!([delivery])),
23619                }),
23620            )
23621        }
23622
23623        fn received(delivery: Value) -> HistoryEvent {
23624            history_event(
23625                "SignalReceived",
23626                json!({
23627                    "signal_name": MESSAGE_STREAM_SIGNAL,
23628                    "arguments": fixture_envelope(json!([delivery])),
23629                    "payload_codec": DEFAULT_CODEC,
23630                }),
23631            )
23632        }
23633
23634        let client = Client::new("http://127.0.0.1:8080").expect("client");
23635        let mut worker = Worker::new(client, "rust-workers");
23636        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
23637            let messages = ctx.message_stream("orders")?.receive(2).await?;
23638            Ok(json!(messages
23639                .into_iter()
23640                .map(|message| message.message_id)
23641                .collect::<Vec<_>>()))
23642        });
23643
23644        let first = delivery("message-1", 1, "one");
23645        let second = delivery("message-2", 2, "two");
23646        let batch = worker
23647            .execute_workflow_task_decision(workflow_task(
23648                "rust.message-stream-batch",
23649                vec![
23650                    opened(1),
23651                    received(first.clone()),
23652                    applied(1, first.clone()),
23653                    received(first.clone()),
23654                    received(second),
23655                ],
23656                DEFAULT_CODEC,
23657            ))
23658            .expect("worker task consumes the available batch");
23659
23660        assert_eq!(batch.commands.len(), 1);
23661        assert_eq!(batch.commands[0]["type"], "complete_workflow");
23662        assert_eq!(
23663            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
23664                .expect("workflow result"),
23665            json!(["message-1", "message-2"])
23666        );
23667        assert_eq!(
23668            batch.message_stream_cursors,
23669            vec![json!({"stream_name": "orders", "through_position": 2})]
23670        );
23671        assert!(batch.message_stream_waits.is_empty());
23672
23673        let partial = worker
23674            .execute_workflow_task_decision(workflow_task(
23675                "rust.message-stream-batch",
23676                vec![opened(1), received(first.clone()), applied(1, first)],
23677                DEFAULT_CODEC,
23678            ))
23679            .expect("worker task returns without waiting for a missing second item");
23680        assert_eq!(partial.commands.len(), 1);
23681        assert_eq!(partial.commands[0]["type"], "complete_workflow");
23682        assert_eq!(
23683            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
23684                .expect("workflow result"),
23685            json!(["message-1"])
23686        );
23687        assert_eq!(
23688            partial.message_stream_cursors,
23689            vec![json!({"stream_name": "orders", "through_position": 1})]
23690        );
23691        assert!(partial.message_stream_waits.is_empty());
23692    }
23693
23694    #[test]
23695    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
23696        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23697            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23698                value.to_string(),
23699            )]))
23700            .expect("message payload");
23701            json!({
23702                "schema": MESSAGE_STREAM_SCHEMA,
23703                "stream_name": "orders",
23704                "message_id": message_id,
23705                "position": position,
23706                "payload_envelope": payload,
23707            })
23708        }
23709
23710        fn opened(sequence: u64) -> HistoryEvent {
23711            history_event(
23712                "SignalWaitOpened",
23713                json!({
23714                    "sequence": sequence,
23715                    "signal_name": MESSAGE_STREAM_SIGNAL,
23716                }),
23717            )
23718        }
23719
23720        fn received(delivery: Value) -> HistoryEvent {
23721            history_event(
23722                "SignalReceived",
23723                json!({
23724                    "signal_name": MESSAGE_STREAM_SIGNAL,
23725                    "arguments": fixture_envelope(json!([delivery])),
23726                    "payload_codec": DEFAULT_CODEC,
23727                }),
23728            )
23729        }
23730
23731        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23732            history_event(
23733                "SignalApplied",
23734                json!({
23735                    "sequence": sequence,
23736                    "signal_name": MESSAGE_STREAM_SIGNAL,
23737                    "value": fixture_envelope(json!([delivery])),
23738                }),
23739            )
23740        }
23741
23742        let client = Client::new("http://127.0.0.1:8080").expect("client");
23743        let mut worker = Worker::new(client, "rust-workers");
23744        worker.register_workflow(
23745            "rust.message-stream-partial-batches",
23746            |ctx, _input| async move {
23747                let stream = ctx.message_stream("orders")?;
23748                let first = stream.receive(10).await?;
23749                let second = stream.receive(10).await?;
23750                Ok(json!([
23751                    first
23752                        .into_iter()
23753                        .map(|message| message.message_id)
23754                        .collect::<Vec<_>>(),
23755                    second
23756                        .into_iter()
23757                        .map(|message| message.message_id)
23758                        .collect::<Vec<_>>(),
23759                ]))
23760            },
23761        );
23762
23763        let first = delivery("message-1", 1, "one");
23764        let second = delivery("message-2", 2, "two");
23765        let decision = worker
23766            .execute_workflow_task_decision(workflow_task(
23767                "rust.message-stream-partial-batches",
23768                vec![
23769                    opened(1),
23770                    received(first.clone()),
23771                    applied(1, first),
23772                    opened(2),
23773                    received(second.clone()),
23774                    applied(2, second),
23775                ],
23776                DEFAULT_CODEC,
23777            ))
23778            .expect("cold replay preserves both authored receive boundaries");
23779
23780        assert_eq!(decision.commands.len(), 1);
23781        assert_eq!(decision.commands[0]["type"], "complete_workflow");
23782        assert_eq!(
23783            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
23784                .expect("workflow result"),
23785            json!([["message-1"], ["message-2"]])
23786        );
23787        assert_eq!(
23788            decision.message_stream_cursors,
23789            vec![json!({"stream_name": "orders", "through_position": 2})]
23790        );
23791        assert!(decision.message_stream_waits.is_empty());
23792    }
23793
23794    #[test]
23795    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
23796        let ctx = workflow_context(Vec::new());
23797        let stream = ctx.message_stream("orders").expect("message stream");
23798        let mut receive = Box::pin(stream.receive(10));
23799        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23800
23801        assert!(matches!(
23802            receive.as_mut().poll(&mut task_context),
23803            Poll::Pending
23804        ));
23805        assert_eq!(
23806            ctx.take_commands().expect("message-stream wait command"),
23807            vec![json!({
23808                "type": "open_signal_wait",
23809                "signal_name": MESSAGE_STREAM_SIGNAL,
23810            })]
23811        );
23812        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
23813        assert!(cursors.is_empty());
23814        assert_eq!(
23815            waits,
23816            vec![json!({"stream_name": "orders", "after_position": 0})]
23817        );
23818    }
23819
23820    #[test]
23821    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
23822        let ctx = workflow_context(vec![history_event(
23823            "SignalReceived",
23824            json!({
23825                "signal_name": MESSAGE_STREAM_SIGNAL,
23826                "arguments": fixture_envelope(json!([{
23827                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
23828                    "stream_name": "orders",
23829                    "through_position": 2,
23830                }])),
23831                "payload_codec": DEFAULT_CODEC,
23832            }),
23833        )]);
23834        let stream = ctx.message_stream("orders").expect("message stream");
23835        let mut receive = Box::pin(stream.receive(10));
23836        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23837
23838        assert!(matches!(
23839            receive.as_mut().poll(&mut task_context),
23840            Poll::Pending
23841        ));
23842        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
23843        assert_eq!(
23844            cursors,
23845            vec![json!({"stream_name": "orders", "through_position": 2})]
23846        );
23847        assert_eq!(
23848            waits,
23849            vec![json!({"stream_name": "orders", "after_position": 2})]
23850        );
23851    }
23852
23853    #[test]
23854    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
23855        let mut empty_map = BTreeMap::new();
23856        let mut nested = BTreeMap::new();
23857        nested.insert(
23858            "value".to_string(),
23859            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
23860        );
23861        let values = vec![
23862            AvroValue::Bytes(vec![0, 255]),
23863            AvroValue::Long(1),
23864            AvroValue::Double(1.0),
23865            AvroValue::Array(Vec::new()),
23866            AvroValue::Map(std::mem::take(&mut empty_map)),
23867            AvroValue::Map(nested),
23868        ];
23869        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
23870        let transport = vec![json!({
23871            "schema": MESSAGE_STREAM_SCHEMA,
23872            "stream_name": "orders",
23873            "message_id": "message-1",
23874            "position": 1,
23875            "payload_envelope": payload,
23876        })];
23877
23878        for _ in 0..2 {
23879            let Some(MessageStreamDelivery::Message(message)) =
23880                decode_message_stream_delivery(transport.clone()).expect("delivery")
23881            else {
23882                panic!("message delivery expected");
23883            };
23884            assert_eq!(message.arguments, values);
23885            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
23886            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
23887        }
23888    }
23889
23890    #[test]
23891    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
23892        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23893            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23894                value.to_string(),
23895            )]))
23896            .expect("message payload");
23897            json!({
23898                "schema": MESSAGE_STREAM_SCHEMA,
23899                "stream_name": "orders",
23900                "message_id": message_id,
23901                "position": position,
23902                "payload_envelope": payload,
23903            })
23904        }
23905
23906        fn opened(sequence: u64) -> HistoryEvent {
23907            history_event(
23908                "SignalWaitOpened",
23909                json!({
23910                    "sequence": sequence,
23911                    "signal_name": MESSAGE_STREAM_SIGNAL,
23912                }),
23913            )
23914        }
23915
23916        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23917            history_event(
23918                "SignalApplied",
23919                json!({
23920                    "sequence": sequence,
23921                    "signal_name": MESSAGE_STREAM_SIGNAL,
23922                    "value": fixture_envelope(json!([delivery])),
23923                }),
23924            )
23925        }
23926
23927        fn worker() -> Worker {
23928            let client = Client::new("http://127.0.0.1:8080").expect("client");
23929            let mut worker = Worker::new(client, "rust-workers");
23930            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
23931                let stream = ctx.message_stream("orders")?;
23932                let first = stream.receive_one().await?;
23933                let second = stream.receive_one().await?;
23934                Ok(json!([first.message_id, second.message_id]))
23935            });
23936            worker
23937        }
23938
23939        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
23940            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
23941            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
23942            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
23943            task
23944        }
23945
23946        let waiting = worker()
23947            .execute_workflow_task_decision(workflow_task(
23948                "rust.message-stream",
23949                Vec::new(),
23950                DEFAULT_CODEC,
23951            ))
23952            .expect("first worker opens the stream wait");
23953        assert_eq!(
23954            waiting.commands,
23955            vec![json!({
23956                "type": "open_signal_wait",
23957                "signal_name": MESSAGE_STREAM_SIGNAL,
23958            })]
23959        );
23960        assert!(waiting.message_stream_cursors.is_empty());
23961        assert_eq!(
23962            waiting.message_stream_waits,
23963            vec![json!({"stream_name": "orders", "after_position": 0})]
23964        );
23965
23966        let first_delivery = delivery("message-1", 1, "one");
23967        let first_arrival = worker()
23968            .execute_workflow_task_decision(task_with_resume(
23969                vec![opened(1)],
23970                first_delivery.clone(),
23971            ))
23972            .expect("replacement worker consumes the first arrival");
23973        assert_eq!(
23974            first_arrival.commands,
23975            vec![json!({
23976                "type": "open_signal_wait",
23977                "signal_name": MESSAGE_STREAM_SIGNAL,
23978            })]
23979        );
23980        assert_eq!(
23981            first_arrival.message_stream_cursors,
23982            vec![json!({"stream_name": "orders", "through_position": 1})]
23983        );
23984        assert_eq!(
23985            first_arrival.message_stream_waits,
23986            vec![json!({"stream_name": "orders", "after_position": 1})]
23987        );
23988
23989        let second_delivery = delivery("message-2", 2, "two");
23990        let first_applied = applied(1, first_delivery);
23991        let completed = worker()
23992            .execute_workflow_task_decision(task_with_resume(
23993                vec![opened(1), first_applied.clone(), opened(2)],
23994                second_delivery.clone(),
23995            ))
23996            .expect("next replacement worker consumes the second arrival");
23997        assert_eq!(completed.commands.len(), 1);
23998        assert_eq!(completed.commands[0]["type"], "complete_workflow");
23999        assert_eq!(
24000            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
24001                .expect("workflow result"),
24002            json!(["message-1", "message-2"])
24003        );
24004        assert_eq!(
24005            completed.message_stream_cursors,
24006            vec![json!({"stream_name": "orders", "through_position": 2})]
24007        );
24008        assert!(completed.message_stream_waits.is_empty());
24009
24010        let replay_history = vec![
24011            opened(1),
24012            first_applied,
24013            opened(2),
24014            applied(2, second_delivery),
24015        ];
24016        for _cold_worker_or_restart in 0..2 {
24017            let replayed = worker()
24018                .execute_workflow_task_decision(workflow_task(
24019                    "rust.message-stream",
24020                    replay_history.clone(),
24021                    DEFAULT_CODEC,
24022                ))
24023                .expect("cold worker replays each logical message exactly once");
24024            assert_eq!(replayed.commands.len(), 1);
24025            assert_eq!(
24026                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
24027                    .expect("replayed workflow result"),
24028                json!(["message-1", "message-2"])
24029            );
24030            assert_eq!(
24031                replayed.message_stream_cursors,
24032                vec![json!({"stream_name": "orders", "through_position": 2})]
24033            );
24034            assert!(replayed.message_stream_waits.is_empty());
24035        }
24036    }
24037
24038    #[test]
24039    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
24040        assert!(!worker_protocol_supports_message_streams("1.14"));
24041        assert!(worker_protocol_supports_message_streams("1.15"));
24042        assert!(worker_protocol_supports_message_streams("1.16"));
24043        assert!(worker_protocol_supports_message_streams(
24044            WORKER_PROTOCOL_VERSION
24045        ));
24046        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
24047    }
24048
24049    #[test]
24050    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
24051        let ctx = workflow_context(vec![
24052            history_event(
24053                "ConditionWaitOpened",
24054                json!({
24055                    "sequence": 1,
24056                    "condition_wait_id": "condition:1",
24057                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24058                    "condition_key": "signal:finish",
24059                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24060                }),
24061            ),
24062            history_event(
24063                "ConditionWaitSatisfied",
24064                json!({
24065                    "sequence": 1,
24066                    "condition_wait_id": "condition:1",
24067                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24068                    "condition_key": "signal:finish",
24069                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24070                }),
24071            ),
24072            history_event(
24073                "SignalReceived",
24074                json!({"signal_name": "finish", "arguments": []}),
24075            ),
24076        ]);
24077        let mut signal = Box::pin(ctx.wait_signal("finish"));
24078        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24079
24080        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24081            signal.as_mut().poll(&mut task_context)
24082        else {
24083            panic!("condition history must not resolve as a typed signal wait");
24084        };
24085        assert_eq!(failure.reason, "recorded_command_mismatch");
24086        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
24087    }
24088
24089    #[test]
24090    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
24091        let signal_then_timer = vec![
24092            history_event(
24093                "SignalWaitOpened",
24094                json!({"sequence": 1, "signal_name": "go"}),
24095            ),
24096            history_event(
24097                "SignalApplied",
24098                json!({
24099                    "sequence": 1,
24100                    "signal_name": "go",
24101                    "value": fixture_envelope(json!(["now"])),
24102                }),
24103            ),
24104            history_event(
24105                "TimerScheduled",
24106                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24107            ),
24108            history_event(
24109                "TimerFired",
24110                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24111            ),
24112        ];
24113
24114        let ctx = workflow_context(signal_then_timer.clone());
24115        let mut signal = Box::pin(ctx.wait_signal("go"));
24116        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24117        assert!(matches!(
24118            signal.as_mut().poll(&mut task_context),
24119            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
24120        ));
24121        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
24122        assert!(matches!(
24123            timer.as_mut().poll(&mut task_context),
24124            Poll::Ready(Ok(()))
24125        ));
24126        ctx.ensure_history_consumed()
24127            .expect("signal and timer history consumed in order");
24128
24129        let reordered = workflow_context(signal_then_timer);
24130        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
24131        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24132            timer_first.as_mut().poll(&mut task_context)
24133        else {
24134            panic!("timer cannot consume signal-wait-first history");
24135        };
24136        assert_eq!(failure.reason, "recorded_command_mismatch");
24137        assert_eq!(failure.sequence, Some(1));
24138        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
24139
24140        let timer_then_signal = vec![
24141            history_event(
24142                "TimerScheduled",
24143                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24144            ),
24145            history_event(
24146                "TimerFired",
24147                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24148            ),
24149            history_event(
24150                "SignalWaitOpened",
24151                json!({"sequence": 2, "signal_name": "go"}),
24152            ),
24153            history_event(
24154                "SignalApplied",
24155                json!({
24156                    "sequence": 2,
24157                    "signal_name": "go",
24158                    "value": fixture_envelope(json!([])),
24159                }),
24160            ),
24161        ];
24162        let reordered = workflow_context(timer_then_signal);
24163        let mut signal_first = Box::pin(reordered.wait_signal("go"));
24164        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24165            signal_first.as_mut().poll(&mut task_context)
24166        else {
24167            panic!("signal wait cannot consume timer-first history");
24168        };
24169        assert_eq!(failure.reason, "recorded_command_mismatch");
24170        assert_eq!(failure.sequence, Some(1));
24171        assert_eq!(failure.expected.as_deref(), Some("timer"));
24172    }
24173
24174    #[test]
24175    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
24176        let duplicate_timer = WorkflowState::new(
24177            vec![
24178                history_event(
24179                    "TimerScheduled",
24180                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24181                ),
24182                history_event(
24183                    "TimerScheduled",
24184                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24185                ),
24186            ],
24187            "rust-workers".to_string(),
24188            DEFAULT_CODEC.to_string(),
24189            None,
24190        )
24191        .expect_err("one workflow sequence cannot schedule two timers");
24192        assert!(matches!(
24193            duplicate_timer,
24194            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24195                if reason == "timer_schedule_missing_or_duplicate"
24196        ));
24197
24198        let colliding_kinds = WorkflowState::new(
24199            vec![
24200                history_event(
24201                    "TimerScheduled",
24202                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24203                ),
24204                history_event(
24205                    "ActivityCompleted",
24206                    json!({"sequence": 1, "activity_type": "same-sequence"}),
24207                ),
24208            ],
24209            "rust-workers".to_string(),
24210            DEFAULT_CODEC.to_string(),
24211            None,
24212        )
24213        .expect_err("one workflow sequence cannot identify two command kinds");
24214        assert!(matches!(
24215            colliding_kinds,
24216            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24217                if reason == "durable_command_sequence_collision"
24218        ));
24219
24220        let duplicate_signal_wait = WorkflowState::new(
24221            vec![
24222                history_event(
24223                    "SignalWaitOpened",
24224                    json!({"sequence": 1, "signal_name": "go"}),
24225                ),
24226                history_event(
24227                    "SignalWaitOpened",
24228                    json!({"sequence": 1, "signal_name": "go"}),
24229                ),
24230            ],
24231            "rust-workers".to_string(),
24232            DEFAULT_CODEC.to_string(),
24233            None,
24234        )
24235        .expect_err("one workflow sequence cannot open two signal waits");
24236        assert!(matches!(
24237            duplicate_signal_wait,
24238            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24239                if reason == "signal_wait_open_missing_or_duplicate"
24240        ));
24241    }
24242
24243    #[test]
24244    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
24245        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
24246            .expect("side-effect result");
24247        let ctx = workflow_context(vec![history_event(
24248            "SideEffectRecorded",
24249            json!({"sequence": 99, "result": result}),
24250        )]);
24251
24252        let replayed: Value = ctx
24253            .side_effect(|| panic!("recorded side effect must not run"))
24254            .expect("positive global workflow sequence is valid");
24255        assert_eq!(replayed, json!({"captured": true}));
24256        ctx.ensure_history_consumed().expect("history consumed");
24257    }
24258
24259    #[test]
24260    fn workflow_history_rejects_zero_and_descending_command_sequences() {
24261        let result =
24262            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
24263        let zero = WorkflowState::new(
24264            vec![history_event(
24265                "SideEffectRecorded",
24266                json!({"sequence": 0, "result": result.clone()}),
24267            )],
24268            "rust-workers".to_string(),
24269            DEFAULT_CODEC.to_string(),
24270            None,
24271        )
24272        .expect_err("durable command sequences must be positive");
24273        assert!(matches!(
24274            zero,
24275            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24276                if reason == "durable_command_sequence_invalid"
24277        ));
24278
24279        let descending = WorkflowState::new(
24280            vec![
24281                history_event(
24282                    "SideEffectRecorded",
24283                    json!({"sequence": 3, "result": result}),
24284                ),
24285                history_event(
24286                    "VersionMarkerRecorded",
24287                    json!({
24288                        "sequence": 2,
24289                        "change_id": "descending-marker",
24290                        "version": 1,
24291                        "min_supported": 1,
24292                        "max_supported": 1,
24293                    }),
24294                ),
24295            ],
24296            "rust-workers".to_string(),
24297            DEFAULT_CODEC.to_string(),
24298            None,
24299        )
24300        .expect_err("new durable commands must remain strictly ordered");
24301        let Error::NonDeterministicReplay(failure) = descending else {
24302            panic!("expected typed replay failure");
24303        };
24304        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
24305        assert_eq!(failure.sequence, Some(2));
24306        assert_eq!(
24307            failure.expected.as_deref(),
24308            Some("workflow sequence greater than 3")
24309        );
24310        assert_eq!(failure.actual.as_deref(), Some("2"));
24311    }
24312
24313    #[test]
24314    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
24315        fn worker() -> Worker {
24316            let client = Client::new("http://127.0.0.1:8080").expect("client");
24317            let mut worker = Worker::new(client, "rust-workers");
24318            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
24319                ctx.wait_signal("finish").await?;
24320                let marker: String =
24321                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
24322                assert_eq!(marker, "after-finish");
24323                Ok(json!("finished"))
24324            });
24325            worker
24326        }
24327
24328        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
24329            .expect("side-effect result");
24330        let task = workflow_task(
24331            "rust.finish-after-gaps",
24332            vec![
24333                history_event(
24334                    "SignalWaitOpened",
24335                    json!({"sequence": 1, "signal_name": "finish"}),
24336                ),
24337                history_event(
24338                    "SignalReceived",
24339                    json!({
24340                        "signal_id": "increment-3",
24341                        "signal_name": "increment",
24342                        "workflow_sequence": 2,
24343                        "payload_codec": DEFAULT_CODEC,
24344                        "arguments": fixture_envelope(json!([3])),
24345                    }),
24346                ),
24347                history_event(
24348                    "SignalReceived",
24349                    json!({
24350                        "signal_id": "increment-5",
24351                        "signal_name": "increment",
24352                        "workflow_sequence": 3,
24353                        "payload_codec": DEFAULT_CODEC,
24354                        "arguments": fixture_envelope(json!([5])),
24355                    }),
24356                ),
24357                history_event(
24358                    "SignalReceived",
24359                    json!({
24360                        "signal_id": "finish",
24361                        "signal_name": "finish",
24362                        "workflow_sequence": 4,
24363                        "payload_codec": DEFAULT_CODEC,
24364                        "arguments": fixture_envelope(json!([])),
24365                    }),
24366                ),
24367                history_event(
24368                    "SignalApplied",
24369                    json!({
24370                        "sequence": 1,
24371                        "signal_id": "finish",
24372                        "signal_name": "finish",
24373                        "payload_codec": DEFAULT_CODEC,
24374                        "value": fixture_envelope(json!([])),
24375                    }),
24376                ),
24377                history_event(
24378                    "SideEffectRecorded",
24379                    json!({"sequence": 5, "result": marker}),
24380                ),
24381            ],
24382            DEFAULT_CODEC,
24383        );
24384
24385        for _original_or_cold_worker in 0..2 {
24386            let commands = worker()
24387                .execute_workflow_task(task.clone())
24388                .expect("signal gaps preserve deterministic replay");
24389            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
24390            assert_eq!(commands[0]["type"], "complete_workflow");
24391            assert_eq!(
24392                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24393                json!("finished")
24394            );
24395        }
24396    }
24397
24398    #[test]
24399    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
24400        let ctx = workflow_context(Vec::new());
24401        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
24402        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24403        assert!(matches!(
24404            sleep.as_mut().poll(&mut task_context),
24405            Poll::Ready(Err(Error::TimerDurationOverflow))
24406        ));
24407        assert!(ctx.take_commands().expect("commands").is_empty());
24408    }
24409
24410    #[test]
24411    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
24412        let entries = AvroValue::Map(BTreeMap::from([
24413            ("text".to_string(), AvroValue::String("same".to_string())),
24414            (
24415                "nested".to_string(),
24416                AvroValue::Map(BTreeMap::from([
24417                    ("beta".to_string(), AvroValue::Long(2)),
24418                    ("alpha".to_string(), AvroValue::Long(1)),
24419                ])),
24420            ),
24421            ("long".to_string(), AvroValue::Long(7)),
24422            ("double".to_string(), AvroValue::Double(7.0)),
24423            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
24424        ]));
24425        let ctx = workflow_context(Vec::new());
24426        ctx.upsert_memo(entries.clone()).expect("valid memo update");
24427        let commands = ctx.take_commands().expect("commands");
24428
24429        assert_eq!(commands.len(), 1);
24430        assert_eq!(commands[0]["type"], "upsert_memo");
24431        let server_entries = json!({
24432            "codec": "avro",
24433            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
24434        });
24435        assert_eq!(
24436            commands[0]["entries"]
24437                .as_object()
24438                .expect("entries envelope")
24439                .keys()
24440                .collect::<Vec<_>>(),
24441            vec!["blob", "codec"]
24442        );
24443        assert_eq!(commands[0]["entries"], server_entries);
24444        let wire_entries =
24445            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
24446        assert_eq!(wire_entries, entries);
24447
24448        let history = vec![history_event(
24449            "MemoUpserted",
24450            json!({
24451                "sequence": 1,
24452                "entries": server_entries.clone(),
24453                "merged": server_entries,
24454            }),
24455        )];
24456        let replay = workflow_context(history.clone());
24457        replay
24458            .upsert_memo(entries.clone())
24459            .expect("matching replay identity");
24460        assert!(replay.take_commands().expect("replay commands").is_empty());
24461
24462        let changed_types = AvroValue::Map(BTreeMap::from([
24463            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
24464            (
24465                "nested".to_string(),
24466                AvroValue::Map(BTreeMap::from([
24467                    ("alpha".to_string(), AvroValue::Long(1)),
24468                    ("beta".to_string(), AvroValue::Long(2)),
24469                ])),
24470            ),
24471            ("long".to_string(), AvroValue::Double(7.0)),
24472            ("double".to_string(), AvroValue::Long(7)),
24473            ("binary".to_string(), AvroValue::String("same".to_string())),
24474        ]));
24475        let error = workflow_context(history)
24476            .upsert_memo(changed_types)
24477            .expect_err("memo replay identity must preserve Avro value types");
24478        assert!(matches!(
24479            error,
24480            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24481        ));
24482    }
24483
24484    #[test]
24485    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
24486        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
24487            .expect("memo envelope");
24488        let replay = workflow_context(vec![history_event(
24489            "MemoUpserted",
24490            json!({
24491                "sequence": 1,
24492                "entries": original.clone(),
24493                "merged": original
24494            }),
24495        )]);
24496        let error = replay
24497            .upsert_memo(json!({"stage": "changed"}))
24498            .expect_err("changed memo update must fail replay");
24499        assert!(matches!(
24500            error,
24501            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24502        ));
24503
24504        let invalid = workflow_context(Vec::new())
24505            .upsert_memo(
24506                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
24507            )
24508            .expect_err("oversized key");
24509        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
24510    }
24511
24512    #[test]
24513    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
24514        let negative_zero = AvroValue::Map(BTreeMap::from([(
24515            "reading".to_string(),
24516            AvroValue::Double(-0.0),
24517        )]));
24518        let negative_zero_envelope =
24519            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
24520        let history = vec![history_event(
24521            "MemoUpserted",
24522            json!({
24523                "sequence": 1,
24524                "entries": negative_zero_envelope.clone(),
24525                "merged": negative_zero_envelope,
24526            }),
24527        )];
24528
24529        workflow_context(history.clone())
24530            .upsert_memo(negative_zero)
24531            .expect("matching negative-zero history identity");
24532
24533        let error = workflow_context(history)
24534            .upsert_memo(AvroValue::Map(BTreeMap::from([(
24535                "reading".to_string(),
24536                AvroValue::Double(0.0),
24537            )])))
24538            .expect_err("positive zero must not consume negative-zero memo history");
24539        assert!(matches!(
24540            error,
24541            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24542        ));
24543    }
24544
24545    #[test]
24546    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
24547        let supported = json!({
24548            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
24549            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
24550        });
24551        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
24552        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
24553            "workflow_memo_updates": {"supported": false},
24554            "supported_workflow_task_commands": ["upsert_memo"]
24555        }))));
24556        assert!(commands_use_workflow_memo_updates(&[json!({
24557            "type": "upsert_memo",
24558            "entries": {"stage": "processing"}
24559        })]));
24560    }
24561
24562    #[test]
24563    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
24564        let client = Client::new("http://127.0.0.1:8080").expect("client");
24565        let mut worker = Worker::new(client, "rust-workers");
24566        worker.register_workflow("rust.timer", |ctx, _input| async move {
24567            ctx.sleep(Duration::from_secs(5)).await?;
24568            ctx.activity("after-timer", json!([])).await
24569        });
24570
24571        let task = |history_events| WorkflowTask {
24572            task_id: "wft-rust-timer-1".to_string(),
24573            workflow_command_id: None,
24574            workflow_id: Some("wf-rust-timer".to_string()),
24575            run_id: Some("run-rust-timer".to_string()),
24576            workflow_type: "rust.timer".to_string(),
24577            cancel_requested: false,
24578            payload_codec: DEFAULT_CODEC.to_string(),
24579            arguments: Some(
24580                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24581            ),
24582            history_events,
24583            total_history_events: None,
24584            history_size_bytes: None,
24585            continue_as_new_recommended: None,
24586            history_budget_pressure: None,
24587            next_history_page_token: None,
24588            workflow_task_attempt: 1,
24589            workflow_signal_id: None,
24590            signal_name: None,
24591            signal_arguments: None,
24592            workflow_update_id: None,
24593            update_name: None,
24594            lease_owner: Some("rust-worker".to_string()),
24595        };
24596
24597        let initial = worker
24598            .execute_workflow_task(task(Vec::new()))
24599            .expect("initial timer task");
24600        assert_eq!(
24601            initial,
24602            vec![json!({"type": "start_timer", "delay_seconds": 5})]
24603        );
24604
24605        let activity_result =
24606            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
24607        let replayed = worker
24608            .execute_workflow_task(task(vec![
24609                history_event(
24610                    "TimerScheduled",
24611                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24612                ),
24613                history_event(
24614                    "TimerFired",
24615                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24616                ),
24617                history_event(
24618                    "ActivityCompleted",
24619                    json!({
24620                        "sequence": 2,
24621                        "activity_type": "after-timer",
24622                        "payload_codec": DEFAULT_CODEC,
24623                        "result": activity_result,
24624                    }),
24625                ),
24626            ]))
24627            .expect("replayed workflow task");
24628        assert_eq!(replayed.len(), 1);
24629        assert_eq!(replayed[0]["type"], "complete_workflow");
24630        assert_eq!(
24631            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
24632            json!("done")
24633        );
24634    }
24635
24636    #[test]
24637    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
24638        let client = Client::new("http://127.0.0.1:8080").expect("client");
24639        let mut worker = Worker::new(client, "rust-workers");
24640        worker.register_workflow("rust.continue", |ctx, _input| async move {
24641            ctx.continue_as_new_with_options(
24642                ContinueAsNewOptions::new()
24643                    .workflow_type("rust.next")
24644                    .task_queue("next-workers"),
24645                json!([2, {"cursor": "next"}]),
24646            )
24647        });
24648
24649        let commands = worker
24650            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
24651            .expect("continue-as-new command");
24652
24653        assert_eq!(commands.len(), 1);
24654        assert_eq!(commands[0]["type"], "continue_as_new");
24655        assert_eq!(commands[0]["workflow_type"], "rust.next");
24656        assert_eq!(commands[0]["queue"], "next-workers");
24657        assert_eq!(
24658            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
24659                .expect("continue-as-new arguments"),
24660            json!([2, {"cursor": "next"}])
24661        );
24662    }
24663
24664    #[test]
24665    fn continue_as_new_preserves_typed_arguments() {
24666        let client = Client::new("http://127.0.0.1:8080").expect("client");
24667        let mut worker = Worker::new(client, "rust-workers");
24668        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
24669            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
24670            unreachable!("continue-as-new returns a control-flow error")
24671        });
24672
24673        let commands = worker
24674            .execute_workflow_task(workflow_task(
24675                "rust.typed-continue",
24676                Vec::new(),
24677                DEFAULT_CODEC,
24678            ))
24679            .expect("typed continue-as-new command");
24680
24681        assert_eq!(commands[0]["type"], "continue_as_new");
24682        assert_eq!(
24683            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
24684                .expect("typed continue arguments"),
24685            AvroValue::Array(vec![typed_fidelity_probe()])
24686        );
24687    }
24688
24689    #[test]
24690    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
24691        let client = Client::new("http://127.0.0.1:8080").expect("client");
24692        let mut worker = Worker::new(client, "rust-workers");
24693        worker.register_workflow("rust.continue", |ctx, _input| async move {
24694            ctx.continue_as_new(json!([2]))
24695        });
24696        let task = workflow_task(
24697            "rust.continue",
24698            vec![history_event(
24699                "WorkflowContinuedAsNew",
24700                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
24701            )],
24702            DEFAULT_CODEC,
24703        );
24704
24705        for _worker_restart_or_redelivery in 0..2 {
24706            let commands = worker
24707                .execute_workflow_task(task.clone())
24708                .expect("recorded transition replays");
24709            assert!(
24710                commands.is_empty(),
24711                "replay must not emit another successor"
24712            );
24713        }
24714    }
24715
24716    #[test]
24717    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
24718        let ctx = workflow_context(Vec::new());
24719        let error = ctx
24720            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
24721            .expect_err("blank queue must be rejected");
24722
24723        let Error::InvalidContinueAsNewOptions(error) = error else {
24724            panic!("expected typed continue-as-new validation error");
24725        };
24726        assert_eq!(error.field, "task_queue");
24727        assert!(ctx.take_commands().expect("commands").is_empty());
24728    }
24729
24730    #[test]
24731    fn workflow_context_exposes_server_history_budget() {
24732        let client = Client::new("http://127.0.0.1:8080").expect("client");
24733        let mut worker = Worker::new(client, "rust-workers");
24734        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
24735            let budget = ctx.history_budget()?;
24736            Ok(json!({
24737                "events": budget.event_count,
24738                "bytes": budget.size_bytes,
24739                "recommended": budget.continue_as_new_recommended,
24740                "pressure": budget.pressure,
24741            }))
24742        });
24743        let task: WorkflowTask = serde_json::from_value(json!({
24744            "task_id": "task-history-budget",
24745            "workflow_type": "rust.history-budget",
24746            "payload_codec": DEFAULT_CODEC,
24747            "history_events": [],
24748            "total_history_events": 480,
24749            "history_size_bytes": 1_048_576,
24750            "continue_as_new_recommended": true,
24751            "history_budget_pressure": "continue_as_new_recommended",
24752        }))
24753        .expect("published workflow task");
24754
24755        let commands = worker
24756            .execute_workflow_task(task)
24757            .expect("history-budget workflow");
24758        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
24759        assert_eq!(result["events"], 480);
24760        assert_eq!(result["bytes"], 1_048_576);
24761        assert_eq!(result["recommended"], true);
24762        assert_eq!(result["pressure"], "continue_as_new_recommended");
24763    }
24764
24765    #[test]
24766    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
24767        let client = Client::new("http://127.0.0.1:8080").expect("client");
24768        let mut worker = Worker::new(client, "rust-workers");
24769        worker.register_workflow("rust.failing", |_ctx, _input| async move {
24770            Err(Error::Codec("rust_conformance_failure".to_string()))
24771        });
24772        let task = WorkflowTask {
24773            task_id: "wft-rust-failing-1".to_string(),
24774            workflow_command_id: None,
24775            workflow_id: Some("wf-rust-failing".to_string()),
24776            run_id: Some("run-rust-failing".to_string()),
24777            workflow_type: "rust.failing".to_string(),
24778            cancel_requested: false,
24779            payload_codec: DEFAULT_CODEC.to_string(),
24780            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24781            history_events: Vec::new(),
24782            total_history_events: Some(0),
24783            history_size_bytes: None,
24784            continue_as_new_recommended: None,
24785            history_budget_pressure: None,
24786            next_history_page_token: None,
24787            workflow_task_attempt: 1,
24788            workflow_signal_id: None,
24789            signal_name: None,
24790            signal_arguments: None,
24791            workflow_update_id: None,
24792            update_name: None,
24793            lease_owner: Some("rust-worker".to_string()),
24794        };
24795
24796        let commands = worker
24797            .execute_workflow_task(task)
24798            .expect("handler failure becomes a workflow command");
24799
24800        assert_eq!(commands.len(), 1);
24801        assert_eq!(commands[0]["type"], "fail_workflow");
24802        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
24803        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
24804        assert_eq!(commands[0]["non_retryable"], false);
24805        assert_eq!(
24806            commands[0]["message"],
24807            "codec error: rust_conformance_failure"
24808        );
24809        assert_eq!(
24810            commands[0]["exception"]["message"],
24811            "codec error: rust_conformance_failure"
24812        );
24813    }
24814
24815    #[test]
24816    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
24817        let client = Client::new("http://127.0.0.1:8080").expect("client");
24818        let mut worker = Worker::new(client, "rust-workers");
24819        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
24820            let _: String = ctx.side_effect(|| "captured".to_string())?;
24821            Err(Error::WorkerLoop("application failure".to_string()))
24822        });
24823
24824        let commands = worker
24825            .execute_workflow_task(workflow_task(
24826                "rust.failing-after-side-effect",
24827                Vec::new(),
24828                DEFAULT_CODEC,
24829            ))
24830            .expect("ordinary failure remains a workflow decision");
24831
24832        assert_eq!(commands.len(), 2);
24833        assert_eq!(commands[0]["type"], "record_side_effect");
24834        assert_eq!(commands[1]["type"], "fail_workflow");
24835    }
24836
24837    #[test]
24838    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
24839        let client = Client::new("http://127.0.0.1:8080").expect("client");
24840        let mut worker = Worker::new(client, "rust-workers");
24841        worker.register_workflow("rust.redrive", |ctx, _input| async move {
24842            ctx.activity("greet", json!([])).await?;
24843            Ok(Value::Null)
24844        });
24845        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
24846            match ctx.activity("greet", json!([])).await {
24847                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
24848                result => result,
24849            }
24850        });
24851
24852        let failed = history_event(
24853            "ActivityFailed",
24854            json!({
24855                "sequence": 1,
24856                "activity_type": "greet",
24857                "activity_execution_id": "activity-1",
24858                "message": "failed"
24859            }),
24860        );
24861        let commands = worker
24862            .execute_workflow_task(workflow_task(
24863                "rust.redrive",
24864                vec![failed.clone()],
24865                DEFAULT_CODEC,
24866            ))
24867            .expect("recorded failure becomes a workflow command");
24868        assert_eq!(commands[0]["type"], "fail_workflow");
24869        assert_eq!(commands[0]["failed_step_sequence"], 1);
24870        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
24871
24872        let translated = worker
24873            .execute_workflow_task(workflow_task(
24874                "rust.redrive-translated",
24875                vec![failed],
24876                DEFAULT_CODEC,
24877            ))
24878            .expect("translated failure becomes a workflow command");
24879        assert_eq!(translated[0]["type"], "fail_workflow");
24880        assert!(translated[0].get("failed_step_sequence").is_none());
24881        assert!(translated[0].get("failed_activity_execution_id").is_none());
24882
24883        let without_identity = worker
24884            .execute_workflow_task(workflow_task(
24885                "rust.redrive",
24886                vec![history_event(
24887                    "ActivityFailed",
24888                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
24889                )],
24890                DEFAULT_CODEC,
24891            ))
24892            .expect("incomplete identity still fails the workflow");
24893        assert!(without_identity[0].get("failed_step_sequence").is_none());
24894
24895        let timed_out = worker
24896            .execute_workflow_task(workflow_task(
24897                "rust.redrive",
24898                vec![history_event(
24899                    "ActivityTimedOut",
24900                    json!({
24901                        "sequence": 1,
24902                        "activity_type": "greet",
24903                        "activity_execution_id": "activity-timeout",
24904                    }),
24905                )],
24906                DEFAULT_CODEC,
24907            ))
24908            .expect("timeout still fails the workflow");
24909        assert!(timed_out[0].get("failed_step_sequence").is_none());
24910    }
24911
24912    #[test]
24913    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
24914        let client = Client::new("http://127.0.0.1:8080").expect("client");
24915        let mut worker = Worker::new(client, "rust-workers");
24916        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
24917            let first = ctx.activity("first", json!([])).await?;
24918            let second = ctx.activity("second", json!([first.clone()])).await?;
24919            Ok(json!({"first": first, "second": second}))
24920        });
24921        let first = history_event(
24922            "ActivityCompleted",
24923            json!({
24924                "sequence": 1,
24925                "activity_type": "first",
24926                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
24927                "payload_codec": DEFAULT_CODEC,
24928                "reused_from_run_id": "failed-run",
24929                "reused_activity_execution_id": "original-first",
24930            }),
24931        );
24932
24933        let retry = worker
24934            .execute_workflow_task(workflow_task(
24935                "rust.redrive-successor",
24936                vec![first.clone()],
24937                DEFAULT_CODEC,
24938            ))
24939            .expect("reused result replays before failed step");
24940        assert_eq!(retry.len(), 1);
24941        assert_eq!(retry[0]["type"], "schedule_activity");
24942        assert_eq!(retry[0]["activity_type"], "second");
24943        assert_eq!(
24944            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
24945            json!(["recorded"]),
24946        );
24947
24948        let second = history_event(
24949            "ActivityCompleted",
24950            json!({
24951                "sequence": 2,
24952                "activity_type": "second",
24953                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
24954                "payload_codec": DEFAULT_CODEC,
24955            }),
24956        );
24957        let completed = worker
24958            .execute_workflow_task(workflow_task(
24959                "rust.redrive-successor",
24960                vec![first, second],
24961                DEFAULT_CODEC,
24962            ))
24963            .expect("retried step completes the successor");
24964        assert_eq!(completed.len(), 1);
24965        assert_eq!(completed[0]["type"], "complete_workflow");
24966        assert_eq!(
24967            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
24968            json!({"first": "recorded", "second": "retried"}),
24969        );
24970    }
24971
24972    #[test]
24973    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
24974        let client = Client::new("http://127.0.0.1:8080").expect("client");
24975        let mut worker = Worker::new(client, "rust-workers");
24976        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
24977            Err(Error::WorkerLoop("application failure".to_string()))
24978        });
24979        let result =
24980            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
24981
24982        let error = worker
24983            .execute_workflow_task(workflow_task(
24984                "rust.removed-side-effect",
24985                vec![history_event(
24986                    "SideEffectRecorded",
24987                    json!({"sequence": 1, "result": result}),
24988                )],
24989                DEFAULT_CODEC,
24990            ))
24991            .expect_err("removed committed history must not become fail_workflow");
24992
24993        let Error::NonDeterministicReplay(failure) = error else {
24994            panic!("expected typed replay failure");
24995        };
24996        assert_eq!(failure.reason, "recorded_commands_unconsumed");
24997        assert_eq!(failure.sequence, Some(1));
24998        assert_eq!(failure.expected.as_deref(), Some("side effect"));
24999    }
25000
25001    #[test]
25002    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
25003        let client = Client::new("http://127.0.0.1:8080").expect("client");
25004        let mut worker = Worker::new(client, "rust-workers");
25005        worker.register_workflow(
25006            "rust.side-effect-before-marker-error",
25007            |ctx, _input| async move {
25008                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
25009                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
25010                ctx.get_version("restart-safe", 2, 2)?;
25011                Ok(Value::Null)
25012            },
25013        );
25014
25015        let error = worker
25016            .execute_workflow_task(workflow_task(
25017                "rust.side-effect-before-marker-error",
25018                vec![history_event(
25019                    "VersionMarkerRecorded",
25020                    json!({
25021                        "sequence": 1,
25022                        "change_id": "restart-safe",
25023                        "version": 1,
25024                        "min_supported": 1,
25025                        "max_supported": 1,
25026                    }),
25027                )],
25028                DEFAULT_CODEC,
25029            ))
25030            .expect_err("replay error must return no queued workflow commands");
25031
25032        let Error::NonDeterministicReplay(failure) = error else {
25033            panic!("expected typed replay failure");
25034        };
25035        assert_eq!(failure.reason, "version_marker_incompatible_range");
25036        assert_eq!(failure.sequence, Some(1));
25037    }
25038
25039    #[test]
25040    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
25041        let client = Client::new("http://127.0.0.1:8080").expect("client");
25042        let mut worker = Worker::new(client, "rust-workers");
25043        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
25044            ctx.sleep(Duration::from_secs(5)).await?;
25045            Ok(json!({"status": "timer fired"}))
25046        });
25047
25048        let task = WorkflowTask {
25049            task_id: "wft-rust-timer-pending".to_string(),
25050            workflow_command_id: None,
25051            workflow_id: Some("wf-rust-timer".to_string()),
25052            run_id: Some("run-rust-timer".to_string()),
25053            workflow_type: "rust.timer.pending".to_string(),
25054            cancel_requested: false,
25055            payload_codec: DEFAULT_CODEC.to_string(),
25056            arguments: Some(
25057                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25058            ),
25059            history_events: vec![history_event(
25060                "TimerScheduled",
25061                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25062            )],
25063            total_history_events: Some(1),
25064            history_size_bytes: None,
25065            continue_as_new_recommended: None,
25066            history_budget_pressure: None,
25067            next_history_page_token: None,
25068            workflow_task_attempt: 1,
25069            workflow_signal_id: None,
25070            signal_name: None,
25071            signal_arguments: None,
25072            workflow_update_id: None,
25073            update_name: None,
25074            lease_owner: Some("rust-worker".to_string()),
25075        };
25076
25077        for _redelivery_or_restart in 0..2 {
25078            let commands = worker
25079                .execute_workflow_task(task.clone())
25080                .expect("recorded timer remains pending");
25081            assert!(
25082                commands.is_empty(),
25083                "recorded timer must not be rescheduled"
25084            );
25085        }
25086    }
25087
25088    #[test]
25089    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
25090        let client = Client::new("http://127.0.0.1:8080").expect("client");
25091        let mut worker = Worker::new(client, "rust-workers");
25092        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
25093            Ok(json!({"status": "completed"}))
25094        });
25095        let task = WorkflowTask {
25096            task_id: "wft-rust-timer-removed".to_string(),
25097            workflow_command_id: None,
25098            workflow_id: Some("wf-rust-timer".to_string()),
25099            run_id: Some("run-rust-timer".to_string()),
25100            workflow_type: "rust.timer.removed".to_string(),
25101            cancel_requested: false,
25102            payload_codec: DEFAULT_CODEC.to_string(),
25103            arguments: Some(
25104                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25105            ),
25106            history_events: vec![
25107                history_event(
25108                    "TimerScheduled",
25109                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25110                ),
25111                history_event(
25112                    "TimerFired",
25113                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25114                ),
25115            ],
25116            total_history_events: Some(2),
25117            history_size_bytes: None,
25118            continue_as_new_recommended: None,
25119            history_budget_pressure: None,
25120            next_history_page_token: None,
25121            workflow_task_attempt: 1,
25122            workflow_signal_id: None,
25123            signal_name: None,
25124            signal_arguments: None,
25125            workflow_update_id: None,
25126            update_name: None,
25127            lease_owner: Some("rust-worker".to_string()),
25128        };
25129
25130        let Error::NonDeterministicReplay(failure) = worker
25131            .execute_workflow_task(task)
25132            .expect_err("removed timer must fail replay")
25133        else {
25134            panic!("expected typed replay failure");
25135        };
25136        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25137        assert_eq!(failure.sequence, Some(1));
25138    }
25139
25140    #[test]
25141    fn workflow_context_emits_explicit_child_workflow_contract() {
25142        let ctx = WorkflowContext {
25143            cancellation_scope_id: "root".into(),
25144            state: Arc::new(Mutex::new(
25145                WorkflowState::new_with_identity(
25146                    Vec::new(),
25147                    Some("wf-parent".to_string()),
25148                    Some("run-parent".to_string()),
25149                    "parent-workers".to_string(),
25150                    DEFAULT_CODEC.to_string(),
25151                    None,
25152                )
25153                .expect("workflow state"),
25154            )),
25155        };
25156        let options = ChildWorkflowOptions::new("python-workers")
25157            .parent_close_policy(ParentClosePolicy::RequestCancel)
25158            .retry_policy(ChildWorkflowRetryPolicy {
25159                max_attempts: Some(3),
25160                backoff_seconds: vec![1, 5],
25161                non_retryable_error_types: vec!["ValidationError".to_string()],
25162            })
25163            .execution_timeout_seconds(600)
25164            .run_timeout_seconds(120);
25165        let mut call = Box::pin(ctx.start_child_workflow(
25166            "python.fulfil-order",
25167            options,
25168            json!([{"order_id": "order-42"}]),
25169        ));
25170        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25171
25172        assert!(matches!(
25173            call.as_mut().poll(&mut task_context),
25174            Poll::Pending
25175        ));
25176        let commands = ctx.take_commands().expect("commands");
25177        assert_eq!(commands.len(), 1);
25178        let command = &commands[0];
25179        assert_eq!(command["type"], "start_child_workflow");
25180        assert_eq!(command["workflow_type"], "python.fulfil-order");
25181        assert_eq!(command["queue"], "python-workers");
25182        assert_eq!(command["parent_close_policy"], "request_cancel");
25183        assert_eq!(command["retry_policy"]["max_attempts"], 3);
25184        assert_eq!(command["execution_timeout_seconds"], 600);
25185        assert_eq!(command["run_timeout_seconds"], 120);
25186        assert_eq!(
25187            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
25188            json!([{"order_id": "order-42"}])
25189        );
25190    }
25191
25192    fn child_parent_worker() -> Worker {
25193        let client = Client::new("http://127.0.0.1:8080").expect("client");
25194        let mut worker = Worker::new(client, "rust-parent-workers");
25195        worker.register_workflow("rust.parent", |ctx, _input| async move {
25196            let child = ctx
25197                .start_child_workflow(
25198                    "python.child",
25199                    ChildWorkflowOptions::new("python-child-workers")
25200                        .parent_close_policy(ParentClosePolicy::Terminate),
25201                    json!([{"codec_probe": [1, true, "rust"]}]),
25202                )
25203                .await?;
25204            Ok(json!({
25205                "parent_workflow_id": child.parent.workflow_id,
25206                "parent_run_id": child.parent.run_id,
25207                "child_workflow_id": child.child.workflow_id,
25208                "child_run_id": child.child.run_id,
25209                "child_workflow_type": child.child_workflow_type,
25210                "result": child.result,
25211            }))
25212        });
25213        worker
25214    }
25215
25216    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
25217        WorkflowTask {
25218            task_id: "wft-child-parent".to_string(),
25219            workflow_command_id: None,
25220            workflow_id: Some("wf-parent".to_string()),
25221            run_id: Some("run-parent".to_string()),
25222            workflow_type: "rust.parent".to_string(),
25223            cancel_requested: false,
25224            payload_codec: DEFAULT_CODEC.to_string(),
25225            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25226            history_events: vec![
25227                HistoryEvent {
25228                    event_type: "ChildWorkflowScheduled".to_string(),
25229                    payload: json!({
25230                        "sequence": 1,
25231                        "child_call_id": "call-child",
25232                        "child_workflow_instance_id": "wf-child",
25233                        "child_workflow_run_id": "run-child",
25234                        "child_workflow_type": "python.child",
25235                        "parent_close_policy": "terminate",
25236                    }),
25237                    raw: HashMap::new(),
25238                },
25239                HistoryEvent {
25240                    event_type: event_type.to_string(),
25241                    payload,
25242                    raw: HashMap::new(),
25243                },
25244            ],
25245            total_history_events: Some(2),
25246            history_size_bytes: None,
25247            continue_as_new_recommended: None,
25248            history_budget_pressure: None,
25249            next_history_page_token: None,
25250            workflow_task_attempt: 1,
25251            workflow_signal_id: None,
25252            signal_name: None,
25253            signal_arguments: None,
25254            workflow_update_id: None,
25255            update_name: None,
25256            lease_owner: Some("rust-worker".to_string()),
25257        }
25258    }
25259
25260    #[test]
25261    fn committed_child_result_replays_without_starting_a_duplicate() {
25262        let worker = child_parent_worker();
25263        let task = child_parent_task(
25264            "ChildRunCompleted",
25265            json!({
25266                "sequence": 1,
25267                "child_call_id": "call-child",
25268                "child_workflow_instance_id": "wf-child",
25269                "child_workflow_run_id": "run-child",
25270                "child_workflow_type": "python.child",
25271                "payload_codec": DEFAULT_CODEC,
25272                "result": fixture_envelope(json!({"from":"python","ok":true})),
25273            }),
25274        );
25275
25276        for _restart in 0..2 {
25277            let commands = worker
25278                .execute_workflow_task(task.clone())
25279                .expect("replayed parent task");
25280            assert_eq!(commands.len(), 1);
25281            assert_eq!(commands[0]["type"], "complete_workflow");
25282            assert!(!commands
25283                .iter()
25284                .any(|command| command["type"] == "start_child_workflow"));
25285            let output =
25286                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25287            assert_eq!(output["parent_workflow_id"], "wf-parent");
25288            assert_eq!(output["parent_run_id"], "run-parent");
25289            assert_eq!(output["child_workflow_id"], "wf-child");
25290            assert_eq!(output["child_run_id"], "run-child");
25291            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
25292        }
25293    }
25294
25295    #[test]
25296    fn typed_child_arguments_and_results_survive_replay() {
25297        let client = Client::new("http://127.0.0.1:8080").expect("client");
25298        let mut worker = Worker::new(client, "rust-parent-workers");
25299        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
25300            let child = ctx
25301                .start_child_workflow_avro_value(
25302                    "python.typed-child",
25303                    ChildWorkflowOptions::new("python-workers"),
25304                    AvroValue::Array(vec![typed_fidelity_probe()]),
25305                )
25306                .await?;
25307            Ok(child.result)
25308        });
25309
25310        let initial = worker
25311            .execute_workflow_task(workflow_task(
25312                "rust.typed-parent",
25313                Vec::new(),
25314                DEFAULT_CODEC,
25315            ))
25316            .expect("typed child start");
25317        assert_eq!(initial[0]["type"], "start_child_workflow");
25318        assert_eq!(
25319            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
25320                .expect("typed child arguments"),
25321            AvroValue::Array(vec![typed_fidelity_probe()])
25322        );
25323
25324        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
25325            .expect("typed child result");
25326        let task = workflow_task(
25327            "rust.typed-parent",
25328            vec![
25329                history_event(
25330                    "ChildWorkflowScheduled",
25331                    json!({
25332                        "sequence": 1,
25333                        "child_call_id": "call-typed",
25334                        "child_workflow_instance_id": "wf-child",
25335                        "child_workflow_run_id": "run-child",
25336                        "child_workflow_type": "python.typed-child",
25337                    }),
25338                ),
25339                history_event(
25340                    "ChildRunCompleted",
25341                    json!({
25342                        "sequence": 1,
25343                        "child_call_id": "call-typed",
25344                        "child_workflow_instance_id": "wf-child",
25345                        "child_workflow_run_id": "run-child",
25346                        "child_workflow_type": "python.typed-child",
25347                        "payload_codec": DEFAULT_CODEC,
25348                        "result": result,
25349                    }),
25350                ),
25351            ],
25352            DEFAULT_CODEC,
25353        );
25354
25355        let commands = worker
25356            .execute_workflow_task(task)
25357            .expect("typed child replay");
25358        assert_eq!(commands[0]["type"], "complete_workflow");
25359        assert_eq!(
25360            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
25361                .expect("typed parent result"),
25362            typed_fidelity_probe()
25363        );
25364    }
25365
25366    #[test]
25367    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
25368        let worker = child_parent_worker();
25369        let mut task = child_parent_task("unused", Value::Null);
25370        task.history_events.truncate(1);
25371        task.total_history_events = Some(1);
25372
25373        for _redelivery_or_restart in 0..2 {
25374            let commands = worker
25375                .execute_workflow_task(task.clone())
25376                .expect("recorded child remains pending");
25377            assert!(
25378                commands.is_empty(),
25379                "recorded pending child must not be started again"
25380            );
25381        }
25382    }
25383
25384    #[test]
25385    fn child_cancellation_becomes_stable_parent_failure_command() {
25386        let worker = child_parent_worker();
25387        let task = child_parent_task(
25388            "ChildRunCancelled",
25389            json!({
25390                "sequence": 1,
25391                "child_workflow_instance_id": "wf-child",
25392                "child_workflow_run_id": "run-child",
25393                "child_workflow_type": "python.child",
25394                "failure_id": "failure-child",
25395                "failure_category": "cancelled",
25396                "message": "cancelled by parent-close policy",
25397            }),
25398        );
25399
25400        let commands = worker
25401            .execute_workflow_task(task)
25402            .expect("parent settlement");
25403        assert_eq!(commands.len(), 1);
25404        assert_eq!(commands[0]["type"], "fail_workflow");
25405        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
25406        assert_eq!(
25407            commands[0]["exception"]["properties"]["reason"],
25408            "cancelled"
25409        );
25410        assert_eq!(
25411            commands[0]["exception"]["properties"]["child_workflow_run_id"],
25412            "run-child"
25413        );
25414    }
25415
25416    #[test]
25417    fn workflow_can_handle_typed_child_failure() {
25418        let client = Client::new("http://127.0.0.1:8080").expect("client");
25419        let mut worker = Worker::new(client, "rust-parent-workers");
25420        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
25421            match ctx
25422                .start_child_workflow(
25423                    "python.child",
25424                    ChildWorkflowOptions::new("python-child-workers"),
25425                    json!([]),
25426                )
25427                .await
25428            {
25429                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
25430                    "reason": failure.reason,
25431                    "failure_id": failure.failure_id,
25432                    "exception_class": failure.exception_class,
25433                    "child_run_id": failure.child_workflow_run_id,
25434                })),
25435                Err(error) => Err(error),
25436                Ok(_) => Err(Error::WorkerLoop(
25437                    "child unexpectedly succeeded".to_string(),
25438                )),
25439            }
25440        });
25441        let mut task = child_parent_task(
25442            "ChildRunFailed",
25443            json!({
25444                "sequence": 1,
25445                "child_workflow_instance_id": "wf-child",
25446                "child_workflow_run_id": "run-child",
25447                "child_workflow_type": "python.child",
25448                "failure_id": "failure-child",
25449                "failure_category": "child_workflow",
25450                "message": "payment rejected",
25451                "exception": {
25452                    "type": "PaymentRejected",
25453                    "class": "payments.PaymentRejected",
25454                    "message": "payment rejected"
25455                }
25456            }),
25457        );
25458        task.workflow_type = "rust.handled-parent".to_string();
25459        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
25460
25461        let commands = worker.execute_workflow_task(task).expect("handled failure");
25462        assert_eq!(commands[0]["type"], "complete_workflow");
25463        let output =
25464            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25465        assert_eq!(output["reason"], "child_workflow");
25466        assert_eq!(output["failure_id"], "failure-child");
25467        assert_eq!(output["exception_class"], "payments.PaymentRejected");
25468        assert_eq!(output["child_run_id"], "run-child");
25469    }
25470
25471    #[test]
25472    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
25473        let client = Client::new("http://127.0.0.1:8080").expect("client");
25474        let mut worker = Worker::new(client, "rust-workers");
25475
25476        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
25477            let signal = ctx.wait_signal("start").await?;
25478            let name = signal
25479                .first()
25480                .and_then(|value| value.as_str())
25481                .unwrap_or("world");
25482            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
25483            Ok(json!({
25484                "greeting": greeting,
25485                "language": "rust"
25486            }))
25487        });
25488
25489        let signal_arguments =
25490            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
25491        let task = WorkflowTask {
25492            task_id: "wft-rust-signal-1".to_string(),
25493            workflow_command_id: None,
25494            workflow_id: Some("wf-rust-hello".to_string()),
25495            run_id: Some("run-rust-hello".to_string()),
25496            workflow_type: "rust.hello_workflow".to_string(),
25497            cancel_requested: false,
25498            payload_codec: DEFAULT_CODEC.to_string(),
25499            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25500            history_events: vec![HistoryEvent {
25501                event_type: "SignalReceived".to_string(),
25502                payload: json!({
25503                    "signal_id": "sig-rust-1",
25504                    "signal_name": "start"
25505                }),
25506                raw: HashMap::new(),
25507            }],
25508            total_history_events: Some(1),
25509            history_size_bytes: None,
25510            continue_as_new_recommended: None,
25511            history_budget_pressure: None,
25512            next_history_page_token: None,
25513            workflow_task_attempt: 1,
25514            workflow_signal_id: Some("sig-rust-1".to_string()),
25515            signal_name: Some("start".to_string()),
25516            signal_arguments: Some(signal_arguments),
25517            workflow_update_id: None,
25518            update_name: None,
25519            lease_owner: Some("rust-worker".to_string()),
25520        };
25521
25522        let commands = worker.execute_workflow_task(task).expect("workflow task");
25523
25524        assert_eq!(commands.len(), 1);
25525        assert_eq!(commands[0]["type"], "schedule_activity");
25526        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
25527        assert_eq!(
25528            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
25529            json!(["Rust"])
25530        );
25531    }
25532
25533    #[test]
25534    fn workflow_task_appends_paginated_history_events() {
25535        let mut task = WorkflowTask {
25536            task_id: "wft-rust-pages-1".to_string(),
25537            workflow_command_id: None,
25538            workflow_id: Some("wf-rust-pages".to_string()),
25539            run_id: Some("run-rust-pages".to_string()),
25540            workflow_type: "rust.hello_workflow".to_string(),
25541            cancel_requested: false,
25542            payload_codec: DEFAULT_CODEC.to_string(),
25543            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25544            history_events: vec![HistoryEvent {
25545                event_type: "WorkflowStarted".to_string(),
25546                payload: json!({}),
25547                raw: HashMap::new(),
25548            }],
25549            total_history_events: Some(3),
25550            history_size_bytes: None,
25551            continue_as_new_recommended: None,
25552            history_budget_pressure: None,
25553            next_history_page_token: Some("MQ==".to_string()),
25554            workflow_task_attempt: 1,
25555            workflow_signal_id: None,
25556            signal_name: None,
25557            signal_arguments: None,
25558            workflow_update_id: None,
25559            update_name: None,
25560            lease_owner: Some("rust-worker".to_string()),
25561        };
25562
25563        task.append_history_page(WorkflowTaskHistoryPage {
25564            history_events: vec![
25565                HistoryEvent {
25566                    event_type: "SignalReceived".to_string(),
25567                    payload: json!({
25568                        "signal_id": "sig-rust-1",
25569                        "signal_name": "start",
25570                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
25571                            .expect("signal arguments")
25572                    }),
25573                    raw: HashMap::new(),
25574                },
25575                HistoryEvent {
25576                    event_type: "MarkerRecorded".to_string(),
25577                    payload: json!({"sequence": 3}),
25578                    raw: HashMap::new(),
25579                },
25580            ],
25581            total_history_events: Some(3),
25582            next_history_page_token: None,
25583        });
25584
25585        assert_eq!(task.history_events.len(), 3);
25586        assert_eq!(task.total_history_events, Some(3));
25587        assert_eq!(task.next_history_page_token, None);
25588
25589        let signal = task
25590            .history_events
25591            .iter()
25592            .find(|event| event.event_type == "SignalReceived")
25593            .expect("signal event");
25594        assert_eq!(
25595            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
25596            vec![AvroValue::String("Rust".to_string())]
25597        );
25598    }
25599
25600    #[tokio::test]
25601    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
25602        let client = Client::new("http://127.0.0.1:8080").expect("client");
25603        let mut worker = Worker::new(client, "rust-workers");
25604        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25605        worker.register_query("counter", "current", |ctx, _args| async move {
25606            let mut count = 0_i64;
25607            for signal in ctx.signal_events() {
25608                let value = signal
25609                    .arguments
25610                    .first()
25611                    .and_then(Value::as_i64)
25612                    .unwrap_or_default();
25613                match signal.name.as_str() {
25614                    "increment" => count += value,
25615                    "set" => count = value,
25616                    _ => {}
25617                }
25618            }
25619            Ok(json!(count))
25620        });
25621
25622        let task = QueryTask {
25623            query_task_id: "query-rust-counter".to_string(),
25624            query_task_attempt: 1,
25625            lease_owner: Some("rust-worker".to_string()),
25626            workflow_id: Some("counter-1".to_string()),
25627            run_id: Some("run-counter-1".to_string()),
25628            workflow_type: "counter".to_string(),
25629            query_name: "current".to_string(),
25630            payload_codec: DEFAULT_CODEC.to_string(),
25631            workflow_arguments: Some(
25632                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25633            ),
25634            query_arguments: Some(
25635                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
25636            ),
25637            history_events: vec![
25638                HistoryEvent {
25639                    event_type: "SignalReceived".to_string(),
25640                    payload: json!({
25641                        "signal_id": "php-signal-1",
25642                        "signal_name": "increment",
25643                        "workflow_sequence": 1,
25644                        "payload_codec": DEFAULT_CODEC,
25645                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
25646                    }),
25647                    raw: HashMap::new(),
25648                },
25649                HistoryEvent {
25650                    event_type: "SignalReceived".to_string(),
25651                    payload: json!({
25652                        "signal_id": "python-signal-2",
25653                        "signal_name": "increment",
25654                        "workflow_sequence": 2,
25655                        "payload_codec": DEFAULT_CODEC,
25656                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
25657                    }),
25658                    raw: HashMap::new(),
25659                },
25660                HistoryEvent {
25661                    event_type: "SignalReceived".to_string(),
25662                    payload: json!({
25663                        "signal_id": "rust-signal-3",
25664                        "signal_name": "set",
25665                        "workflow_sequence": 3,
25666                        "payload_codec": DEFAULT_CODEC,
25667                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
25668                    }),
25669                    raw: HashMap::new(),
25670                },
25671            ],
25672            history_export: None,
25673            run_status: Some("completed".to_string()),
25674        };
25675
25676        let result = worker.execute_query_task(task).await.expect("query result");
25677        assert_eq!(result.into_json().expect("query projection"), json!(0));
25678    }
25679
25680    #[tokio::test]
25681    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
25682        let worker = replay_counter_worker();
25683        let running_history = json!([
25684            {
25685                "type": "ActivityCompleted",
25686                "payload": {
25687                    "sequence": 1,
25688                    "activity_type": "load-counter",
25689                    "payload_codec": DEFAULT_CODEC,
25690                    "result": fixture_envelope(json!("loaded"))
25691                }
25692            },
25693            {
25694                "type": "SignalWaitOpened",
25695                "payload": {
25696                    "sequence": 3,
25697                    "signal_name": "increment"
25698                }
25699            },
25700            {
25701                "type": "SignalReceived",
25702                "payload": {
25703                    "signal_id": "signal-3",
25704                    "signal_name": "increment",
25705                    "workflow_sequence": 2,
25706                    "payload_codec": DEFAULT_CODEC,
25707                    "arguments": fixture_envelope(json!([3]))
25708                }
25709            },
25710            {
25711                "type": "SignalApplied",
25712                "payload": {
25713                    "sequence": 3,
25714                    "signal_id": "signal-3",
25715                    "signal_name": "increment",
25716                    "payload_codec": DEFAULT_CODEC,
25717                    "value": fixture_envelope(json!([3]))
25718                }
25719            }
25720        ]);
25721
25722        let running = worker
25723            .execute_query_task(replay_counter_query(
25724                "current",
25725                running_history.clone(),
25726                "running",
25727            ))
25728            .await
25729            .expect("running replay query");
25730        assert_eq!(
25731            running.clone().into_json().expect("query projection"),
25732            json!({"loaded": "loaded", "count": 3, "finished": false})
25733        );
25734
25735        let detached = worker
25736            .execute_query_task(replay_counter_query(
25737                "detached-mutation",
25738                running_history.clone(),
25739                "running",
25740            ))
25741            .await
25742            .expect("query mutates only its detached state clone");
25743        assert_eq!(detached.into_json().expect("query projection"), json!(999));
25744        let failed = worker
25745            .execute_query_task(replay_counter_query(
25746                "failed-mutation",
25747                running_history.clone(),
25748                "running",
25749            ))
25750            .await
25751            .expect_err("failed query");
25752        assert_eq!(failed.reason, "query_rejected");
25753        let unchanged = worker
25754            .execute_query_task(replay_counter_query("current", running_history, "running"))
25755            .await
25756            .expect("later query reconstructs unchanged state");
25757        assert_eq!(unchanged, running);
25758
25759        let restarted_worker = replay_counter_worker();
25760        let empty_arguments = fixture_envelope(json!([]));
25761        let loaded_result = fixture_envelope(json!("loaded"));
25762        let signal_three = fixture_blob(json!([3]));
25763        let signal_five = fixture_blob(json!([5]));
25764        let restarted_task: QueryTask = serde_json::from_value(json!({
25765            "query_task_id": "query-after-restart",
25766            "workflow_id": "counter-1",
25767            "run_id": "run-counter-1",
25768            "workflow_type": "replay-counter",
25769            "query_name": "current",
25770            "payload_codec": DEFAULT_CODEC,
25771            "workflow_arguments": empty_arguments.clone(),
25772            "query_arguments": empty_arguments,
25773            "history_events": [],
25774            "history_export": {
25775                "payloads": {"codec": DEFAULT_CODEC},
25776                "history_events": [
25777                    {
25778                        "type": "ActivityCompleted",
25779                        "payload": {
25780                            "sequence": 1,
25781                            "activity_type": "load-counter",
25782                            "payload_codec": DEFAULT_CODEC,
25783                            "result": null
25784                        }
25785                    },
25786                    {
25787                        "type": "SignalWaitOpened",
25788                        "payload": {
25789                            "sequence": 3,
25790                            "signal_name": "increment"
25791                        }
25792                    },
25793                    {
25794                        "type": "SignalReceived",
25795                        "payload": {
25796                            "signal_id": "signal-3",
25797                            "signal_name": "increment",
25798                            "workflow_sequence": 2
25799                        }
25800                    },
25801                    {
25802                        "type": "SignalApplied",
25803                        "payload": {
25804                            "sequence": 3,
25805                            "signal_id": "signal-3",
25806                            "signal_name": "increment"
25807                        }
25808                    },
25809                    {
25810                        "type": "SignalWaitOpened",
25811                        "payload": {
25812                            "sequence": 5,
25813                            "signal_name": "increment"
25814                        }
25815                    },
25816                    {
25817                        "type": "SignalReceived",
25818                        "payload": {
25819                            "signal_id": "signal-5",
25820                            "signal_name": "increment",
25821                            "workflow_sequence": 4
25822                        }
25823                    },
25824                    {
25825                        "type": "SignalApplied",
25826                        "payload": {
25827                            "sequence": 5,
25828                            "signal_id": "signal-5",
25829                            "signal_name": "increment"
25830                        }
25831                    }
25832                ],
25833                "activities": [{
25834                    "sequence": 1,
25835                    "activity_type": "load-counter",
25836                    "payload_codec": DEFAULT_CODEC,
25837                    "result": loaded_result
25838                }],
25839                "signals": [
25840                    {
25841                        "id": "signal-3",
25842                        "name": "increment",
25843                        "workflow_sequence": 2,
25844                        "payload_codec": DEFAULT_CODEC,
25845                        "arguments": signal_three
25846                    },
25847                    {
25848                        "id": "signal-5",
25849                        "name": "increment",
25850                        "workflow_sequence": 4,
25851                        "payload_codec": DEFAULT_CODEC,
25852                        "arguments": signal_five
25853                    }
25854                ]
25855            },
25856            "run_status": "completed"
25857        }))
25858        .expect("cold replay query task");
25859        let completed = restarted_worker
25860            .execute_query_task(restarted_task)
25861            .await
25862            .expect("completed cold replay query");
25863        assert_eq!(
25864            completed.into_json().expect("query projection"),
25865            json!({"loaded": "loaded", "count": 8, "finished": true})
25866        );
25867    }
25868
25869    #[tokio::test]
25870    async fn replayed_query_replay_failures_are_machine_readable() {
25871        let worker = replay_counter_worker();
25872        let task = replay_counter_query(
25873            "current",
25874            json!([{
25875                "type": "ActivityCompleted",
25876                "payload": {
25877                    "sequence": 1,
25878                    "payload_codec": DEFAULT_CODEC,
25879                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
25880                }
25881            }]),
25882            "running",
25883        );
25884        let failure = worker
25885            .execute_query_task(task)
25886            .await
25887            .expect_err("invalid replay history payload");
25888        assert_eq!(failure.reason, "query_payload_decode_failed");
25889        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
25890        assert!(failure.message.contains("invalid_payload_framing"));
25891    }
25892
25893    #[tokio::test]
25894    async fn query_task_restores_compact_history_from_export() {
25895        let client = Client::new("http://127.0.0.1:8080").expect("client");
25896        let mut worker = Worker::new(client, "rust-workers");
25897        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25898        worker.register_query("counter", "current", |ctx, _args| async move {
25899            Ok(json!(ctx.signals("increment")[0][0]))
25900        });
25901        let empty_arguments = fixture_envelope(json!([]));
25902        let exported_signal = fixture_blob(json!([9]));
25903        let task: QueryTask = serde_json::from_value(json!({
25904            "query_task_id": "query-export",
25905            "workflow_type": "counter",
25906            "query_name": "current",
25907            "payload_codec": DEFAULT_CODEC,
25908            "workflow_arguments": empty_arguments.clone(),
25909            "query_arguments": empty_arguments,
25910            "history_events": [],
25911            "history_export": {
25912                "payloads": {"codec": DEFAULT_CODEC},
25913                "history_events": [{
25914                    "type": "SignalReceived",
25915                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
25916                }],
25917                "signals": [{
25918                    "id": "signal-export",
25919                    "name": "increment",
25920                    "status": "applied",
25921                    "workflow_sequence": 1,
25922                    "payload_codec": DEFAULT_CODEC,
25923                    "arguments": exported_signal
25924                }]
25925            }
25926        }))
25927        .expect("query task");
25928
25929        let result = worker.execute_query_task(task).await.expect("query result");
25930        assert_eq!(result.into_json().expect("query projection"), json!(9));
25931    }
25932
25933    #[tokio::test]
25934    async fn query_task_failures_have_stable_reasons() {
25935        let client = Client::new("http://127.0.0.1:8080").expect("client");
25936        let mut worker = Worker::new(client, "rust-workers");
25937        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25938        worker.register_query(
25939            "counter",
25940            "current",
25941            |_ctx, _args| async move { Ok(json!(0)) },
25942        );
25943
25944        let base_task = QueryTask {
25945            query_task_id: "query-errors".to_string(),
25946            query_task_attempt: 1,
25947            lease_owner: None,
25948            workflow_id: Some("counter-errors".to_string()),
25949            run_id: Some("run-errors".to_string()),
25950            workflow_type: "counter".to_string(),
25951            query_name: "missing".to_string(),
25952            payload_codec: DEFAULT_CODEC.to_string(),
25953            workflow_arguments: Some(fixture_envelope(json!([]))),
25954            query_arguments: Some(fixture_envelope(json!([]))),
25955            history_events: Vec::new(),
25956            history_export: None,
25957            run_status: Some("running".to_string()),
25958        };
25959
25960        let unknown = worker
25961            .execute_query_task(base_task.clone())
25962            .await
25963            .expect_err("unknown query");
25964        assert_eq!(unknown.reason, "rejected_unknown_query");
25965
25966        let mut malformed = base_task;
25967        malformed.query_name = "current".to_string();
25968        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
25969        let malformed = worker
25970            .execute_query_task(malformed)
25971            .await
25972            .expect_err("malformed payload");
25973        assert_eq!(malformed.reason, "query_payload_decode_failed");
25974
25975        let client = Client::new("http://127.0.0.1:8080").expect("client");
25976        let mut unavailable_worker = Worker::new(client, "rust-workers");
25977        unavailable_worker
25978            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25979        let empty_arguments = fixture_envelope(json!([]));
25980        let unavailable_task: QueryTask = serde_json::from_value(json!({
25981            "query_task_id": "query-unavailable",
25982            "workflow_type": "counter",
25983            "query_name": "current",
25984            "payload_codec": DEFAULT_CODEC,
25985            "workflow_arguments": empty_arguments.clone(),
25986            "query_arguments": empty_arguments
25987        }))
25988        .expect("query task");
25989        let unavailable = unavailable_worker
25990            .execute_query_task(unavailable_task)
25991            .await
25992            .expect_err("query handler unavailable");
25993        assert_eq!(unavailable.reason, "query_handler_unavailable");
25994    }
25995
25996    #[tokio::test]
25997    async fn client_query_decodes_result_and_typed_failure() {
25998        let server = MockWorkerServer::start();
25999        let client = Client::builder(server.base_url())
26000            .timeout(Duration::from_secs(2))
26001            .build()
26002            .expect("client");
26003
26004        let result = client
26005            .query_workflow("counter-1", "current", json!([]))
26006            .await
26007            .expect("query result");
26008        assert_eq!(result, json!({"count": 8}));
26009
26010        let error = client
26011            .query_workflow("counter-1", "missing", json!([]))
26012            .await
26013            .expect_err("unknown query");
26014        let Error::QueryFailed(failure) = error else {
26015            panic!("expected typed query failure");
26016        };
26017        assert_eq!(failure.status, 404);
26018        assert_eq!(failure.reason, "rejected_unknown_query");
26019    }
26020
26021    #[tokio::test]
26022    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
26023        let server = MockWorkerServer::start();
26024        let client = Client::builder(server.base_url())
26025            .timeout(Duration::from_secs(2))
26026            .build()
26027            .expect("client");
26028        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
26029
26030        client
26031            .start_workflow(
26032                "typed.echo",
26033                "rust-workers",
26034                "typed-start",
26035                arguments.clone(),
26036            )
26037            .await
26038            .expect("typed workflow start");
26039        assert_eq!(
26040            decode_wire_avro_value(
26041                &server.request_body("/api/workflows")["input"],
26042                DEFAULT_CODEC,
26043            )
26044            .expect("typed start input"),
26045            arguments
26046        );
26047
26048        client
26049            .signal_workflow("typed-1", "changed", arguments.clone())
26050            .await
26051            .expect("typed signal");
26052        assert_eq!(
26053            decode_wire_avro_value(
26054                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
26055                DEFAULT_CODEC,
26056            )
26057            .expect("typed signal input"),
26058            arguments
26059        );
26060
26061        assert_eq!(
26062            client
26063                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
26064                .await
26065                .expect("typed query"),
26066            typed_fidelity_probe()
26067        );
26068        assert_eq!(
26069            decode_wire_avro_value(
26070                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
26071                DEFAULT_CODEC,
26072            )
26073            .expect("typed query input"),
26074            arguments
26075        );
26076
26077        assert_eq!(
26078            client
26079                .update_workflow_avro_value(
26080                    "typed-1",
26081                    "replace",
26082                    arguments.clone(),
26083                    Some("typed-request"),
26084                )
26085                .await
26086                .expect("typed update"),
26087            typed_fidelity_probe()
26088        );
26089        let update = server.request_body("/api/workflows/typed-1/update/replace");
26090        assert_eq!(update["request_id"], "typed-request");
26091        assert_eq!(
26092            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
26093            arguments
26094        );
26095
26096        let handle = WorkflowHandle {
26097            client: client.clone(),
26098            workflow_id: "typed-1".to_string(),
26099            run_id: Some("run-typed-1".to_string()),
26100            workflow_type: "typed.echo".to_string(),
26101        };
26102        assert_eq!(
26103            handle
26104                .result_avro_value(WorkflowResultOptions::default())
26105                .await
26106                .expect("typed workflow result"),
26107            typed_fidelity_probe()
26108        );
26109
26110        client
26111            .complete_activity_task(
26112                "activity-typed",
26113                "attempt-typed",
26114                "rust-worker",
26115                typed_fidelity_probe(),
26116                DEFAULT_CODEC,
26117            )
26118            .await
26119            .expect("typed activity completion");
26120        assert_eq!(
26121            decode_wire_avro_value(
26122                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
26123                    ["result"],
26124                DEFAULT_CODEC,
26125            )
26126            .expect("typed activity result"),
26127            typed_fidelity_probe()
26128        );
26129        client
26130            .fail_activity_task(
26131                "activity-typed",
26132                "attempt-typed",
26133                "rust-worker",
26134                "typed failure",
26135                true,
26136            )
26137            .await
26138            .expect("activity failure");
26139    }
26140
26141    #[tokio::test]
26142    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
26143        let server = MockWorkerServer::start();
26144        let client = Client::builder(server.base_url())
26145            .timeout(Duration::from_secs(2))
26146            .build()
26147            .expect("client");
26148
26149        let options = WorkflowCommandOptions::new()
26150            .reason("cleanup requested")
26151            .request_id("cancel-17");
26152        let cancelled = client
26153            .cancel_workflow("wf-lifecycle", options)
26154            .await
26155            .expect("instance cancellation");
26156        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
26157        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
26158        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
26159        assert_eq!(
26160            server.request_body("/api/workflows/wf-lifecycle/cancel"),
26161            json!({"reason":"cleanup requested","request_id":"cancel-17"})
26162        );
26163
26164        let terminated = client
26165            .terminate_workflow(
26166                "wf-lifecycle",
26167                WorkflowCommandOptions::new().reason("forced stop"),
26168            )
26169            .await
26170            .expect("instance termination");
26171        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
26172        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
26173
26174        client
26175            .cancel_workflow_run(
26176                "wf-lifecycle",
26177                "run-current",
26178                WorkflowCommandOptions::default(),
26179            )
26180            .await
26181            .expect("selected run cancellation");
26182        client
26183            .terminate_workflow_run(
26184                "wf-lifecycle",
26185                "run-current",
26186                WorkflowCommandOptions::default(),
26187            )
26188            .await
26189            .expect("selected run termination");
26190
26191        for (command, error) in [
26192            (
26193                WorkflowCommandKind::Cancel,
26194                client
26195                    .cancel_workflow_run(
26196                        "wf-lifecycle",
26197                        "run-stale",
26198                        WorkflowCommandOptions::default(),
26199                    )
26200                    .await
26201                    .expect_err("stale cancellation must be rejected"),
26202            ),
26203            (
26204                WorkflowCommandKind::Terminate,
26205                client
26206                    .terminate_workflow_run(
26207                        "wf-lifecycle",
26208                        "run-stale",
26209                        WorkflowCommandOptions::default(),
26210                    )
26211                    .await
26212                    .expect_err("stale termination must be rejected"),
26213            ),
26214        ] {
26215            let Error::WorkflowCommandRejected(rejection) = error else {
26216                panic!("expected typed command rejection");
26217            };
26218            assert_eq!(rejection.command, command);
26219            assert_eq!(rejection.status, 409);
26220            assert_eq!(rejection.reason, "historical_run_command_rejected");
26221            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
26222            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
26223        }
26224    }
26225
26226    #[tokio::test]
26227    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
26228        let server = MockWorkerServer::start();
26229        let client = Client::builder(server.base_url())
26230            .timeout(Duration::from_secs(2))
26231            .build()
26232            .expect("client");
26233
26234        let result = client
26235            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
26236            .await
26237            .expect("redrive accepted");
26238        assert_eq!(result.workflow_id, "wf-lifecycle");
26239        assert_eq!(result.source_run_id, "run-failed");
26240        assert_eq!(result.run_id, "run-successor");
26241        assert_eq!(result.resume_step_sequence, 2);
26242        assert_eq!(
26243            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
26244            json!({"request_id":"retry-1"})
26245        );
26246
26247        let repeated = client
26248            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
26249            .await
26250            .expect("idempotent redrive response accepted");
26251        assert_eq!(repeated.run_id, "run-successor");
26252
26253        let error = client
26254            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
26255            .await
26256            .expect_err("completed run must be rejected");
26257        let Error::Http { status, body } = error else {
26258            panic!("expected HTTP redrive rejection");
26259        };
26260        assert_eq!(status.as_u16(), 409);
26261        assert!(body.contains("run_not_failed"));
26262        assert_eq!(
26263            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
26264            json!({})
26265        );
26266
26267        let handle = WorkflowHandle {
26268            client: client.clone(),
26269            workflow_id: "wf-lifecycle".to_string(),
26270            run_id: Some("run-failed".to_string()),
26271            workflow_type: "test".to_string(),
26272        };
26273        assert_eq!(
26274            handle.redrive(None).await.expect("handle redrive").run_id,
26275            "run-successor"
26276        );
26277        let missing_run = WorkflowHandle {
26278            run_id: None,
26279            ..handle
26280        };
26281        assert!(matches!(
26282            missing_run.redrive(None).await,
26283            Err(Error::Codec(_))
26284        ));
26285    }
26286
26287    #[tokio::test]
26288    async fn workflow_start_options_send_server_enforced_deadlines() {
26289        let server = MockWorkerServer::start();
26290        let client = Client::builder(server.base_url())
26291            .timeout(Duration::from_secs(2))
26292            .build()
26293            .expect("client");
26294
26295        let handle = client
26296            .start_workflow_with_options(
26297                "rust.timeout",
26298                "rust-timeouts",
26299                "wf-start-options",
26300                WorkflowStartOptions::new()
26301                    .execution_timeout_seconds(30)
26302                    .run_timeout_seconds(1),
26303                json!([]),
26304            )
26305            .await
26306            .expect("workflow start");
26307
26308        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
26309        let body = server.request_body("/api/workflows");
26310        assert_eq!(body["execution_timeout_seconds"], 30);
26311        assert_eq!(body["run_timeout_seconds"], 1);
26312
26313        let invalid = client
26314            .start_workflow_with_options(
26315                "rust.timeout",
26316                "rust-timeouts",
26317                "wf-invalid-options",
26318                WorkflowStartOptions::new()
26319                    .execution_timeout_seconds(1)
26320                    .run_timeout_seconds(2),
26321                json!([]),
26322            )
26323            .await
26324            .expect_err("invalid deadline ordering");
26325        assert!(invalid
26326            .to_string()
26327            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
26328    }
26329
26330    #[tokio::test]
26331    async fn workflow_result_returns_each_typed_terminal_outcome() {
26332        let server = MockWorkerServer::start();
26333        let client = Client::builder(server.base_url())
26334            .timeout(Duration::from_secs(2))
26335            .build()
26336            .expect("client");
26337        let options = WorkflowResultOptions {
26338            poll_interval: Duration::ZERO,
26339            timeout: Duration::from_secs(1),
26340        };
26341
26342        let failed = WorkflowHandle {
26343            client: client.clone(),
26344            workflow_id: "wf-failed".to_string(),
26345            run_id: Some("run-failed".to_string()),
26346            workflow_type: "failure".to_string(),
26347        }
26348        .result(options)
26349        .await
26350        .expect_err("failed outcome");
26351        let Error::WorkflowFailed(failure) = failed else {
26352            panic!("expected WorkflowFailed");
26353        };
26354        assert_eq!(failure.workflow_id, "wf-failed");
26355        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
26356        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
26357        assert_eq!(failure.failure_category.as_deref(), Some("application"));
26358        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
26359        assert_eq!(
26360            failure.exception_class.as_deref(),
26361            Some("billing::PaymentError")
26362        );
26363        assert_eq!(failure.non_retryable, Some(true));
26364
26365        for (workflow_id, expected_kind, expected_reason) in [
26366            (
26367                "wf-cancelled",
26368                WorkflowTerminalKind::Cancelled,
26369                "cleanup requested",
26370            ),
26371            (
26372                "wf-terminated",
26373                WorkflowTerminalKind::Terminated,
26374                "forced stop",
26375            ),
26376            (
26377                "wf-timed-out",
26378                WorkflowTerminalKind::TimedOut,
26379                "run_timeout",
26380            ),
26381        ] {
26382            let error = WorkflowHandle {
26383                client: client.clone(),
26384                workflow_id: workflow_id.to_string(),
26385                run_id: None,
26386                workflow_type: "terminal".to_string(),
26387            }
26388            .result(options)
26389            .await
26390            .expect_err("typed terminal outcome");
26391            let outcome = match error {
26392                Error::WorkflowCancelled(outcome) => outcome,
26393                Error::WorkflowTerminated(outcome) => outcome,
26394                Error::WorkflowTimedOut(outcome) => outcome,
26395                other => panic!("unexpected terminal error: {other}"),
26396            };
26397            assert_eq!(outcome.kind, expected_kind);
26398            assert_eq!(outcome.workflow_id, workflow_id);
26399            assert_eq!(outcome.reason, expected_reason);
26400        }
26401
26402        let wait_timeout = WorkflowHandle {
26403            client,
26404            workflow_id: "wf-waiting".to_string(),
26405            run_id: Some("run-waiting".to_string()),
26406            workflow_type: "waiting".to_string(),
26407        }
26408        .result(WorkflowResultOptions {
26409            poll_interval: Duration::ZERO,
26410            timeout: Duration::ZERO,
26411        })
26412        .await
26413        .expect_err("client wait timeout");
26414        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
26415            panic!("expected typed client timeout");
26416        };
26417        assert_eq!(timeout.reason, "result_wait_timeout");
26418        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
26419        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
26420    }
26421
26422    #[tokio::test]
26423    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
26424        let server = MockWorkerServer::start();
26425        let client = Client::builder(server.base_url())
26426            .timeout(Duration::from_secs(2))
26427            .build()
26428            .expect("client");
26429
26430        let handle = WorkflowHandle {
26431            client,
26432            workflow_id: "wf-selected".to_string(),
26433            run_id: Some("run-selected".to_string()),
26434            workflow_type: "selected".to_string(),
26435        };
26436        let options = WorkflowResultOptions {
26437            poll_interval: Duration::ZERO,
26438            timeout: Duration::from_secs(1),
26439        };
26440
26441        let current = handle
26442            .result(options)
26443            .await
26444            .expect("instance result follows the current run");
26445        assert_eq!(current, json!("current run output"));
26446
26447        let error = handle
26448            .result_selected_run(options)
26449            .await
26450            .expect_err("the selected run is cancelled even though the current run completed");
26451
26452        let Error::WorkflowCancelled(outcome) = error else {
26453            panic!("expected selected run cancellation");
26454        };
26455        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
26456        assert_eq!(outcome.reason, "selected run cancelled");
26457        assert_eq!(
26458            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
26459            1
26460        );
26461        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
26462    }
26463
26464    #[tokio::test]
26465    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
26466        let server = MockWorkerServer::draining_polls();
26467        let client = Client::builder(server.base_url())
26468            .timeout(Duration::from_secs(2))
26469            .build()
26470            .expect("client");
26471
26472        let workflow = client
26473            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
26474            .await
26475            .expect("workflow drain response");
26476        let activity = client
26477            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
26478            .await
26479            .expect("activity drain response");
26480        let query = client
26481            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
26482            .await
26483            .expect("query drain response");
26484
26485        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
26486            assert_eq!(
26487                outcome,
26488                WorkerPollOutcome::Stop {
26489                    poll_status: Some("draining".to_string()),
26490                    reason: Some("worker_draining".to_string()),
26491                }
26492            );
26493        }
26494
26495        assert!(client
26496            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
26497            .await
26498            .expect("compatibility poll")
26499            .is_none());
26500    }
26501
26502    #[tokio::test]
26503    async fn managed_worker_honors_drain_stop_for_every_task_family() {
26504        let server = MockWorkerServer::draining_polls();
26505        let client = Client::builder(server.base_url())
26506            .timeout(Duration::from_secs(2))
26507            .build()
26508            .expect("client");
26509
26510        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
26511            .worker_id("draining-workflow-worker")
26512            .poll_timeout(Duration::ZERO);
26513        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
26514        workflow_worker
26515            .run()
26516            .await
26517            .expect("workflow drain is a clean stop");
26518
26519        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
26520            .worker_id("draining-activity-worker")
26521            .poll_timeout(Duration::ZERO);
26522        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
26523        activity_worker
26524            .run()
26525            .await
26526            .expect("activity drain is a clean stop");
26527
26528        let mut query_worker = Worker::new(client, "rust-workers")
26529            .worker_id("draining-query-worker")
26530            .poll_timeout(Duration::ZERO);
26531        query_worker.register_query("counter", "current", |_ctx, _args| async {
26532            Ok(Value::Null)
26533        });
26534        query_worker
26535            .run()
26536            .await
26537            .expect("query drain is a clean stop");
26538    }
26539
26540    #[tokio::test]
26541    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
26542        let server = MockWorkerServer::start();
26543        let client = Client::builder(server.base_url())
26544            .timeout(Duration::from_secs(2))
26545            .build()
26546            .expect("client");
26547
26548        let details: Value = serde_json::from_str(include_str!(
26549            "../tests/fixtures/activity-heartbeat-progress.json"
26550        ))
26551        .expect("heartbeat progress fixture");
26552        // Every individual field fits Server's progress contract, while the
26553        // obsolete encoded envelope exceeded its 191-character string limit.
26554        assert!(
26555            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
26556                .unwrap()["blob"]
26557                .as_str()
26558                .unwrap()
26559                .len()
26560                > 191
26561        );
26562        let heartbeat = client
26563            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
26564            .await
26565            .expect("cancellation heartbeat");
26566        assert!(heartbeat.cancel_requested);
26567        assert!(heartbeat.should_stop());
26568        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
26569        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
26570        let heartbeat_body =
26571            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
26572        assert_eq!(heartbeat_body["details"], details);
26573        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
26574        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
26575
26576        let error = client
26577            .complete_activity_task(
26578                "activity-cancel",
26579                "attempt-cancel",
26580                "rust-worker",
26581                json!({"late":true}),
26582                DEFAULT_CODEC,
26583            )
26584            .await
26585            .expect_err("late completion must be refused");
26586        assert!(activity_task_rejection_is_final(&error));
26587        let Error::ActivityTaskRejected(rejection) = error else {
26588            panic!("expected typed activity rejection");
26589        };
26590        assert_eq!(rejection.status, 409);
26591        assert_eq!(rejection.reason, "run_cancelled");
26592        assert!(rejection.cancel_requested);
26593        assert_eq!(rejection.can_continue, Some(false));
26594    }
26595
26596    #[tokio::test]
26597    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
26598        let server = MockWorkerServer::cancelled_activity();
26599        let client = Client::builder(server.base_url())
26600            .timeout(Duration::from_secs(2))
26601            .build()
26602            .expect("client");
26603        let cancellation_observed = Arc::new(AtomicBool::new(false));
26604        let observed = Arc::clone(&cancellation_observed);
26605        let mut worker = Worker::new(client.clone(), "rust-workers")
26606            .worker_id("rust-cancel-worker")
26607            .poll_timeout(Duration::from_millis(10));
26608        worker.register_activity("cancel-aware", move |ctx, _args| {
26609            let observed = Arc::clone(&observed);
26610            async move {
26611                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
26612                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
26613                Ok(json!({"late":"completion"}))
26614            }
26615        });
26616
26617        assert_eq!(
26618            worker.run_once().await.expect("cancelled attempt handled"),
26619            1
26620        );
26621        assert!(cancellation_observed.load(Ordering::SeqCst));
26622        assert_eq!(
26623            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
26624            1
26625        );
26626
26627        let mut restarted = Worker::new(client, "rust-workers")
26628            .worker_id("rust-cancel-worker-restarted")
26629            .poll_timeout(Duration::from_millis(10));
26630        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
26631        assert_eq!(
26632            restarted
26633                .run_once()
26634                .await
26635                .expect("replacement worker continues polling"),
26636            0
26637        );
26638    }
26639
26640    #[tokio::test]
26641    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
26642        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"}"#;
26643        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
26644        let client = Client::builder(server.base_url())
26645            .timeout(Duration::from_secs(2))
26646            .build()
26647            .expect("client");
26648
26649        let direct_error = client
26650            .complete_workflow_task(
26651                "workflow-timeout-task",
26652                "timeout-worker",
26653                3,
26654                vec![json!({
26655                    "type": "complete_workflow",
26656                    "result": fixture_envelope(Value::Null)
26657                })],
26658            )
26659            .await
26660            .expect_err("the low-level client preserves the completion rejection");
26661        let Error::Http { status, body } = direct_error else {
26662            panic!("expected the original HTTP completion rejection");
26663        };
26664        assert_eq!(status, reqwest::StatusCode::CONFLICT);
26665        assert_eq!(
26666            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
26667            "run_timed_out"
26668        );
26669
26670        let mut worker = Worker::new(client, "rust-workers")
26671            .worker_id("timeout-worker")
26672            .poll_timeout(Duration::from_millis(10));
26673        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26674            Ok(json!({"late": "result"}))
26675        });
26676
26677        assert_eq!(
26678            worker
26679                .run_once()
26680                .await
26681                .expect("authoritative selected-run timeout settles the tick"),
26682            1
26683        );
26684        assert_eq!(
26685            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
26686            2,
26687            "both the direct client proof and managed worker must see the rejection"
26688        );
26689    }
26690
26691    #[tokio::test]
26692    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
26693        for (name, status, response) in [
26694            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
26695            (
26696                "command was recorded",
26697                "409 Conflict",
26698                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26699            ),
26700            (
26701                "lease conflict",
26702                "409 Conflict",
26703                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
26704            ),
26705            (
26706                "nonterminal run",
26707                "409 Conflict",
26708                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
26709            ),
26710            (
26711                "different selected run",
26712                "409 Conflict",
26713                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"}"#,
26714            ),
26715            (
26716                "different task attempt",
26717                "409 Conflict",
26718                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26719            ),
26720            (
26721                "authentication failure",
26722                "401 Unauthorized",
26723                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26724            ),
26725            (
26726                "authorization failure",
26727                "403 Forbidden",
26728                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26729            ),
26730            (
26731                "protocol failure",
26732                "400 Bad Request",
26733                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
26734            ),
26735            (
26736                "malformed command",
26737                "422 Unprocessable Entity",
26738                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26739            ),
26740            (
26741                "transient server failure",
26742                "503 Service Unavailable",
26743                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26744            ),
26745        ] {
26746            let server = MockWorkerServer::workflow_completion(status, response);
26747            let client = Client::builder(server.base_url())
26748                .timeout(Duration::from_secs(2))
26749                .build()
26750                .expect("client");
26751            let mut worker = Worker::new(client, "rust-workers")
26752                .worker_id("timeout-worker")
26753                .poll_timeout(Duration::from_millis(10));
26754            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26755                Ok(json!({"late": "result"}))
26756            });
26757
26758            let error = worker
26759                .run_once()
26760                .await
26761                .expect_err(&format!("{name} must remain an error"));
26762            assert!(
26763                matches!(error, Error::Http { .. } | Error::Protocol(_)),
26764                "{name} returned an unexpected error variant: {error}"
26765            );
26766        }
26767    }
26768
26769    #[tokio::test]
26770    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
26771        let server = MockWorkerServer::start();
26772        let client = Client::builder(server.base_url())
26773            .worker_token(Some("worker-secret".to_string()))
26774            .namespace("orders")
26775            .timeout(Duration::from_secs(2))
26776            .build()
26777            .expect("client");
26778        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
26779
26780        let result = client
26781            .deregister_worker_registration("worker/α space")
26782            .await
26783            .expect("deregister worker registration");
26784
26785        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
26786        assert_eq!(
26787            server.worker_protocol_for(path).as_deref(),
26788            Some(WORKER_PROTOCOL_VERSION)
26789        );
26790        assert_eq!(server.control_protocol_for(path), None);
26791        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
26792        assert_eq!(
26793            server.authorization_for(path).as_deref(),
26794            Some("Bearer worker-secret")
26795        );
26796        assert_eq!(
26797            result,
26798            WorkerDeregistrationEnvelope {
26799                worker_id: "deregistered-worker".to_string(),
26800                outcome: "deregistered".to_string(),
26801                recovered_workflow_task_count: 2,
26802            }
26803        );
26804    }
26805
26806    #[tokio::test]
26807    async fn low_level_registration_rejects_update_validators_before_transport() {
26808        let server = MockWorkerServer::start();
26809        let client = Client::builder(server.base_url())
26810            .timeout(Duration::from_secs(2))
26811            .build()
26812            .expect("client");
26813
26814        for update_validators in [json!(["approve"]), json!("approve")] {
26815            let error = client
26816                .register_worker_with_command_contracts(
26817                    "validator-claiming-worker",
26818                    "rust-workers",
26819                    vec!["orders".to_string()],
26820                    vec![],
26821                    1,
26822                    1,
26823                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
26824                    json!({
26825                        "orders": {
26826                            "queries": ["current"],
26827                            "updates": ["approve"],
26828                            "update_validators": update_validators,
26829                        },
26830                    }),
26831                )
26832                .await
26833                .expect_err("unsupported validator claims must fail before registration");
26834
26835            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
26836                panic!("expected typed unsupported-validator failure");
26837            };
26838            assert_eq!(workflow_type, "orders");
26839        }
26840        assert_eq!(server.request_count("/api/worker/register"), 0);
26841    }
26842
26843    #[tokio::test]
26844    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
26845        let server = MockWorkerServer::start();
26846        let client = Client::builder(server.base_url())
26847            .timeout(Duration::from_secs(2))
26848            .build()
26849            .expect("client");
26850        let mut worker = Worker::new(client, "rust-workers");
26851        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
26852        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
26853        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
26854        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
26855        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
26856        worker
26857            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
26858            .expect("declare workflow signals");
26859
26860        worker.register().await.expect("register handler contracts");
26861
26862        let declaration =
26863            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
26864        let expected_contracts = json!([
26865            {
26866                "name": "a-avro",
26867                "parameters": [{
26868                    "name": "args", "position": 0, "required": false,
26869                    "variadic": true, "type": null, "allows_null": true,
26870                    "default_available": false, "default": null,
26871                }],
26872            },
26873            {
26874                "name": "z-json",
26875                "parameters": [{
26876                    "name": "args", "position": 0, "required": false,
26877                    "variadic": true, "type": null, "allows_null": true,
26878                    "default_available": false, "default": null,
26879                }],
26880            },
26881        ]);
26882        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
26883        assert_eq!(declaration["query_contracts"], expected_contracts);
26884        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
26885        assert_eq!(declaration["update_contracts"], expected_contracts);
26886        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
26887        assert_eq!(declaration["signal_contracts"], expected_contracts);
26888        assert_eq!(declaration["update_validators"], json!([]));
26889    }
26890
26891    #[tokio::test]
26892    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
26893        let server = MockWorkerServer::start();
26894        let client = Client::new(server.base_url()).expect("client");
26895        let mut worker = Worker::new(client, "rust-workers");
26896        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
26897        assert!(worker
26898            .declare_workflow_signals("missing", &["finish"])
26899            .is_err());
26900        worker
26901            .declare_workflow_signals("orders", &["finish"])
26902            .unwrap();
26903        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
26904            assert!(worker.declare_workflow_signals("orders", names).is_err());
26905        }
26906        worker.register().await.unwrap();
26907        assert_eq!(
26908            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
26909                ["signals"],
26910            json!(["finish"])
26911        );
26912        worker.declare_workflow_signals("orders", &[]).unwrap();
26913        worker.register().await.unwrap();
26914        let registrations = server.request_bodies("/api/worker/register");
26915        assert_eq!(
26916            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
26917            json!([])
26918        );
26919        assert_eq!(
26920            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
26921            json!([])
26922        );
26923    }
26924
26925    #[tokio::test]
26926    async fn low_level_registration_preserves_query_and_update_contracts() {
26927        let server = MockWorkerServer::start();
26928        let client = Client::builder(server.base_url())
26929            .timeout(Duration::from_secs(2))
26930            .build()
26931            .expect("client");
26932        let contracts = json!({
26933            "orders": {
26934                "queries": ["current"],
26935                "updates": ["approve"],
26936                "update_validators": [],
26937            },
26938            "payments": {
26939                "queries": ["status"],
26940                "updates": ["capture"],
26941            },
26942        });
26943
26944        client
26945            .register_worker_with_command_contracts(
26946                "command-worker",
26947                "rust-workers",
26948                vec!["orders".to_string(), "payments".to_string()],
26949                vec![],
26950                1,
26951                1,
26952                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
26953                contracts.clone(),
26954            )
26955            .await
26956            .expect("query and update contracts must remain supported");
26957
26958        assert_eq!(
26959            server.request_body("/api/worker/register")["workflow_command_contracts"],
26960            contracts
26961        );
26962        assert!(server
26963            .request_body("/api/worker/register")
26964            .get("workflow_definition_fingerprints")
26965            .is_none());
26966    }
26967
26968    #[tokio::test]
26969    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
26970        let server = MockWorkerServer::start();
26971        let client = Client::builder(server.base_url())
26972            .timeout(Duration::from_secs(2))
26973            .build()
26974            .expect("client");
26975        let mut worker = Worker::new(client.clone(), "rust-workers");
26976        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
26977
26978        assert!(worker
26979            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
26980            .is_err());
26981        assert!(worker
26982            .set_workflow_definition_sources("orders", &[])
26983            .is_err());
26984        worker
26985            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
26986            .expect("embed workflow source");
26987        worker.register().await.expect("register worker");
26988        let first = server.request_bodies("/api/worker/register")[0]
26989            ["workflow_definition_fingerprints"]["orders"]
26990            .as_str()
26991            .expect("source-backed fingerprint")
26992            .to_string();
26993        assert!(first.starts_with("sha256:"));
26994
26995        worker
26996            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
26997            .expect("change embedded helper source");
26998        worker.register().await.expect("register changed source");
26999        let changed = server.request_bodies("/api/worker/register")[1]
27000            ["workflow_definition_fingerprints"]["orders"]
27001            .as_str()
27002            .expect("changed fingerprint")
27003            .to_string();
27004        assert_ne!(first, changed);
27005
27006        let mut replacement =
27007            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
27008        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27009        replacement
27010            .register()
27011            .await
27012            .expect("register replacement handler");
27013        assert_eq!(
27014            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
27015            json!({})
27016        );
27017    }
27018
27019    #[tokio::test]
27020    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
27021        let server = MockWorkerServer::start();
27022        let control_only = Client::builder(server.base_url())
27023            .control_token(Some("control-secret".to_string()))
27024            .build()
27025            .expect("control client");
27026
27027        let error = control_only
27028            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27029            .await
27030            .expect_err("control token must not authorize a worker request");
27031        assert!(matches!(
27032            error,
27033            Error::MissingRoleCredentials { role: "worker", .. }
27034        ));
27035        assert_eq!(server.request_count("/api/worker/register"), 0);
27036
27037        let worker_only = Client::builder(server.base_url())
27038            .worker_token(Some("worker-secret".to_string()))
27039            .build()
27040            .expect("worker client");
27041        let error = worker_only
27042            .health()
27043            .await
27044            .expect_err("worker token must not authorize a control request");
27045        assert!(matches!(
27046            error,
27047            Error::MissingRoleCredentials {
27048                role: "control",
27049                ..
27050            }
27051        ));
27052        assert_eq!(server.request_count("/api/health"), 0);
27053    }
27054
27055    #[tokio::test]
27056    async fn shared_token_supports_worker_and_control_planes() {
27057        let server = MockWorkerServer::start();
27058        let client = Client::builder(server.base_url())
27059            .token(Some("shared-secret".to_string()))
27060            .build()
27061            .expect("client");
27062
27063        client.health().await.expect("control request");
27064        client
27065            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27066            .await
27067            .expect("worker request");
27068
27069        assert_eq!(
27070            server.authorization_for("/api/health").as_deref(),
27071            Some("Bearer shared-secret")
27072        );
27073        assert_eq!(
27074            server.control_protocol_for("/api/health").as_deref(),
27075            Some(CONTROL_PLANE_VERSION)
27076        );
27077        assert_eq!(
27078            server.authorization_for("/api/worker/register").as_deref(),
27079            Some("Bearer shared-secret")
27080        );
27081        assert_eq!(
27082            server
27083                .worker_protocol_for("/api/worker/register")
27084                .as_deref(),
27085            Some(WORKER_PROTOCOL_VERSION)
27086        );
27087    }
27088
27089    #[tokio::test]
27090    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
27091        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
27092        let server = MockWorkerServer::start();
27093        let client = Client::builder(server.base_url())
27094            .timeout(Duration::from_secs(2))
27095            .build()
27096            .expect("client");
27097
27098        client
27099            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
27100            .await
27101            .expect("register");
27102        client
27103            .heartbeat_worker("capture-worker", 1, 1)
27104            .await
27105            .expect("heartbeat");
27106        client
27107            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27108            .await
27109            .expect("workflow poll");
27110        client
27111            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27112            .await
27113            .expect("activity poll");
27114
27115        for path in [
27116            "/api/worker/register",
27117            "/api/worker/heartbeat",
27118            "/api/worker/workflow-tasks/poll",
27119            "/api/worker/activity-tasks/poll",
27120        ] {
27121            assert_eq!(
27122                server.worker_protocol_for(path).as_deref(),
27123                Some(WORKER_PROTOCOL_VERSION),
27124                "unexpected protocol for {path}"
27125            );
27126        }
27127
27128        assert_eq!(
27129            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
27130            1
27131        );
27132        assert_eq!(
27133            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
27134            500
27135        );
27136        assert_eq!(
27137            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
27138            1
27139        );
27140        assert!(
27141            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
27142                .as_str()
27143                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
27144        );
27145        assert!(
27146            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
27147                .as_str()
27148                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
27149        );
27150        let registration = server.request_body("/api/worker/register");
27151        for optional in [
27152            "cooperative_cancellation",
27153            "local_activities",
27154            "worker_sessions",
27155            "sticky_execution",
27156        ] {
27157            assert!(!registration["capabilities"]
27158                .as_array()
27159                .is_some_and(|capabilities| capabilities
27160                    .iter()
27161                    .any(|capability| capability.as_str() == Some(optional))));
27162        }
27163    }
27164
27165    #[tokio::test]
27166    async fn explicit_previous_worker_protocol_preserves_headers() {
27167        let server = MockWorkerServer::start();
27168        let client = Client::builder(server.base_url())
27169            .worker_protocol_version(WorkerProtocolVersion::V119)
27170            .timeout(Duration::from_secs(2))
27171            .build()
27172            .expect("client");
27173        client
27174            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
27175            .await
27176            .expect("register");
27177        client
27178            .heartbeat_worker("legacy-worker", 1, 1)
27179            .await
27180            .expect("heartbeat");
27181        client
27182            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
27183            .await
27184            .expect("workflow poll");
27185        client
27186            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
27187            .await
27188            .expect("activity poll");
27189        client
27190            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
27191            .await
27192            .expect("query poll");
27193        client
27194            .deregister_worker_registration("legacy-worker")
27195            .await
27196            .expect("deregister");
27197        for path in [
27198            "/api/worker/register",
27199            "/api/worker/heartbeat",
27200            "/api/worker/workflow-tasks/poll",
27201            "/api/worker/activity-tasks/poll",
27202            "/api/worker/query-tasks/poll",
27203            "/api/worker/registrations/legacy-worker",
27204        ] {
27205            assert_eq!(
27206                server.worker_protocol_for(path).as_deref(),
27207                Some("1.19"),
27208                "{path}"
27209            );
27210            assert_eq!(server.control_protocol_for(path), None, "{path}");
27211        }
27212    }
27213
27214    #[tokio::test]
27215    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
27216        let server = MockWorkerServer::start();
27217        let client = Client::builder(server.base_url())
27218            .worker_protocol_version(WorkerProtocolVersion::V119)
27219            .timeout(Duration::from_secs(2))
27220            .build()
27221            .expect("client");
27222        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
27223        let error = worker
27224            .register()
27225            .await
27226            .expect_err("legacy cooperation must be refused");
27227        assert!(matches!(
27228            error,
27229            Error::CooperativeCancellationUnavailable(_)
27230        ));
27231        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
27232    }
27233
27234    #[tokio::test]
27235    async fn query_task_endpoints_send_the_selected_worker_protocol() {
27236        let server = MockWorkerServer::start();
27237        let client = Client::builder(server.base_url())
27238            .timeout(Duration::from_secs(2))
27239            .build()
27240            .expect("client");
27241
27242        client
27243            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27244            .await
27245            .expect("query poll");
27246        client
27247            .complete_query_task(
27248                "query-capture",
27249                "capture-worker",
27250                1,
27251                json!(8),
27252                DEFAULT_CODEC,
27253            )
27254            .await
27255            .expect("query complete");
27256        client
27257            .fail_query_task(
27258                "query-capture",
27259                "capture-worker",
27260                1,
27261                "failed",
27262                "query_rejected",
27263                "QueryFailed",
27264            )
27265            .await
27266            .expect("query fail");
27267
27268        for path in [
27269            "/api/worker/query-tasks/poll",
27270            "/api/worker/query-tasks/query-capture/complete",
27271            "/api/worker/query-tasks/query-capture/fail",
27272        ] {
27273            assert_eq!(
27274                server.worker_protocol_for(path).as_deref(),
27275                Some(WORKER_PROTOCOL_VERSION),
27276                "unexpected protocol for {path}"
27277            );
27278        }
27279
27280        assert_eq!(
27281            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
27282            1
27283        );
27284        assert!(
27285            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
27286                .as_str()
27287                .is_some_and(|id| id.starts_with("rust-query-poll-"))
27288        );
27289    }
27290
27291    #[tokio::test]
27292    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
27293        let server = MockWorkerServer::transient_worker_failures();
27294        let client = Client::builder(server.base_url())
27295            .timeout(Duration::from_secs(2))
27296            .build()
27297            .expect("client");
27298
27299        client
27300            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27301            .await
27302            .expect("workflow poll retry");
27303        client
27304            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27305            .await
27306            .expect("activity poll retry");
27307        client
27308            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27309            .await
27310            .expect("query poll retry");
27311
27312        for path in [
27313            "/api/worker/workflow-tasks/poll",
27314            "/api/worker/activity-tasks/poll",
27315            "/api/worker/query-tasks/poll",
27316        ] {
27317            let bodies = server.request_bodies(path);
27318            assert_eq!(bodies.len(), 2, "{path} must be retried once");
27319            assert_eq!(
27320                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
27321                "{path} must preserve the request binding across retry"
27322            );
27323        }
27324    }
27325
27326    #[tokio::test]
27327    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
27328        let server = MockWorkerServer::consecutive_poll_failures(2);
27329        let client = Client::builder(server.base_url())
27330            .timeout(Duration::from_secs(2))
27331            .build()
27332            .expect("client");
27333        let mut worker = Worker::new(client, "capture")
27334            .worker_id("capture-worker")
27335            .poll_timeout(Duration::from_millis(10))
27336            .retry_policy(WorkerRetryPolicy {
27337                max_retries: 2,
27338                initial_backoff: Duration::from_millis(1),
27339                max_backoff: Duration::from_millis(1),
27340            });
27341        worker.register_workflow(
27342            "capture.workflow",
27343            |_ctx, _input| async move { Ok(Value::Null) },
27344        );
27345        worker.register_activity(
27346            "capture.activity",
27347            |_ctx, _input| async move { Ok(Value::Null) },
27348        );
27349        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
27350            Ok(Value::Null)
27351        });
27352
27353        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
27354
27355        for path in [
27356            "/api/worker/workflow-tasks/poll",
27357            "/api/worker/activity-tasks/poll",
27358            "/api/worker/query-tasks/poll",
27359        ] {
27360            let bodies = server.request_bodies(path);
27361            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
27362            assert!(
27363                bodies
27364                    .iter()
27365                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
27366                "{path} must preserve one request binding across every retry"
27367            );
27368        }
27369    }
27370
27371    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
27372        let reason = if unavailable {
27373            "storage_admission_unavailable"
27374        } else {
27375            "storage_pressure"
27376        };
27377        let mut body = json!({
27378            "reason": reason,
27379            "storage_state": if unavailable { "fenced" } else { "draining" },
27380            "retryable": true,
27381            "retry_after_seconds": 1,
27382        });
27383        if !mid_poll {
27384            body["request_admitted"] = json!(false);
27385        }
27386        if let Some(id) = poll_id {
27387            body["task"] = Value::Null;
27388            body["poll_status"] = json!(reason);
27389            body["poll_request_id"] = json!(id);
27390            body["retry_same_poll_request_id"] = json!(true);
27391            body["claim_admitted"] = json!(false);
27392        }
27393        body
27394    }
27395
27396    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
27397        let operation = match path {
27398            "/api/worker/register" => "register_worker",
27399            "/api/worker/heartbeat" => "heartbeat_worker",
27400            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
27401            "/api/worker/activity-tasks/poll" => "poll_activity_task",
27402            "/api/worker/query-tasks/poll" => "poll_query_task",
27403            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
27404            _ => return None,
27405        };
27406        let request: Value = serde_json::from_str(request).ok()?;
27407        let mut response = json!({
27408            "reason": "backend_unavailable",
27409            "operation": operation,
27410            "outcome": "unknown",
27411            "retryable": true,
27412            "retry_after_seconds": 1,
27413            "worker_id": request["worker_id"],
27414            "task_queue": request.get("task_queue"),
27415        });
27416        if path.ends_with("/poll") {
27417            response["task"] = Value::Null;
27418            response["poll_status"] = json!("backend_unavailable");
27419            response["poll_request_id"] = request["poll_request_id"].clone();
27420            response["retry_same_poll_request_id"] = json!(true);
27421        }
27422        Some(response)
27423    }
27424
27425    fn backend_retry_override(
27426        path: &str,
27427        request: &str,
27428        number: usize,
27429    ) -> Option<(&'static str, String)> {
27430        if number > 8 {
27431            return None;
27432        }
27433        Some((
27434            "503 Service Unavailable",
27435            backend_refusal(path, request)?.to_string(),
27436        ))
27437    }
27438
27439    fn backend_unavailable_override(
27440        path: &str,
27441        request: &str,
27442        _number: usize,
27443    ) -> Option<(&'static str, String)> {
27444        Some((
27445            "503 Service Unavailable",
27446            backend_refusal(path, request)?.to_string(),
27447        ))
27448    }
27449
27450    fn storage_worker(server: &MockWorkerServer) -> Worker {
27451        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
27452            .worker_id("storage-worker")
27453            .retry_policy(WorkerRetryPolicy {
27454                max_retries: 1,
27455                initial_backoff: Duration::from_millis(1),
27456                max_backoff: Duration::from_millis(1),
27457            })
27458    }
27459
27460    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
27461        let requests = server.requests.lock().expect("requests");
27462        let bodies: Vec<_> = requests
27463            .iter()
27464            .filter(|request| request.path == path)
27465            .map(|request| &request.body)
27466            .collect();
27467        assert_eq!(bodies.len(), count, "{path}");
27468        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
27469    }
27470
27471    #[test]
27472    fn backend_recovery_requires_the_explicit_worker_contract() {
27473        for (path, operation) in [
27474            ("/worker/register", "register_worker"),
27475            ("/worker/heartbeat", "heartbeat_worker"),
27476            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
27477            ("/worker/activity-tasks/poll", "poll_activity_task"),
27478            ("/worker/query-tasks/poll", "poll_query_task"),
27479            (
27480                "/worker/update-validation-tasks/poll",
27481                "poll_update_validation_task",
27482            ),
27483        ] {
27484            let poll_id = path.ends_with("/poll").then_some("same-poll");
27485            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
27486            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
27487                .expect("worker operation");
27488            assert_eq!(body["operation"], operation);
27489            let error = Error::Http {
27490                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27491                body: body.to_string(),
27492            };
27493            assert_eq!(
27494                worker_backend_unavailable_retry_after(&error, path, poll_id),
27495                Some(Duration::from_secs(1))
27496            );
27497            assert!(!worker_operation_is_retryable(&error));
27498            for (field, value) in [
27499                ("operation", json!("wrong_operation")),
27500                ("outcome", json!("completed")),
27501                ("retryable", json!(false)),
27502                ("retry_after_seconds", json!(0)),
27503                ("worker_id", json!("")),
27504            ] {
27505                let mut invalid = body.clone();
27506                invalid[field] = value;
27507                let error = Error::Http {
27508                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27509                    body: invalid.to_string(),
27510                };
27511                assert!(
27512                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
27513                    "{path}: {field}"
27514                );
27515                assert!(!worker_operation_is_retryable(&error));
27516            }
27517            if let Some(poll_id) = poll_id {
27518                for (field, value) in [
27519                    ("poll_request_id", json!("wrong-poll")),
27520                    ("poll_status", json!("empty")),
27521                    ("task", json!({"task_id":"claimed"})),
27522                    ("retry_same_poll_request_id", json!(false)),
27523                ] {
27524                    let mut invalid = body.clone();
27525                    invalid[field] = value;
27526                    let error = Error::Http {
27527                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27528                        body: invalid.to_string(),
27529                    };
27530                    assert!(
27531                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
27532                            .is_none(),
27533                        "{path}: {field}"
27534                    );
27535                }
27536            }
27537            let error = Error::Http {
27538                status: reqwest::StatusCode::UNAUTHORIZED,
27539                body: body.to_string(),
27540            };
27541            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
27542            assert!(!worker_operation_is_retryable(&error));
27543        }
27544    }
27545
27546    #[tokio::test]
27547    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
27548        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27549            request_override: Some(backend_retry_override),
27550            ..MockWorkerBehavior::default()
27551        });
27552        let mut worker =
27553            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27554        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27555        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
27556        worker.register_query("backend.workflow", "state", |_, _| async {
27557            Ok(Value::Null)
27558        });
27559        worker.register().await.expect("registration recovery");
27560        worker
27561            .client
27562            .heartbeat_worker("storage-worker", 1, 1)
27563            .await
27564            .expect("heartbeat recovery");
27565        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
27566        for path in [
27567            "/api/worker/register",
27568            "/api/worker/heartbeat",
27569            "/api/worker/workflow-tasks/poll",
27570            "/api/worker/activity-tasks/poll",
27571            "/api/worker/query-tasks/poll",
27572        ] {
27573            assert_identical_requests(&server, path, 9);
27574        }
27575    }
27576
27577    #[tokio::test]
27578    async fn backend_recovery_wait_stops_with_worker() {
27579        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27580            request_override: Some(backend_unavailable_override),
27581            ..MockWorkerBehavior::default()
27582        });
27583        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
27584            max_retries: 1,
27585            initial_backoff: Duration::from_secs(2),
27586            max_backoff: Duration::from_secs(2),
27587        });
27588        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27589        let started = tokio::time::Instant::now();
27590        let _ = tokio::time::timeout(
27591            Duration::from_secs(1),
27592            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
27593        )
27594        .await
27595        .expect("shutdown interrupts backend wait");
27596        assert!(started.elapsed() < Duration::from_secs(1));
27597        assert!(server.request_count("/api/worker/register") >= 1);
27598    }
27599
27600    #[test]
27601    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
27602        for unavailable in [false, true] {
27603            for mid_poll in [false, true] {
27604                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
27605                let error = Error::Http {
27606                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27607                    body: body.to_string(),
27608                };
27609                assert_eq!(
27610                    worker_storage_admission_retry_after(&error, Some("same-poll")),
27611                    Some(Duration::from_secs(1))
27612                );
27613                assert!(
27614                    !worker_operation_is_retryable(&error),
27615                    "storage is not a bounded generic retry"
27616                );
27617                for (field, value) in [
27618                    ("poll_request_id", json!("wrong-poll")),
27619                    ("task", json!({"task_id":"claimed"})),
27620                    ("retryable", json!(false)),
27621                    ("retry_after_seconds", json!(0)),
27622                    ("retry_after_seconds", json!(true)),
27623                    ("retry_after_seconds", json!(1.0)),
27624                    ("storage_state", json!("normal")),
27625                    ("poll_status", json!("empty")),
27626                    ("claim_admitted", json!(true)),
27627                    ("retry_same_poll_request_id", json!(false)),
27628                    ("request_admitted", json!(true)),
27629                ] {
27630                    let mut invalid = body.clone();
27631                    invalid[field] = value;
27632                    let error = Error::Http {
27633                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27634                        body: invalid.to_string(),
27635                    };
27636                    assert!(
27637                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
27638                        "{field}"
27639                    );
27640                }
27641            }
27642        }
27643        let body = storage_refusal(None, false, false);
27644        let error = Error::Http {
27645            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27646            body: body.to_string(),
27647        };
27648        assert!(worker_storage_admission_retry_after(&error, None).is_some());
27649        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
27650        let error = Error::Http {
27651            status: reqwest::StatusCode::FORBIDDEN,
27652            body: body.to_string(),
27653        };
27654        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27655        let body = storage_refusal(None, false, true);
27656        let error = Error::Http {
27657            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27658            body: body.to_string(),
27659        };
27660        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27661    }
27662
27663    #[tokio::test]
27664    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
27665        for unavailable in [false, true] {
27666            for mid_poll in [false, true] {
27667                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27668                    poll_failures_per_path: 1,
27669                    storage_refusals: 7,
27670                    storage_path: Some("/poll"),
27671                    storage_unavailable: unavailable,
27672                    storage_mid_poll: mid_poll,
27673                    ..MockWorkerBehavior::default()
27674                });
27675                let mut worker = storage_worker(&server);
27676                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
27677                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
27678                for path in [
27679                    "/api/worker/workflow-tasks/poll",
27680                    "/api/worker/activity-tasks/poll",
27681                    "/api/worker/query-tasks/poll",
27682                ] {
27683                    assert_identical_requests(&server, path, 9);
27684                }
27685            }
27686        }
27687    }
27688
27689    #[tokio::test]
27690    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
27691        struct CountedBody(Arc<AtomicUsize>);
27692        impl Serialize for CountedBody {
27693            fn serialize<S: Serializer>(
27694                &self,
27695                serializer: S,
27696            ) -> std::result::Result<S::Ok, S::Error> {
27697                let count = self.0.fetch_add(1, Ordering::SeqCst);
27698                json!({"serialization":count,"lease_owner":"worker","attempt":7})
27699                    .serialize(serializer)
27700            }
27701        }
27702        for path in [
27703            "/api/worker/register",
27704            "/api/worker/heartbeat",
27705            "/api/worker/workflow-tasks/storage-task/complete",
27706            "/api/worker/workflow-tasks/storage-task/fail",
27707            "/api/worker/activity-tasks/storage-task/complete",
27708            "/api/worker/activity-tasks/storage-task/fail",
27709            "/api/worker/activity-tasks/storage-task/heartbeat",
27710            "/api/worker/query-tasks/storage-task/complete",
27711            "/api/worker/query-tasks/storage-task/fail",
27712        ] {
27713            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27714                storage_refusals: 7,
27715                storage_path: Some(path),
27716                ..MockWorkerBehavior::default()
27717            });
27718            let worker =
27719                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27720            let calls = Arc::new(AtomicUsize::new(0));
27721            let _: Value = worker
27722                .client
27723                .request_json(
27724                    reqwest::Method::POST,
27725                    &path[4..],
27726                    RequestProtocol::DefaultWorker,
27727                    Some(&CountedBody(Arc::clone(&calls))),
27728                )
27729                .await
27730                .expect("prepared request recovery");
27731            assert_eq!(calls.load(Ordering::SeqCst), 1);
27732            assert_identical_requests(&server, path, 8);
27733        }
27734        for worker_scope in [false, true] {
27735            let path = if worker_scope {
27736                "/api/health"
27737            } else {
27738                "/api/worker/register"
27739            };
27740            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27741                storage_refusals: usize::MAX,
27742                storage_path: Some(path),
27743                ..MockWorkerBehavior::default()
27744            });
27745            let worker = storage_worker(&server);
27746            let client = worker.client.clone();
27747            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
27748            let error = if worker_scope {
27749                worker
27750                    .client
27751                    .health()
27752                    .await
27753                    .expect_err("control plane is not retried")
27754            } else {
27755                client
27756                    .request_json::<Value, Value>(
27757                        reqwest::Method::POST,
27758                        "/worker/register",
27759                        RequestProtocol::DefaultWorker,
27760                        Some(&json!({})),
27761                    )
27762                    .await
27763                    .expect_err("direct client is not retried")
27764            };
27765            assert!(worker_storage_admission_body(&error).is_some());
27766            assert_eq!(server.request_count(path), 1);
27767        }
27768    }
27769
27770    #[tokio::test]
27771    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
27772        for fail in [false, true] {
27773            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27774                storage_activity: true,
27775                storage_refusals: 7,
27776                storage_path: Some("/storage-activity/"),
27777                ..MockWorkerBehavior::default()
27778            });
27779            let mut worker = storage_worker(&server);
27780            let calls = Arc::new(AtomicUsize::new(0));
27781            let observed = Arc::clone(&calls);
27782            worker.register_activity("storage.activity", move |ctx, _| {
27783                let calls = Arc::clone(&observed);
27784                async move {
27785                    calls.fetch_add(1, Ordering::SeqCst);
27786                    ctx.heartbeat(json!({"step":2})).await?;
27787                    if fail {
27788                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
27789                    } else {
27790                        Ok(json!({"receipt":true}))
27791                    }
27792                }
27793            });
27794            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
27795            assert_eq!(calls.load(Ordering::SeqCst), 1);
27796            assert_identical_requests(
27797                &server,
27798                "/api/worker/activity-tasks/storage-activity/heartbeat",
27799                8,
27800            );
27801            let suffix = if fail { "fail" } else { "complete" };
27802            assert_identical_requests(
27803                &server,
27804                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
27805                8,
27806            );
27807            let other = if fail { "complete" } else { "fail" };
27808            assert_eq!(
27809                server.request_count(&format!(
27810                    "/api/worker/activity-tasks/storage-activity/{other}"
27811                )),
27812                0
27813            );
27814        }
27815    }
27816
27817    #[tokio::test]
27818    async fn storage_waits_are_interruptible_without_false_activity_failure() {
27819        for path in [
27820            "/api/worker/register",
27821            "/api/worker/heartbeat",
27822            "/api/worker/activity-tasks/poll",
27823            "/api/worker/activity-tasks/storage-activity/heartbeat",
27824            "/api/worker/activity-tasks/storage-activity/complete",
27825        ] {
27826            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27827                storage_activity: true,
27828                storage_refusals: usize::MAX,
27829                storage_path: Some(path),
27830                ..MockWorkerBehavior::default()
27831            });
27832            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
27833            worker.register_activity("storage.activity", |ctx, _| async move {
27834                ctx.heartbeat(json!({"step":2})).await?;
27835                Ok(json!({"receipt":true}))
27836            });
27837            let shutdown = async {
27838                while server.request_count(path) == 0 {
27839                    tokio::time::sleep(Duration::from_millis(1)).await;
27840                }
27841            };
27842            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
27843                .await
27844                .expect("shutdown interrupts admission");
27845            assert!(
27846                result.is_err(),
27847                "a refused operation must not appear acknowledged: {path}, {result:?}"
27848            );
27849            assert_eq!(server.request_count(path), 1);
27850            assert_eq!(
27851                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
27852                0
27853            );
27854            assert_eq!(
27855                server.request_count("/api/worker/registrations/mock-worker"),
27856                usize::from(!path.ends_with("/register"))
27857            );
27858        }
27859    }
27860
27861    #[tokio::test]
27862    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
27863        for fail in [false, true] {
27864            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27865                storage_query: true,
27866                storage_refusals: 7,
27867                storage_path: Some("/storage-query/"),
27868                ..MockWorkerBehavior::default()
27869            });
27870            let mut worker = storage_worker(&server);
27871            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
27872            let calls = Arc::new(AtomicUsize::new(0));
27873            let observed = Arc::clone(&calls);
27874            worker.register_query("storage.workflow", "state", move |_, _| {
27875                let calls = Arc::clone(&observed);
27876                async move {
27877                    calls.fetch_add(1, Ordering::SeqCst);
27878                    if fail {
27879                        Err(Error::WorkerLoop("intentional query failure".to_string()))
27880                    } else {
27881                        Ok(json!({"state":"waiting"}))
27882                    }
27883                }
27884            });
27885            assert_eq!(worker.run_once().await.expect("query settled"), 1);
27886            assert_eq!(calls.load(Ordering::SeqCst), 1);
27887            let suffix = if fail { "fail" } else { "complete" };
27888            assert_identical_requests(
27889                &server,
27890                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
27891                8,
27892            );
27893            let other = if fail { "complete" } else { "fail" };
27894            assert_eq!(
27895                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
27896                0
27897            );
27898        }
27899    }
27900
27901    #[tokio::test]
27902    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
27903        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27904            storage_refusals: 7,
27905            storage_path: Some("/poll"),
27906            unauthorized_polls: true,
27907            ..MockWorkerBehavior::default()
27908        });
27909        let error = storage_worker(&server)
27910            .run_once()
27911            .await
27912            .expect_err("auth remains terminal");
27913        assert!(matches!(
27914            error,
27915            Error::Http {
27916                status: reqwest::StatusCode::UNAUTHORIZED,
27917                ..
27918            }
27919        ));
27920        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
27921
27922        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27923            storage_refusals: 7,
27924            storage_path: Some("/activity-cancel/complete"),
27925            ..MockWorkerBehavior::default()
27926        });
27927        let worker =
27928            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27929        let error = worker
27930            .client
27931            .complete_activity_task(
27932                "activity-cancel",
27933                "attempt-cancel",
27934                "worker",
27935                json!({}),
27936                DEFAULT_CODEC,
27937            )
27938            .await
27939            .expect_err("cancellation remains terminal");
27940        assert!(activity_task_rejection_is_final(&error));
27941        assert_identical_requests(
27942            &server,
27943            "/api/worker/activity-tasks/activity-cancel/complete",
27944            8,
27945        );
27946
27947        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27948            storage_refusals: usize::MAX,
27949            storage_path: Some("/poll"),
27950            storage_wrong_poll_id: true,
27951            ..MockWorkerBehavior::default()
27952        });
27953        assert!(storage_worker(&server).run_once().await.is_err());
27954        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
27955    }
27956
27957    #[tokio::test]
27958    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
27959        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27960            storage_refusals: usize::MAX,
27961            storage_path: Some("/poll"),
27962            ..MockWorkerBehavior::default()
27963        });
27964        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
27965        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
27966        let run = tokio::spawn(async move { worker.run().await });
27967        tokio::time::timeout(Duration::from_secs(2), async {
27968            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
27969                tokio::time::sleep(Duration::from_millis(1)).await;
27970            }
27971        })
27972        .await
27973        .expect("poll started");
27974        run.abort();
27975        assert!(run.await.expect_err("cancelled run").is_cancelled());
27976        tokio::time::sleep(Duration::from_millis(250)).await;
27977        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
27978    }
27979
27980    #[tokio::test]
27981    async fn query_protocol_rejection_from_older_server_is_typed() {
27982        let server = MockWorkerServer::reject_query_protocol();
27983        let client = Client::builder(server.base_url())
27984            .timeout(Duration::from_secs(2))
27985            .build()
27986            .expect("client");
27987
27988        let error = client
27989            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27990            .await
27991            .expect_err("server below query protocol floor must reject");
27992        let Error::Protocol(failure) = error else {
27993            panic!("expected typed protocol failure");
27994        };
27995
27996        assert_eq!(failure.status, 400);
27997        assert_eq!(failure.reason, "unsupported_protocol_version");
27998        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
27999        assert_eq!(
28000            failure.requested_version.as_deref(),
28001            Some(WORKER_PROTOCOL_VERSION)
28002        );
28003        assert_eq!(
28004            server
28005                .worker_protocol_for("/api/worker/query-tasks/poll")
28006                .as_deref(),
28007            Some(WORKER_PROTOCOL_VERSION)
28008        );
28009    }
28010
28011    #[tokio::test]
28012    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
28013        let server = MockWorkerServer::reject_query_protocol();
28014        let client = Client::builder(server.base_url())
28015            .timeout(Duration::from_secs(2))
28016            .build()
28017            .expect("client");
28018        let mut worker = Worker::new(client, "rust-workers")
28019            .worker_id("baseline-worker")
28020            .poll_timeout(Duration::from_millis(10));
28021
28022        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
28023            Ok(Value::Null)
28024        });
28025
28026        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
28027        assert_eq!(
28028            server
28029                .worker_protocol_for("/api/worker/workflow-tasks/poll")
28030                .as_deref(),
28031            Some(WORKER_PROTOCOL_VERSION)
28032        );
28033        assert_eq!(
28034            server.worker_protocol_for("/api/worker/query-tasks/poll"),
28035            None,
28036            "a worker without query handlers must not use the query-task endpoint"
28037        );
28038    }
28039
28040    #[tokio::test]
28041    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
28042        let server = MockWorkerServer::reject_query_completion();
28043        let client = Client::builder(server.base_url())
28044            .timeout(Duration::from_secs(2))
28045            .build()
28046            .expect("client");
28047
28048        let error = client
28049            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
28050            .await
28051            .expect_err("expired completion must be rejected");
28052        let Error::QueryFailed(failure) = error else {
28053            panic!("expected typed query failure");
28054        };
28055        assert_eq!(failure.status, 409);
28056        assert_eq!(failure.reason, "query_task_timed_out");
28057
28058        let mut worker = Worker::new(client, "rust-workers")
28059            .worker_id("late-worker")
28060            .poll_timeout(Duration::from_millis(10));
28061        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28062        worker.register_query(
28063            "counter",
28064            "current",
28065            |_ctx, _args| async move { Ok(json!(8)) },
28066        );
28067
28068        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
28069        assert_eq!(
28070            worker
28071                .run_once()
28072                .await
28073                .expect("worker continues after late completion"),
28074            0
28075        );
28076        assert_eq!(
28077            server.request_count("/api/worker/query-tasks/query-late/complete"),
28078            2
28079        );
28080        assert_eq!(
28081            server.request_count("/api/worker/query-tasks/query-late/fail"),
28082            0,
28083            "a server completion rejection must not be reported as an encoding failure"
28084        );
28085    }
28086
28087    #[tokio::test]
28088    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
28089        let server = MockWorkerServer::start();
28090        let client = Client::builder(server.base_url())
28091            .timeout(Duration::from_secs(2))
28092            .build()
28093            .expect("client");
28094        let mut worker = Worker::new(client, "rust-workers")
28095            .worker_id("joined-worker")
28096            .poll_timeout(Duration::from_millis(10));
28097        worker.register_workflow(
28098            "joined.workflow",
28099            |_ctx, _input| async move { Ok(Value::Null) },
28100        );
28101        worker.register_activity(
28102            "joined.activity",
28103            |_ctx, _input| async move { Ok(Value::Null) },
28104        );
28105        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
28106            Ok(Value::Null)
28107        });
28108
28109        worker
28110            .run_until(tokio::time::sleep(Duration::from_millis(20)))
28111            .await
28112            .expect("normal shutdown");
28113
28114        let deregistration_path = "/api/worker/registrations/mock-worker";
28115        assert_eq!(server.request_count(deregistration_path), 1);
28116        for poll_path in [
28117            "/api/worker/workflow-tasks/poll",
28118            "/api/worker/activity-tasks/poll",
28119            "/api/worker/query-tasks/poll",
28120        ] {
28121            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
28122        }
28123        assert_eq!(
28124            server.captured_paths().last().map(String::as_str),
28125            Some(deregistration_path),
28126            "deregistration must start only after every poller has joined"
28127        );
28128    }
28129
28130    #[tokio::test]
28131    async fn registration_failure_does_not_deregister() {
28132        let server = MockWorkerServer::rejected_registration();
28133        let client = Client::builder(server.base_url())
28134            .timeout(Duration::from_secs(2))
28135            .build()
28136            .expect("client");
28137        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
28138
28139        let error = worker
28140            .run_until(async {})
28141            .await
28142            .expect_err("registration must fail");
28143        assert!(matches!(
28144            error,
28145            Error::Http {
28146                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28147                ..
28148            }
28149        ));
28150        assert!(server
28151            .captured_paths()
28152            .iter()
28153            .all(|path| !path.starts_with("/api/worker/registrations/")));
28154    }
28155
28156    #[tokio::test]
28157    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
28158        let server = MockWorkerServer::rejected_registration_protocol();
28159        let client = Client::builder(server.base_url())
28160            .timeout(Duration::from_secs(2))
28161            .build()
28162            .expect("client");
28163        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
28164
28165        let error = worker
28166            .run_until(async {})
28167            .await
28168            .expect_err("a protocol 1.16 server must reject this worker");
28169        let Error::Protocol(failure) = error else {
28170            panic!("expected typed protocol rejection");
28171        };
28172        assert_eq!(failure.reason, "unsupported_protocol_version");
28173        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
28174        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
28175        assert_eq!(
28176            server
28177                .worker_protocol_for("/api/worker/register")
28178                .as_deref(),
28179            Some(WORKER_PROTOCOL_VERSION)
28180        );
28181    }
28182
28183    #[tokio::test]
28184    async fn declined_registration_does_not_deregister() {
28185        let server = MockWorkerServer::declined_registration();
28186        let client = Client::builder(server.base_url())
28187            .timeout(Duration::from_secs(2))
28188            .build()
28189            .expect("client");
28190        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
28191
28192        let error = worker
28193            .run_until(async {})
28194            .await
28195            .expect_err("declined registration must fail");
28196        assert!(matches!(error, Error::WorkerLoop(_)));
28197        assert!(error.to_string().contains("was not accepted"));
28198        assert!(server
28199            .captured_paths()
28200            .iter()
28201            .all(|path| !path.starts_with("/api/worker/registrations/")));
28202    }
28203
28204    #[tokio::test]
28205    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
28206        let server = MockWorkerServer::rejected_deregistration();
28207        let client = Client::builder(server.base_url())
28208            .timeout(Duration::from_secs(2))
28209            .build()
28210            .expect("client");
28211        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
28212
28213        let error = worker
28214            .run_until(async {})
28215            .await
28216            .expect_err("deregistration must fail");
28217        assert!(matches!(
28218            error,
28219            Error::Http {
28220                status: reqwest::StatusCode::FORBIDDEN,
28221                ..
28222            }
28223        ));
28224        assert_eq!(
28225            server.request_count("/api/worker/registrations/mock-worker"),
28226            1
28227        );
28228    }
28229
28230    #[tokio::test]
28231    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
28232        let server = MockWorkerServer::rejected_deregistration_protocol();
28233        let client = Client::builder(server.base_url())
28234            .timeout(Duration::from_secs(2))
28235            .build()
28236            .expect("client");
28237        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
28238
28239        let error = worker
28240            .run_until(async {})
28241            .await
28242            .expect_err("protocol rejection must fail shutdown");
28243        let Error::Protocol(failure) = error else {
28244            panic!("expected typed protocol failure");
28245        };
28246        assert_eq!(failure.reason, "unsupported_protocol_version");
28247        assert_eq!(
28248            failure.requested_version.as_deref(),
28249            Some(WORKER_PROTOCOL_VERSION)
28250        );
28251        assert_eq!(
28252            server.request_count("/api/worker/registrations/mock-worker"),
28253            1
28254        );
28255    }
28256
28257    #[tokio::test]
28258    async fn primary_poller_error_retains_deregistration_failure_context() {
28259        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
28260        let client = Client::builder(server.base_url())
28261            .timeout(Duration::from_secs(2))
28262            .build()
28263            .expect("client");
28264        let mut worker = Worker::new(client, "rust-workers")
28265            .worker_id("combined-failure")
28266            .poll_timeout(Duration::from_millis(10));
28267        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
28268            Ok(Value::Null)
28269        });
28270
28271        let error = worker
28272            .run()
28273            .await
28274            .expect_err("worker and cleanup must fail");
28275        let summary = error.to_string();
28276        assert!(summary.contains("authentication_failed"));
28277        assert!(summary.contains("worker cannot deregister"));
28278        let Error::WorkerShutdown {
28279            primary,
28280            deregistration,
28281        } = error
28282        else {
28283            panic!("expected combined worker shutdown error");
28284        };
28285        assert!(matches!(
28286            *primary,
28287            Error::Http {
28288                status: reqwest::StatusCode::UNAUTHORIZED,
28289                ..
28290            }
28291        ));
28292        assert!(matches!(
28293            *deregistration,
28294            Error::Http {
28295                status: reqwest::StatusCode::FORBIDDEN,
28296                ..
28297            }
28298        ));
28299        assert_eq!(
28300            server.request_count("/api/worker/registrations/mock-worker"),
28301            1
28302        );
28303    }
28304
28305    #[tokio::test]
28306    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
28307        let server = MockWorkerServer::start();
28308        let client = Client::builder(server.base_url())
28309            .timeout(Duration::from_secs(2))
28310            .build()
28311            .expect("client");
28312        let mut worker = Worker::new(client, "rust-workers")
28313            .worker_id("activity-only-worker")
28314            .poll_timeout(Duration::from_millis(10));
28315
28316        worker.register_activity(
28317            "activity.only",
28318            |_ctx, _args| async move { Ok(Value::Null) },
28319        );
28320
28321        worker.run_until(async {}).await.expect("run worker");
28322    }
28323
28324    #[tokio::test]
28325    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
28326        let server = MockWorkerServer::start();
28327        let client = Client::builder(server.base_url())
28328            .timeout(Duration::from_secs(2))
28329            .build()
28330            .expect("client");
28331        let mut worker = Worker::new(client, "rust-workers")
28332            .worker_id("workflow-only-worker")
28333            .poll_timeout(Duration::from_millis(10));
28334
28335        worker.register_workflow(
28336            "workflow.only",
28337            |_ctx, _input| async move { Ok(Value::Null) },
28338        );
28339
28340        worker.run_until(async {}).await.expect("run worker");
28341    }
28342
28343    #[tokio::test]
28344    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
28345        let server = MockWorkerServer::start();
28346        let client = Client::builder(server.base_url())
28347            .timeout(Duration::from_secs(2))
28348            .build()
28349            .expect("client");
28350        let observations = Arc::new(Mutex::new(Vec::new()));
28351        let observed = Arc::clone(&observations);
28352        let mut worker = Worker::new(client, "rust-workers")
28353            .worker_id("observed-heartbeat-worker")
28354            .poll_timeout(Duration::from_millis(10))
28355            .on_worker_heartbeat(move |observation| {
28356                observed
28357                    .lock()
28358                    .expect("heartbeat observations")
28359                    .push(observation.clone());
28360            });
28361
28362        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
28363            Ok(Value::Null)
28364        });
28365        let acknowledged = Arc::clone(&observations);
28366        worker
28367            .run_until(async move {
28368                tokio::time::timeout(Duration::from_secs(2), async move {
28369                    loop {
28370                        if !acknowledged
28371                            .lock()
28372                            .expect("heartbeat observations")
28373                            .is_empty()
28374                        {
28375                            break;
28376                        }
28377                        tokio::time::sleep(Duration::from_millis(1)).await;
28378                    }
28379                })
28380                .await
28381                .expect("heartbeat acknowledgement within timeout");
28382            })
28383            .await
28384            .expect("run worker");
28385
28386        let observations = observations.lock().expect("heartbeat observations");
28387        let first = observations.first().expect("heartbeat acknowledgement");
28388        assert_eq!(first.worker_id, "observed-heartbeat-worker");
28389        assert_eq!(first.task_queue, "rust-workers");
28390        assert!(first.acknowledged_at_unix_millis > 0);
28391        assert_eq!(first.acknowledgement, json!({}));
28392    }
28393
28394    #[tokio::test]
28395    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
28396        let server = MockWorkerServer::delayed_heartbeat_worker();
28397        let client = Client::builder(server.base_url())
28398            .timeout(Duration::from_secs(3))
28399            .build()
28400            .expect("client");
28401        let observations = Arc::new(Mutex::new(Vec::new()));
28402        let observed = Arc::clone(&observations);
28403        let mut worker = Worker::new(client, "rust-snapshot-workers")
28404            .worker_id("rust-snapshot-worker")
28405            .poll_timeout(Duration::from_millis(10))
28406            .on_worker_heartbeat(move |observation| {
28407                observed
28408                    .lock()
28409                    .expect("heartbeat observations")
28410                    .push(observation.clone());
28411            });
28412
28413        worker.register_workflow("snapshot", |ctx, _input| async move {
28414            ctx.wait_signal("finish").await?;
28415            Ok(json!({"status": "finished"}))
28416        });
28417        worker.register_query("snapshot", "current", |ctx, _args| async move {
28418            Ok(json!(ctx
28419                .signals("increment")
28420                .iter()
28421                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28422                .sum::<i64>()))
28423        });
28424        worker.register_activity("cancel-aware", |_ctx, _args| async move {
28425            Ok(json!({"late": "completion"}))
28426        });
28427
28428        worker
28429            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
28430            .await
28431            .expect("delayed heartbeat must allow a clean worker shutdown");
28432
28433        let observations = observations.lock().expect("heartbeat observations");
28434        assert!(
28435            observations.len() >= 3,
28436            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
28437        );
28438        assert!(
28439            observations.windows(2).all(|pair| {
28440                pair[1].acknowledged_at_unix_millis
28441                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28442                    >= 850
28443            }),
28444            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
28445        );
28446        drop(observations);
28447
28448        let heartbeat_times = server.request_times("/api/worker/heartbeat");
28449        let delayed_request_at = *heartbeat_times
28450            .get(1)
28451            .expect("intentionally delayed heartbeat request");
28452        let delay_window_start = delayed_request_at + Duration::from_millis(100);
28453        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
28454        for path in [
28455            "/api/worker/workflow-tasks/poll",
28456            "/api/worker/activity-tasks/poll",
28457            "/api/worker/query-tasks/poll",
28458        ] {
28459            assert!(
28460                server
28461                    .request_times(path)
28462                    .iter()
28463                    .any(|received_at| *received_at >= delay_window_start
28464                        && *received_at <= delay_window_end),
28465                "{path} must keep polling while a heartbeat acknowledgement is delayed"
28466            );
28467        }
28468        assert!(
28469            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
28470            "workflow work must be settled"
28471        );
28472        assert!(
28473            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
28474            "activity work must be settled"
28475        );
28476        assert!(
28477            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
28478            "query work must be settled"
28479        );
28480    }
28481
28482    #[tokio::test]
28483    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
28484        let server = MockWorkerServer::heartbeat_retry_worker();
28485        let client = Client::builder(server.base_url())
28486            .timeout(Duration::from_secs(2))
28487            .build()
28488            .expect("client");
28489        let observations = Arc::new(Mutex::new(Vec::new()));
28490        let observed = Arc::clone(&observations);
28491        let worker = Worker::new(client, "rust-workers")
28492            .worker_id("heartbeat-retry-worker")
28493            .retry_policy(WorkerRetryPolicy {
28494                max_retries: 1,
28495                initial_backoff: Duration::from_millis(300),
28496                max_backoff: Duration::from_millis(300),
28497            })
28498            .on_worker_heartbeat(move |observation| {
28499                observed
28500                    .lock()
28501                    .expect("heartbeat observations")
28502                    .push(observation.clone());
28503            });
28504
28505        worker
28506            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
28507            .await
28508            .expect("retryable heartbeat failure must remain bounded and recover");
28509
28510        let observations = observations.lock().expect("heartbeat observations");
28511        assert!(observations.len() >= 3, "heartbeat retry must recover");
28512        assert!(
28513            observations.windows(2).all(|pair| {
28514                pair[1]
28515                    .acknowledged_at_unix_millis
28516                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28517                    >= 850
28518            }),
28519            "a successful retry must start a fresh advertised cadence: {observations:?}"
28520        );
28521        assert_eq!(
28522            server.request_count("/api/worker/heartbeat"),
28523            observations.len() + 1,
28524            "one retryable failure must add exactly one bounded request"
28525        );
28526    }
28527
28528    #[tokio::test]
28529    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
28530        let server = MockWorkerServer::waiting_query_worker();
28531        let client = Client::builder(server.base_url())
28532            .timeout(Duration::from_secs(2))
28533            .build()
28534            .expect("client");
28535        let observations = Arc::new(Mutex::new(Vec::new()));
28536        let observed = Arc::clone(&observations);
28537        let mut worker = Worker::new(client, "rust-snapshot-workers")
28538            .worker_id("rust-snapshot-worker")
28539            .poll_timeout(Duration::from_millis(10))
28540            .on_worker_heartbeat(move |observation| {
28541                observed
28542                    .lock()
28543                    .expect("heartbeat observations")
28544                    .push(observation.clone());
28545            });
28546
28547        worker.register_workflow("snapshot", |ctx, _input| async move {
28548            ctx.wait_signal("finish").await?;
28549            Ok(json!({"status": "finished"}))
28550        });
28551        worker.register_query("snapshot", "current", |ctx, _args| async move {
28552            let current = ctx
28553                .signals("increment")
28554                .iter()
28555                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28556                .sum::<i64>();
28557            Ok(json!(current))
28558        });
28559        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
28560        worker
28561            .declare_workflow_signals("snapshot", &["finish"])
28562            .expect("declare finish signal");
28563
28564        worker
28565            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
28566            .await
28567            .expect("pending workflow and query poller must remain live until shutdown");
28568
28569        assert!(
28570            observations.lock().expect("heartbeat observations").len() >= 4,
28571            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
28572        );
28573        assert!(
28574            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
28575            "workflow polling must continue after empty replay acknowledgements"
28576        );
28577        assert!(
28578            server.request_count("/api/worker/query-tasks/poll") >= 2,
28579            "query polling must continue after serving the current query"
28580        );
28581        assert_eq!(
28582            server.request_body("/api/worker/register")["capabilities"],
28583            json!([
28584                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
28585                DURABLE_SELECTION_CAPABILITY,
28586                MEMO_UPSERTS_CAPABILITY,
28587                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
28588                QUERY_TASKS_CAPABILITY,
28589                WORKFLOW_UPDATES_CAPABILITY,
28590                MESSAGE_STREAMS_CAPABILITY
28591            ])
28592        );
28593        assert_eq!(
28594            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
28595            json!({
28596                "queries": ["current"],
28597                "query_contracts": [{
28598                    "name": "current",
28599                    "parameters": [{
28600                        "name": "args", "position": 0, "required": false,
28601                        "variadic": true, "type": null, "allows_null": true,
28602                        "default_available": false, "default": null,
28603                    }],
28604                }],
28605                "signals": ["finish"],
28606                "signal_contracts": [{
28607                    "name": "finish",
28608                    "parameters": [{
28609                        "name": "args", "position": 0, "required": false,
28610                        "variadic": true, "type": null, "allows_null": true,
28611                        "default_available": false, "default": null,
28612                    }],
28613                }],
28614                "updates": ["replace"],
28615                "update_contracts": [{
28616                    "name": "replace",
28617                    "parameters": [{
28618                        "name": "args", "position": 0, "required": false,
28619                        "variadic": true, "type": null, "allows_null": true,
28620                        "default_available": false, "default": null,
28621                    }],
28622                }],
28623                "update_validators": [],
28624            })
28625        );
28626
28627        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
28628        assert_eq!(
28629            opened["commands"],
28630            json!([{
28631                "type": "open_signal_wait",
28632                "signal_name": "finish",
28633            }])
28634        );
28635
28636        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
28637            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
28638            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
28639            let failure = server.request_body(&fail_path);
28640            assert_eq!(
28641                failure["failure"]["type"],
28642                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
28643            );
28644            assert_eq!(server.request_count(&completion_path), 0);
28645        }
28646
28647        let query_completion =
28648            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
28649        assert_eq!(query_completion["result"], json!(8));
28650
28651        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
28652        assert_eq!(
28653            server.request_count(terminal_path),
28654            1,
28655            "the matching signal must settle the workflow exactly once"
28656        );
28657        let terminal = server.request_body(terminal_path);
28658        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
28659        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
28660        assert_eq!(
28661            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
28662                .expect("terminal workflow result"),
28663            json!({"status": "finished"})
28664        );
28665    }
28666
28667    #[tokio::test]
28668    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
28669        let server = MockWorkerServer::transient_worker_failures();
28670        let client = Client::builder(server.base_url())
28671            .timeout(Duration::from_secs(2))
28672            .build()
28673            .expect("client");
28674        let mut worker = Worker::new(client, "rust-workers")
28675            .worker_id("retry-worker")
28676            .poll_timeout(Duration::from_millis(10))
28677            .retry_policy(WorkerRetryPolicy {
28678                max_retries: 2,
28679                initial_backoff: Duration::from_millis(1),
28680                max_backoff: Duration::from_millis(1),
28681            });
28682        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28683        worker.register_activity(
28684            "counter.activity",
28685            |_ctx, _input| async move { Ok(Value::Null) },
28686        );
28687        worker.register_query(
28688            "counter",
28689            "current",
28690            |_ctx, _args| async move { Ok(json!(8)) },
28691        );
28692
28693        worker
28694            .run_until(tokio::time::sleep(Duration::from_millis(75)))
28695            .await
28696            .expect("transient failures must not stop the worker");
28697
28698        for path in [
28699            "/api/worker/heartbeat",
28700            "/api/worker/workflow-tasks/poll",
28701            "/api/worker/activity-tasks/poll",
28702            "/api/worker/query-tasks/poll",
28703        ] {
28704            assert!(
28705                server.request_count(path) >= 2,
28706                "{path} must continue after its transient failure"
28707            );
28708        }
28709    }
28710
28711    #[tokio::test]
28712    async fn worker_continues_after_long_poll_capacity_backpressure() {
28713        let server = MockWorkerServer::capacity_limited_activity_poll();
28714        let client = Client::builder(server.base_url())
28715            .timeout(Duration::from_secs(2))
28716            .build()
28717            .expect("client");
28718        let mut worker = Worker::new(client, "rust-workers")
28719            .worker_id("capacity-worker")
28720            .poll_timeout(Duration::from_millis(10))
28721            .retry_policy(WorkerRetryPolicy {
28722                max_retries: 0,
28723                initial_backoff: Duration::from_millis(1),
28724                max_backoff: Duration::from_millis(1),
28725            });
28726        worker.register_activity("capacity.activity", |_ctx, _input| async move {
28727            Ok(json!({"handled": true}))
28728        });
28729
28730        worker
28731            .run_until(tokio::time::sleep(Duration::from_millis(50)))
28732            .await
28733            .expect("capacity backpressure must not stop the worker");
28734
28735        assert!(
28736            server.request_count("/api/worker/activity-tasks/poll") >= 2,
28737            "the activity poller must continue after capacity backpressure"
28738        );
28739        assert_eq!(
28740            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
28741            1,
28742            "the worker must complete work returned after capacity recovers"
28743        );
28744    }
28745
28746    #[test]
28747    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
28748        let capacity = Error::Http {
28749            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28750            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
28751        };
28752        assert_eq!(
28753            worker_poll_capacity_retry_after(&capacity),
28754            Some(Duration::from_secs(3))
28755        );
28756
28757        let rejected_capacity = Error::Http {
28758            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28759            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
28760        };
28761        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
28762        assert!(!worker_operation_is_retryable(&rejected_capacity));
28763
28764        let ordinary_rate_limit = Error::Http {
28765            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28766            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
28767                .to_string(),
28768        };
28769        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
28770        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
28771    }
28772
28773    #[tokio::test]
28774    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
28775        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28776            poll_failures_per_path: 8,
28777            heartbeat_failures: 8,
28778            ..MockWorkerBehavior::default()
28779        });
28780        let client = Client::builder(server.base_url())
28781            .timeout(Duration::from_secs(2))
28782            .build()
28783            .expect("client");
28784        let acknowledgements = Arc::new(AtomicUsize::new(0));
28785        let observed = Arc::clone(&acknowledgements);
28786        let mut worker = Worker::new(client, "rust-workers")
28787            .recover_transient_outages(true)
28788            .poll_timeout(Duration::from_millis(10))
28789            .retry_policy(WorkerRetryPolicy {
28790                max_retries: 2,
28791                initial_backoff: Duration::from_millis(2),
28792                max_backoff: Duration::from_millis(5),
28793            })
28794            .on_worker_heartbeat(move |_| {
28795                observed.fetch_add(1, Ordering::SeqCst);
28796            });
28797        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28798        worker.register_activity(
28799            "counter.activity",
28800            |_ctx, _input| async move { Ok(Value::Null) },
28801        );
28802        worker.register_query("counter", "current", |_ctx, _args| async move {
28803            Ok(Value::Null)
28804        });
28805
28806        worker
28807            .run_until(tokio::time::sleep(Duration::from_millis(500)))
28808            .await
28809            .expect("a recoverable outage must not stop the service worker");
28810
28811        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
28812        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
28813        for path in [
28814            "/api/worker/workflow-tasks/poll",
28815            "/api/worker/activity-tasks/poll",
28816            "/api/worker/query-tasks/poll",
28817        ] {
28818            let bodies = server.request_bodies(path);
28819            assert!(bodies.len() >= 10, "{path} must resume after recovery");
28820            let first = &bodies[0]["poll_request_id"];
28821            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
28822            for body in &bodies[..9] {
28823                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
28824            }
28825            assert_ne!(&bodies[9]["poll_request_id"], first);
28826            let times = server.request_times(path);
28827            for pair in times[..9].windows(2) {
28828                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
28829            }
28830        }
28831    }
28832
28833    #[tokio::test]
28834    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
28835        for heartbeat_outage in [false, true] {
28836            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28837                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
28838                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
28839                ..MockWorkerBehavior::default()
28840            });
28841            let client = Client::builder(server.base_url()).build().expect("client");
28842            let mut worker = Worker::new(client, "rust-workers")
28843                .recover_transient_outages(true)
28844                .retry_policy(WorkerRetryPolicy {
28845                    max_retries: 1,
28846                    initial_backoff: Duration::from_secs(5),
28847                    max_backoff: Duration::from_secs(5),
28848                });
28849            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28850            let started = Instant::now();
28851            worker
28852                .run_until(tokio::time::sleep(Duration::from_millis(200)))
28853                .await
28854                .expect("shutdown during an outage is a normal stop");
28855            assert!(started.elapsed() < Duration::from_secs(1));
28856            let path = if heartbeat_outage {
28857                "/api/worker/heartbeat"
28858            } else {
28859                "/api/worker/workflow-tasks/poll"
28860            };
28861            assert_eq!(server.request_count(path), 1);
28862            assert_eq!(
28863                server.request_count("/api/worker/registrations/mock-worker"),
28864                1
28865            );
28866        }
28867    }
28868
28869    #[tokio::test]
28870    async fn worker_outage_recovery_keeps_run_once_bounded() {
28871        let server = MockWorkerServer::unavailable_polls();
28872        let client = Client::builder(server.base_url()).build().expect("client");
28873        let mut worker = Worker::new(client, "rust-workers")
28874            .recover_transient_outages(true)
28875            .retry_policy(WorkerRetryPolicy {
28876                max_retries: 2,
28877                initial_backoff: Duration::from_millis(1),
28878                max_backoff: Duration::from_millis(1),
28879            });
28880        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28881        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
28882        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
28883    }
28884
28885    #[tokio::test]
28886    async fn worker_outage_recovery_respects_disabled_retries() {
28887        let server = MockWorkerServer::unavailable_polls();
28888        let client = Client::builder(server.base_url()).build().expect("client");
28889        let mut worker = Worker::new(client, "rust-workers")
28890            .recover_transient_outages(true)
28891            .retry_policy(WorkerRetryPolicy {
28892                max_retries: 0,
28893                ..WorkerRetryPolicy::default()
28894            });
28895        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28896        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
28897        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28898    }
28899
28900    #[tokio::test]
28901    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
28902        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28903            heartbeat_failures: usize::MAX,
28904            unauthorized_polls: true,
28905            ..MockWorkerBehavior::default()
28906        });
28907        let client = Client::builder(server.base_url()).build().expect("client");
28908        let mut worker = Worker::new(client, "rust-workers")
28909            .recover_transient_outages(true)
28910            .retry_policy(WorkerRetryPolicy {
28911                max_retries: 1,
28912                initial_backoff: Duration::from_secs(5),
28913                max_backoff: Duration::from_secs(5),
28914            });
28915        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28916        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
28917            .await
28918            .expect("fatal poll errors must interrupt heartbeat recovery")
28919            .expect_err("authentication failure is terminal");
28920        assert!(
28921            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
28922        );
28923        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28924    }
28925
28926    #[tokio::test]
28927    async fn worker_bounds_transport_retries() {
28928        let server = MockWorkerServer::unavailable_polls();
28929        let client = Client::builder(server.base_url())
28930            .timeout(Duration::from_secs(2))
28931            .build()
28932            .expect("client");
28933        let mut worker = Worker::new(client, "rust-workers")
28934            .worker_id("bounded-retry-worker")
28935            .poll_timeout(Duration::from_millis(10))
28936            .retry_policy(WorkerRetryPolicy {
28937                max_retries: 2,
28938                initial_backoff: Duration::from_millis(1),
28939                max_backoff: Duration::from_millis(1),
28940            });
28941        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28942
28943        let error = worker.run().await.expect_err("retry bound must terminate");
28944        assert!(matches!(error, Error::Transport(_)));
28945        assert_eq!(
28946            server.request_count("/api/worker/workflow-tasks/poll"),
28947            3,
28948            "one initial request plus exactly two retries"
28949        );
28950    }
28951
28952    #[tokio::test]
28953    async fn worker_retry_policy_can_disable_poll_retries() {
28954        let server = MockWorkerServer::unavailable_polls();
28955        let client = Client::builder(server.base_url())
28956            .timeout(Duration::from_secs(2))
28957            .build()
28958            .expect("client");
28959        let mut worker = Worker::new(client, "rust-workers")
28960            .worker_id("no-retry-worker")
28961            .poll_timeout(Duration::from_millis(10))
28962            .retry_policy(WorkerRetryPolicy {
28963                max_retries: 0,
28964                initial_backoff: Duration::from_millis(1),
28965                max_backoff: Duration::from_millis(1),
28966            });
28967        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28968
28969        let error = worker
28970            .run_once()
28971            .await
28972            .expect_err("disabled retries must return the first transport failure");
28973        assert!(matches!(error, Error::Transport(_)));
28974        assert_eq!(
28975            server.request_count("/api/worker/workflow-tasks/poll"),
28976            1,
28977            "max_retries=0 must send only the initial request"
28978        );
28979    }
28980
28981    #[tokio::test]
28982    async fn worker_does_not_retry_authentication_failures() {
28983        let server = MockWorkerServer::unauthorized_polls();
28984        let client = Client::builder(server.base_url())
28985            .timeout(Duration::from_secs(2))
28986            .build()
28987            .expect("client");
28988        let mut worker = Worker::new(client, "rust-workers")
28989            .worker_id("unauthorized-worker")
28990            .recover_transient_outages(true)
28991            .poll_timeout(Duration::from_millis(10));
28992        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28993
28994        let error = worker
28995            .run()
28996            .await
28997            .expect_err("authentication must terminate");
28998        let Error::Http { status, body } = error else {
28999            panic!("expected stable HTTP authentication error");
29000        };
29001        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
29002        assert!(body.contains("authentication_failed"));
29003        assert_eq!(
29004            server.request_count("/api/worker/workflow-tasks/poll"),
29005            1,
29006            "authentication failures must not be retried"
29007        );
29008    }
29009
29010    #[test]
29011    fn duplicate_registration_keeps_the_original_workflow() {
29012        let client = Client::new("http://127.0.0.1:9").expect("client");
29013        let mut worker = Worker::new(client, "registration-tests");
29014        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29015        let original = Arc::clone(&worker.workflows["same"].execute);
29016        worker
29017            .set_workflow_definition_sources("same", &["first workflow source"])
29018            .expect("source identity");
29019        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
29020        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
29021        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
29022        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
29023    }
29024
29025    #[test]
29026    fn duplicate_registration_keeps_the_original_activity() {
29027        let client = Client::new("http://127.0.0.1:9").expect("client");
29028        let mut worker = Worker::new(client, "registration-tests");
29029        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
29030        let original = Arc::clone(&worker.activities["same"]);
29031        worker.register_activity_avro_value("same", |_ctx, _input| async {
29032            Ok(AvroValue::String("second".into()))
29033        });
29034        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
29035    }
29036
29037    #[test]
29038    fn duplicate_registration_keeps_original_query_and_update_handlers() {
29039        let client = Client::new("http://127.0.0.1:9").expect("client");
29040        let mut worker = Worker::new(client, "registration-tests");
29041        worker.register_query("orders", "same", |_ctx, _input| async {
29042            Ok(json!("first"))
29043        });
29044        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
29045            panic!("snapshot query");
29046        };
29047        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
29048            Ok(json!("second"))
29049        });
29050        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
29051            panic!("duplicate replaced the query adapter");
29052        };
29053        assert!(Arc::ptr_eq(&original, retained));
29054        worker.register_update("orders", "same", |_ctx, _input| async {
29055            Ok(json!("first"))
29056        });
29057        let original = Arc::clone(&worker.updates["orders"]["same"]);
29058        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
29059            Ok(AvroValue::Null)
29060        });
29061        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
29062    }
29063
29064    #[tokio::test]
29065    async fn duplicate_registration_fails_before_server_contact() {
29066        let server = MockWorkerServer::start();
29067        let client = Client::builder(server.base_url()).build().expect("client");
29068        let mut worker =
29069            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
29070        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29071        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
29072        let error = worker
29073            .run_once()
29074            .await
29075            .expect_err("ambiguous worker must not poll");
29076        assert!(
29077            error.to_string().contains("duplicate_registration"),
29078            "{error}"
29079        );
29080        assert!(server.requests.lock().expect("requests").is_empty());
29081    }
29082
29083    #[derive(Clone, Debug)]
29084    struct CapturedRequest {
29085        headers: String,
29086        method: String,
29087        path: String,
29088        authorization: Option<String>,
29089        namespace: Option<String>,
29090        worker_protocol: Option<String>,
29091        control_protocol: Option<String>,
29092        body: String,
29093        received_at: Instant,
29094    }
29095
29096    struct MockWorkerServer {
29097        addr: SocketAddr,
29098        stop: Arc<AtomicBool>,
29099        requests: Arc<Mutex<Vec<CapturedRequest>>>,
29100        thread: Option<thread::JoinHandle<()>>,
29101    }
29102
29103    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
29104
29105    #[derive(Clone, Copy, Default)]
29106    struct MockWorkerBehavior {
29107        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
29108        request_override: Option<RequestOverride>,
29109        storage_refusals: usize,
29110        storage_path: Option<&'static str>,
29111        storage_unavailable: bool,
29112        storage_mid_poll: bool,
29113        storage_activity: bool,
29114        storage_query: bool,
29115        storage_wrong_poll_id: bool,
29116        reject_query_protocol: bool,
29117        reject_query_completion: bool,
29118        waiting_query_worker: bool,
29119        decline_registration: bool,
29120        complete_named_signal: bool,
29121        poll_failures_per_path: usize,
29122        long_poll_capacity_responses_per_path: usize,
29123        heartbeat_failures: usize,
29124        heartbeat_failure_request: Option<usize>,
29125        delayed_heartbeat_request: Option<usize>,
29126        heartbeat_response_delay: Duration,
29127        concurrent_requests: bool,
29128        unauthorized_polls: bool,
29129        reject_registration: bool,
29130        reject_registration_protocol: bool,
29131        reject_deregistration: bool,
29132        reject_deregistration_protocol: bool,
29133        cancelled_activity: bool,
29134        draining_polls: bool,
29135        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
29136        workflow_completion_status: Option<&'static str>,
29137        workflow_completion_body: Option<&'static str>,
29138    }
29139
29140    impl MockWorkerServer {
29141        fn start() -> Self {
29142            Self::start_with_behavior(MockWorkerBehavior::default())
29143        }
29144
29145        fn reject_query_protocol() -> Self {
29146            Self::start_with_behavior(MockWorkerBehavior {
29147                reject_query_protocol: true,
29148                ..MockWorkerBehavior::default()
29149            })
29150        }
29151
29152        fn reject_query_completion() -> Self {
29153            Self::start_with_behavior(MockWorkerBehavior {
29154                reject_query_completion: true,
29155                ..MockWorkerBehavior::default()
29156            })
29157        }
29158
29159        fn waiting_query_worker() -> Self {
29160            Self::start_with_behavior(MockWorkerBehavior {
29161                waiting_query_worker: true,
29162                complete_named_signal: true,
29163                ..MockWorkerBehavior::default()
29164            })
29165        }
29166
29167        fn transient_worker_failures() -> Self {
29168            Self::start_with_behavior(MockWorkerBehavior {
29169                poll_failures_per_path: 1,
29170                heartbeat_failures: 1,
29171                ..MockWorkerBehavior::default()
29172            })
29173        }
29174
29175        fn consecutive_poll_failures(count: usize) -> Self {
29176            Self::start_with_behavior(MockWorkerBehavior {
29177                poll_failures_per_path: count,
29178                ..MockWorkerBehavior::default()
29179            })
29180        }
29181
29182        fn capacity_limited_activity_poll() -> Self {
29183            Self::start_with_behavior(MockWorkerBehavior {
29184                long_poll_capacity_responses_per_path: 1,
29185                ..MockWorkerBehavior::default()
29186            })
29187        }
29188
29189        fn delayed_heartbeat_worker() -> Self {
29190            Self::start_with_behavior(MockWorkerBehavior {
29191                waiting_query_worker: true,
29192                delayed_heartbeat_request: Some(2),
29193                heartbeat_response_delay: Duration::from_millis(1_500),
29194                concurrent_requests: true,
29195                cancelled_activity: true,
29196                ..MockWorkerBehavior::default()
29197            })
29198        }
29199
29200        fn heartbeat_retry_worker() -> Self {
29201            Self::start_with_behavior(MockWorkerBehavior {
29202                waiting_query_worker: true,
29203                heartbeat_failure_request: Some(2),
29204                concurrent_requests: true,
29205                ..MockWorkerBehavior::default()
29206            })
29207        }
29208
29209        fn unavailable_polls() -> Self {
29210            Self::start_with_behavior(MockWorkerBehavior {
29211                poll_failures_per_path: usize::MAX,
29212                ..MockWorkerBehavior::default()
29213            })
29214        }
29215
29216        fn unauthorized_polls() -> Self {
29217            Self::start_with_behavior(MockWorkerBehavior {
29218                unauthorized_polls: true,
29219                ..MockWorkerBehavior::default()
29220            })
29221        }
29222
29223        fn rejected_registration() -> Self {
29224            Self::start_with_behavior(MockWorkerBehavior {
29225                reject_registration: true,
29226                ..MockWorkerBehavior::default()
29227            })
29228        }
29229
29230        fn rejected_registration_protocol() -> Self {
29231            Self::start_with_behavior(MockWorkerBehavior {
29232                reject_registration_protocol: true,
29233                ..MockWorkerBehavior::default()
29234            })
29235        }
29236
29237        fn declined_registration() -> Self {
29238            Self::start_with_behavior(MockWorkerBehavior {
29239                decline_registration: true,
29240                ..MockWorkerBehavior::default()
29241            })
29242        }
29243
29244        fn rejected_deregistration() -> Self {
29245            Self::start_with_behavior(MockWorkerBehavior {
29246                reject_deregistration: true,
29247                ..MockWorkerBehavior::default()
29248            })
29249        }
29250
29251        fn rejected_deregistration_protocol() -> Self {
29252            Self::start_with_behavior(MockWorkerBehavior {
29253                reject_deregistration_protocol: true,
29254                ..MockWorkerBehavior::default()
29255            })
29256        }
29257
29258        fn unauthorized_polls_and_rejected_deregistration() -> Self {
29259            Self::start_with_behavior(MockWorkerBehavior {
29260                unauthorized_polls: true,
29261                reject_deregistration: true,
29262                ..MockWorkerBehavior::default()
29263            })
29264        }
29265
29266        fn cancelled_activity() -> Self {
29267            Self::start_with_behavior(MockWorkerBehavior {
29268                cancelled_activity: true,
29269                ..MockWorkerBehavior::default()
29270            })
29271        }
29272
29273        fn draining_polls() -> Self {
29274            Self::start_with_behavior(MockWorkerBehavior {
29275                draining_polls: true,
29276                ..MockWorkerBehavior::default()
29277            })
29278        }
29279
29280        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
29281            Self::start_with_behavior(MockWorkerBehavior {
29282                invalid_task_payload_codec: Some(codec),
29283                ..MockWorkerBehavior::default()
29284            })
29285        }
29286
29287        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
29288            Self::start_with_behavior(MockWorkerBehavior {
29289                workflow_completion_status: Some(status),
29290                workflow_completion_body: Some(body),
29291                ..MockWorkerBehavior::default()
29292            })
29293        }
29294
29295        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
29296            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
29297            listener
29298                .set_nonblocking(true)
29299                .expect("configure mock listener");
29300            let addr = listener.local_addr().expect("mock server address");
29301            let stop = Arc::new(AtomicBool::new(false));
29302            let server_stop = Arc::clone(&stop);
29303            let requests = Arc::new(Mutex::new(Vec::new()));
29304            let server_requests = Arc::clone(&requests);
29305            let thread = thread::spawn(move || {
29306                let mut request_threads = Vec::new();
29307                while !server_stop.load(Ordering::SeqCst) {
29308                    match listener.accept() {
29309                        Ok((mut stream, _)) => {
29310                            if behavior.concurrent_requests {
29311                                let requests = Arc::clone(&server_requests);
29312                                request_threads.push(thread::spawn(move || {
29313                                    handle_mock_worker_request(&mut stream, &requests, behavior)
29314                                }));
29315                            } else {
29316                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
29317                            }
29318                        }
29319                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
29320                            let mut index = 0;
29321                            while index < request_threads.len() {
29322                                if request_threads[index].is_finished() {
29323                                    request_threads
29324                                        .swap_remove(index)
29325                                        .join()
29326                                        .expect("join mock request");
29327                                } else {
29328                                    index += 1;
29329                                }
29330                            }
29331                            thread::sleep(Duration::from_millis(5));
29332                        }
29333                        Err(_) => break,
29334                    }
29335                }
29336                for request_thread in request_threads {
29337                    request_thread.join().expect("join mock request");
29338                }
29339            });
29340
29341            Self {
29342                addr,
29343                stop,
29344                requests,
29345                thread: Some(thread),
29346            }
29347        }
29348
29349        fn base_url(&self) -> String {
29350            format!("http://{}", self.addr)
29351        }
29352
29353        fn worker_protocol_for(&self, path: &str) -> Option<String> {
29354            self.requests
29355                .lock()
29356                .expect("captured requests")
29357                .iter()
29358                .find(|request| request.path == path)
29359                .and_then(|request| request.worker_protocol.clone())
29360        }
29361
29362        fn control_protocol_for(&self, path: &str) -> Option<String> {
29363            self.requests
29364                .lock()
29365                .expect("captured requests")
29366                .iter()
29367                .find(|request| request.path == path)
29368                .and_then(|request| request.control_protocol.clone())
29369        }
29370
29371        fn method_for(&self, path: &str) -> Option<String> {
29372            self.requests
29373                .lock()
29374                .expect("captured requests")
29375                .iter()
29376                .find(|request| request.path == path)
29377                .map(|request| request.method.clone())
29378        }
29379
29380        fn authorization_for(&self, path: &str) -> Option<String> {
29381            self.requests
29382                .lock()
29383                .expect("captured requests")
29384                .iter()
29385                .find(|request| request.path == path)
29386                .and_then(|request| request.authorization.clone())
29387        }
29388
29389        fn namespace_for(&self, path: &str) -> Option<String> {
29390            self.requests
29391                .lock()
29392                .expect("captured requests")
29393                .iter()
29394                .find(|request| request.path == path)
29395                .and_then(|request| request.namespace.clone())
29396        }
29397
29398        fn request_count(&self, path: &str) -> usize {
29399            self.requests
29400                .lock()
29401                .expect("captured requests")
29402                .iter()
29403                .filter(|request| request.path == path)
29404                .count()
29405        }
29406
29407        fn captured_paths(&self) -> Vec<String> {
29408            self.requests
29409                .lock()
29410                .expect("captured requests")
29411                .iter()
29412                .map(|request| request.path.clone())
29413                .collect()
29414        }
29415
29416        fn request_times(&self, path: &str) -> Vec<Instant> {
29417            self.requests
29418                .lock()
29419                .expect("captured requests")
29420                .iter()
29421                .filter(|request| request.path == path)
29422                .map(|request| request.received_at)
29423                .collect()
29424        }
29425
29426        fn request_body(&self, path: &str) -> Value {
29427            let requests = self.requests.lock().expect("captured requests");
29428            let body = &requests
29429                .iter()
29430                .find(|request| request.path == path)
29431                .unwrap_or_else(|| panic!("missing request for {path}"))
29432                .body;
29433            serde_json::from_str(body).unwrap_or_else(|error| {
29434                panic!("invalid JSON request body for {path}: {error}: {body:?}")
29435            })
29436        }
29437
29438        fn request_bodies(&self, path: &str) -> Vec<Value> {
29439            self.requests
29440                .lock()
29441                .expect("captured requests")
29442                .iter()
29443                .filter(|request| request.path == path)
29444                .map(|request| {
29445                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
29446                        panic!(
29447                            "invalid JSON request body for {path}: {error}: {:?}",
29448                            request.body
29449                        )
29450                    })
29451                })
29452                .collect()
29453        }
29454    }
29455
29456    impl Drop for MockWorkerServer {
29457        fn drop(&mut self) {
29458            self.stop.store(true, Ordering::SeqCst);
29459            let _ = TcpStream::connect(self.addr);
29460
29461            if let Some(thread) = self.thread.take() {
29462                thread.join().expect("join mock server");
29463            }
29464        }
29465    }
29466
29467    fn handle_mock_worker_request(
29468        stream: &mut TcpStream,
29469        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
29470        behavior: MockWorkerBehavior,
29471    ) {
29472        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
29473        let mut buffer = [0_u8; 8192];
29474        let mut request = Vec::new();
29475
29476        loop {
29477            match stream.read(&mut buffer) {
29478                Ok(0) => break,
29479                Ok(read) => {
29480                    request.extend_from_slice(&buffer[..read]);
29481                    if mock_request_is_complete(&request) {
29482                        break;
29483                    }
29484                }
29485                Err(error)
29486                    if matches!(
29487                        error.kind(),
29488                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
29489                    ) =>
29490                {
29491                    break;
29492                }
29493                Err(_) => return,
29494            }
29495        }
29496
29497        let request = String::from_utf8_lossy(&request);
29498        let body = request
29499            .split_once("\r\n\r\n")
29500            .map(|(_, body)| body)
29501            .unwrap_or_default();
29502        let path = request
29503            .lines()
29504            .next()
29505            .and_then(|line| line.split_whitespace().nth(1))
29506            .unwrap_or_default();
29507        let method = request
29508            .lines()
29509            .next()
29510            .and_then(|line| line.split_whitespace().next())
29511            .unwrap_or_default();
29512        let authorization = request.lines().find_map(|line| {
29513            let (name, value) = line.split_once(':')?;
29514            name.eq_ignore_ascii_case("Authorization")
29515                .then(|| value.trim().to_string())
29516        });
29517        let namespace = request.lines().find_map(|line| {
29518            let (name, value) = line.split_once(':')?;
29519            name.eq_ignore_ascii_case("X-Namespace")
29520                .then(|| value.trim().to_string())
29521        });
29522        let worker_protocol = request.lines().find_map(|line| {
29523            let (name, value) = line.split_once(':')?;
29524            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
29525                .then(|| value.trim().to_string())
29526        });
29527        let control_protocol = request.lines().find_map(|line| {
29528            let (name, value) = line.split_once(':')?;
29529            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
29530                .then(|| value.trim().to_string())
29531        });
29532        let request_number = {
29533            let mut requests = requests.lock().expect("captured requests");
29534            requests.push(CapturedRequest {
29535                headers: request
29536                    .split_once("\r\n\r\n")
29537                    .map_or("", |(headers, _)| headers)
29538                    .to_owned(),
29539                method: method.to_string(),
29540                path: path.to_string(),
29541                authorization,
29542                namespace,
29543                worker_protocol: worker_protocol.clone(),
29544                control_protocol,
29545                body: body.to_string(),
29546                received_at: Instant::now(),
29547            });
29548            requests
29549                .iter()
29550                .filter(|request| request.path == path)
29551                .count()
29552        };
29553
29554        if let Some(response) = behavior
29555            .request_override
29556            .and_then(|handler| handler(path, body, request_number))
29557        {
29558            write_mock_response(stream, response.0, &response.1);
29559            return;
29560        }
29561        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
29562            write_mock_response(stream, response.0, &response.1);
29563            return;
29564        }
29565        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
29566            return;
29567        }
29568        let pressure_path = behavior
29569            .storage_path
29570            .is_some_and(|part| path.contains(part));
29571        let prior_failures = if path.ends_with("/poll") {
29572            behavior.poll_failures_per_path
29573        } else {
29574            0
29575        };
29576        if pressure_path
29577            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
29578        {
29579            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
29580            let poll_id = path
29581                .ends_with("/poll")
29582                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
29583            let mut refusal = storage_refusal(
29584                poll_id,
29585                behavior.storage_unavailable,
29586                behavior.storage_mid_poll,
29587            );
29588            if behavior.storage_wrong_poll_id {
29589                refusal["poll_request_id"] = json!("wrong-poll");
29590            }
29591            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
29592            return;
29593        }
29594        if path.contains("/storage-task/")
29595            || path.contains("/storage-activity/")
29596            || path.contains("/storage-query/")
29597        {
29598            write_mock_response(stream, "200 OK", "{}");
29599            return;
29600        }
29601        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
29602            write_mock_response(stream, "200 OK", &json!({"task":{
29603                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
29604                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
29605                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29606                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29607                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
29608            }}).to_string());
29609            return;
29610        }
29611        if behavior.storage_activity
29612            && path == "/api/worker/activity-tasks/poll"
29613            && request_number == 1
29614        {
29615            write_mock_response(stream, "200 OK", &json!({"task":{
29616                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
29617                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29618                "attempt_number":7, "lease_owner":"storage-worker"
29619            }}).to_string());
29620            return;
29621        }
29622
29623        if path == "/api/worker/register" {
29624            if behavior.reject_registration_protocol {
29625                write_mock_response(
29626                    stream,
29627                    "400 Bad Request",
29628                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
29629                );
29630                return;
29631            }
29632            if behavior.reject_registration {
29633                write_mock_response(
29634                    stream,
29635                    "503 Service Unavailable",
29636                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
29637                );
29638                return;
29639            }
29640        }
29641
29642        if path.starts_with("/api/worker/registrations/") {
29643            if behavior.reject_deregistration_protocol {
29644                write_mock_response(
29645                    stream,
29646                    "400 Bad Request",
29647                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
29648                );
29649            } else if behavior.reject_deregistration {
29650                write_mock_response(
29651                    stream,
29652                    "403 Forbidden",
29653                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
29654                );
29655            } else {
29656                write_mock_response(
29657                    stream,
29658                    "200 OK",
29659                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
29660                );
29661            }
29662            return;
29663        }
29664
29665        let is_poll = matches!(
29666            path,
29667            "/api/worker/workflow-tasks/poll"
29668                | "/api/worker/activity-tasks/poll"
29669                | "/api/worker/query-tasks/poll"
29670        );
29671        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
29672            write_mock_response(
29673                stream,
29674                "429 Too Many Requests",
29675                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
29676            );
29677            return;
29678        }
29679        if is_poll && request_number <= behavior.poll_failures_per_path {
29680            return;
29681        }
29682        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
29683            return;
29684        }
29685        if path == "/api/worker/heartbeat"
29686            && behavior.heartbeat_failure_request == Some(request_number)
29687        {
29688            return;
29689        }
29690        if path == "/api/worker/heartbeat"
29691            && behavior.delayed_heartbeat_request == Some(request_number)
29692        {
29693            thread::sleep(behavior.heartbeat_response_delay);
29694        }
29695        if behavior.unauthorized_polls && is_poll {
29696            write_mock_response(
29697                stream,
29698                "401 Unauthorized",
29699                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
29700            );
29701            return;
29702        }
29703        if behavior.draining_polls && is_poll {
29704            write_mock_response(
29705                stream,
29706                "409 Conflict",
29707                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
29708            );
29709            return;
29710        }
29711
29712        if let Some(codec_case) = behavior.invalid_task_payload_codec {
29713            if is_poll && request_number == 1 {
29714                let mut task = match path {
29715                    "/api/worker/workflow-tasks/poll" => json!({
29716                        "task_id": "codec-workflow",
29717                        "workflow_type": "codec.workflow",
29718                        "payload_codec": DEFAULT_CODEC,
29719                        "workflow_task_attempt": 1,
29720                        "lease_owner": "codec-worker"
29721                    }),
29722                    "/api/worker/activity-tasks/poll" => json!({
29723                        "task_id": "codec-activity",
29724                        "activity_attempt_id": "codec-activity-attempt",
29725                        "activity_type": "codec.activity",
29726                        "payload_codec": DEFAULT_CODEC,
29727                        "attempt_number": 1,
29728                        "lease_owner": "codec-worker"
29729                    }),
29730                    "/api/worker/query-tasks/poll" => json!({
29731                        "query_task_id": "codec-query",
29732                        "query_task_attempt": 1,
29733                        "workflow_type": "codec.workflow",
29734                        "query_name": "known",
29735                        "payload_codec": DEFAULT_CODEC,
29736                        "lease_owner": "codec-worker"
29737                    }),
29738                    _ => unreachable!("is_poll limits task codec probe paths"),
29739                };
29740                codec_case.apply(&mut task);
29741                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
29742                return;
29743            }
29744
29745            if matches!(
29746                path,
29747                "/api/worker/workflow-tasks/codec-workflow/fail"
29748                    | "/api/worker/activity-tasks/codec-activity/fail"
29749                    | "/api/worker/query-tasks/codec-query/fail"
29750            ) {
29751                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
29752                return;
29753            }
29754        }
29755
29756        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
29757            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
29758            let body = format!(
29759                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
29760            );
29761            write_mock_response(stream, "400 Bad Request", &body);
29762            return;
29763        }
29764
29765        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
29766        {
29767            write_mock_response(
29768                stream,
29769                "409 Conflict",
29770                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
29771            );
29772            return;
29773        }
29774
29775        if behavior.workflow_completion_status.is_some()
29776            && path == "/api/worker/workflow-tasks/poll"
29777            && request_number == 1
29778        {
29779            write_mock_response(
29780                stream,
29781                "200 OK",
29782                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"}}"#,
29783            );
29784            return;
29785        }
29786
29787        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
29788            if let (Some(status), Some(body)) = (
29789                behavior.workflow_completion_status,
29790                behavior.workflow_completion_body,
29791            ) {
29792                write_mock_response(stream, status, body);
29793                return;
29794            }
29795        }
29796
29797        if behavior.waiting_query_worker {
29798            if behavior.complete_named_signal
29799                && path == "/api/worker/workflow-tasks/poll"
29800                && request_number == 1
29801            {
29802                let body = json!({
29803                    "task": {
29804                        "task_id": "snapshot-open",
29805                        "workflow_id": "snapshot-1",
29806                        "run_id": "snapshot-run-1",
29807                        "workflow_type": "snapshot",
29808                        "payload_codec": DEFAULT_CODEC,
29809                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29810                            .expect("Avro workflow arguments"),
29811                        "history_events": [],
29812                        "workflow_task_attempt": 1,
29813                        "lease_owner": "rust-snapshot-worker"
29814                    }
29815                })
29816                .to_string();
29817                write_mock_response(stream, "200 OK", &body);
29818                return;
29819            }
29820
29821            let signal_request = request_number - usize::from(behavior.complete_named_signal);
29822            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
29823            if path == "/api/worker/workflow-tasks/poll"
29824                && signal_request >= 1
29825                && signal_request <= signal_request_limit
29826            {
29827                let finish = behavior.complete_named_signal && signal_request == 3;
29828                let amounts = if signal_request == 1 {
29829                    vec![3]
29830                } else {
29831                    vec![3, 5]
29832                };
29833                let task_id = if signal_request == 1 {
29834                    "snapshot-wait-3"
29835                } else if finish {
29836                    "snapshot-finish"
29837                } else {
29838                    "snapshot-wait-5"
29839                };
29840                let mut history_events = std::iter::once(json!({
29841                    "event_type": "SignalWaitOpened",
29842                    "payload": {"sequence": 1, "signal_name": "finish"}
29843                }))
29844                .chain(amounts.iter().enumerate().map(|(index, amount)| {
29845                    json!({
29846                        "event_type": "SignalReceived",
29847                        "payload": {
29848                            "signal_id": format!("increment-{amount}"),
29849                            "signal_name": "increment",
29850                            "workflow_sequence": index + 2,
29851                            "payload_codec": DEFAULT_CODEC,
29852                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29853                                .expect("Avro signal envelope")
29854                        }
29855                    })
29856                }))
29857                .collect::<Vec<_>>();
29858                let (resume_id, resume_name, resume_arguments) = if finish {
29859                    history_events.push(json!({
29860                        "event_type": "SignalReceived",
29861                        "payload": {
29862                            "signal_id": "finish",
29863                            "signal_name": "finish",
29864                            "workflow_sequence": 4,
29865                            "payload_codec": DEFAULT_CODEC,
29866                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29867                                .expect("Avro finish signal envelope")
29868                        }
29869                    }));
29870                    (
29871                        "finish".to_string(),
29872                        "finish".to_string(),
29873                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
29874                            .expect("Avro finish resume signal"),
29875                    )
29876                } else {
29877                    let amount = amounts.last().expect("amount");
29878                    (
29879                        format!("increment-{amount}"),
29880                        "increment".to_string(),
29881                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29882                            .expect("Avro increment resume signal"),
29883                    )
29884                };
29885                let body = json!({
29886                    "task": {
29887                        "task_id": task_id,
29888                        "workflow_id": "snapshot-1",
29889                        "run_id": "snapshot-run-1",
29890                        "workflow_type": "snapshot",
29891                        "payload_codec": DEFAULT_CODEC,
29892                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29893                            .expect("Avro workflow arguments"),
29894                        "history_events": history_events,
29895                        "workflow_task_attempt": 1,
29896                        "workflow_signal_id": resume_id,
29897                        "signal_name": resume_name,
29898                        "signal_arguments": resume_arguments,
29899                        "lease_owner": "rust-snapshot-worker"
29900                    }
29901                })
29902                .to_string();
29903                write_mock_response(stream, "200 OK", &body);
29904                return;
29905            }
29906
29907            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
29908                let history_events = [3, 5]
29909                    .into_iter()
29910                    .enumerate()
29911                    .map(|(index, amount)| {
29912                        json!({
29913                            "event_type": "SignalReceived",
29914                            "payload": {
29915                                "signal_id": format!("increment-{amount}"),
29916                                "signal_name": "increment",
29917                                "workflow_sequence": index + 2,
29918                                "payload_codec": DEFAULT_CODEC,
29919                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29920                                    .expect("Avro query signal envelope")
29921                            }
29922                        })
29923                    })
29924                    .collect::<Vec<_>>();
29925                let body = json!({
29926                    "task": {
29927                        "query_task_id": "snapshot-current",
29928                        "query_task_attempt": 1,
29929                        "lease_owner": "rust-snapshot-worker",
29930                        "workflow_id": "snapshot-1",
29931                        "run_id": "snapshot-run-1",
29932                        "workflow_type": "snapshot",
29933                        "query_name": "current",
29934                        "payload_codec": DEFAULT_CODEC,
29935                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29936                            .expect("Avro workflow arguments"),
29937                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29938                            .expect("Avro query arguments"),
29939                        "history_events": history_events,
29940                        "run_status": "waiting"
29941                    }
29942                })
29943                .to_string();
29944                write_mock_response(stream, "200 OK", &body);
29945                return;
29946            }
29947
29948            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
29949                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
29950            {
29951                write_mock_response(
29952                    stream,
29953                    "200 OK",
29954                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
29955                );
29956                return;
29957            }
29958
29959            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
29960                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
29961                return;
29962            }
29963
29964            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
29965                write_mock_response(
29966                    stream,
29967                    "200 OK",
29968                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
29969                );
29970                return;
29971            }
29972
29973            if path == "/api/worker/query-tasks/snapshot-current/complete" {
29974                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
29975                return;
29976            }
29977        }
29978
29979        if matches!(
29980            path,
29981            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
29982        ) {
29983            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
29984                .expect("typed mock result");
29985            let body = json!({
29986                "result": typed_fidelity_probe().into_json().expect("result projection"),
29987                "result_envelope": result,
29988            })
29989            .to_string();
29990            write_mock_response(stream, "200 OK", &body);
29991            return;
29992        }
29993
29994        if path == "/api/workflows/typed-1" {
29995            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
29996                .expect("typed mock result");
29997            let body = json!({
29998                "workflow_id": "typed-1",
29999                "run_id": "run-typed-1",
30000                "workflow_type": "typed.echo",
30001                "status": "completed",
30002                "output": typed_fidelity_probe().into_json().expect("output projection"),
30003                "output_envelope": result,
30004            })
30005            .to_string();
30006            write_mock_response(stream, "200 OK", &body);
30007            return;
30008        }
30009
30010        let (status, body) = match path {
30011            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
30012            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
30013            "/api/workflows" => (
30014                "201 Created",
30015                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
30016            ),
30017            "/api/worker/register" if behavior.decline_registration => (
30018                "200 OK",
30019                r#"{"worker_id":"declined-worker","registered":false}"#,
30020            ),
30021            "/api/worker/register" if behavior.waiting_query_worker => (
30022                "200 OK",
30023                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
30024            ),
30025            "/api/worker/register" => (
30026                "200 OK",
30027                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
30028            ),
30029            "/api/worker/heartbeat" => ("200 OK", "{}"),
30030            "/api/worker/activity-tasks/poll"
30031                if behavior.cancelled_activity && request_number == 1 =>
30032            {
30033                (
30034                    "200 OK",
30035                    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"}}"#,
30036                )
30037            }
30038            "/api/worker/activity-tasks/poll"
30039                if behavior.long_poll_capacity_responses_per_path > 0
30040                    && request_number
30041                        == behavior
30042                            .long_poll_capacity_responses_per_path
30043                            .saturating_add(1) =>
30044            {
30045                (
30046                    "200 OK",
30047                    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"}}"#,
30048                )
30049            }
30050            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
30051                ("200 OK", r#"{"task":null}"#)
30052            }
30053            "/api/worker/query-tasks/poll"
30054                if behavior.reject_query_completion && request_number == 1 =>
30055            {
30056                (
30057                    "200 OK",
30058                    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"}}"#,
30059                )
30060            }
30061            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
30062            "/api/worker/query-tasks/query-capture/complete"
30063            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
30064            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
30065                "200 OK",
30066                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
30067            ),
30068            "/api/worker/activity-tasks/activity-cancel/complete" => (
30069                "409 Conflict",
30070                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
30071            ),
30072            "/api/worker/activity-tasks/activity-typed/complete"
30073            | "/api/worker/activity-tasks/activity-typed/fail"
30074            | "/api/worker/activity-tasks/capacity-activity/complete"
30075            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
30076            "/api/workflows/counter-1/query/current" => (
30077                "200 OK",
30078                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
30079            ),
30080            "/api/workflows/counter-1/query/missing" => (
30081                "404 Not Found",
30082                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
30083            ),
30084            "/api/workflows/wf-lifecycle/cancel" => (
30085                "200 OK",
30086                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
30087            ),
30088            "/api/workflows/wf-lifecycle/terminate" => (
30089                "200 OK",
30090                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
30091            ),
30092            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
30093                "200 OK",
30094                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
30095            ),
30096            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
30097                "200 OK",
30098                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
30099            ),
30100            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
30101                "202 Accepted",
30102                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
30103            ),
30104            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
30105                "200 OK",
30106                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}"#,
30107            ),
30108            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
30109                "409 Conflict",
30110                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
30111            ),
30112            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
30113            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
30114                "409 Conflict",
30115                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
30116            ),
30117            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
30118                "200 OK",
30119                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"}]}}"#,
30120            ),
30121            "/api/workflows/wf-cancelled" => (
30122                "200 OK",
30123                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
30124            ),
30125            "/api/workflows/wf-terminated" => (
30126                "200 OK",
30127                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
30128            ),
30129            "/api/workflows/wf-timed-out" => (
30130                "200 OK",
30131                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
30132            ),
30133            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
30134                "200 OK",
30135                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
30136            ),
30137            "/api/workflows/wf-selected" => (
30138                "200 OK",
30139                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
30140            ),
30141            "/api/workflows/wf-selected/runs/run-selected" => (
30142                "200 OK",
30143                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
30144            ),
30145            _ => ("404 Not Found", r#"{"message":"not found"}"#),
30146        };
30147        write_mock_response(stream, status, body);
30148    }
30149
30150    fn mock_request_is_complete(request: &[u8]) -> bool {
30151        let Some(header_end) = request
30152            .windows(4)
30153            .position(|window| window == b"\r\n\r\n")
30154            .map(|position| position + 4)
30155        else {
30156            return false;
30157        };
30158        let headers = String::from_utf8_lossy(&request[..header_end]);
30159        let content_length = headers.lines().find_map(|line| {
30160            let (name, value) = line.split_once(':')?;
30161            name.eq_ignore_ascii_case("content-length")
30162                .then(|| value.trim().parse::<usize>().ok())
30163                .flatten()
30164        });
30165
30166        request.len() >= header_end + content_length.unwrap_or(0)
30167    }
30168
30169    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
30170        let response = format!(
30171            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
30172            body.len()
30173        );
30174
30175        let _ = stream.write_all(response.as_bytes());
30176        let _ = stream.flush();
30177    }
30178
30179    fn activity_completion_backend_recovery(
30180        path: &str,
30181        _body: &str,
30182        request_number: usize,
30183    ) -> Option<(&'static str, String)> {
30184        match path {
30185            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
30186                "200 OK",
30187                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(),
30188            )),
30189            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
30190                "503 Service Unavailable",
30191                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(),
30192            )),
30193            "/api/worker/activity-tasks/recover-activity/complete" => Some((
30194                "200 OK",
30195                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30196            )),
30197            _ => None,
30198        }
30199    }
30200
30201    fn workflow_completion_backend_recovery(
30202        path: &str,
30203        _body: &str,
30204        request_number: usize,
30205    ) -> Option<(&'static str, String)> {
30206        match path {
30207            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
30208                "200 OK",
30209                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
30210            )),
30211            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
30212                "503 Service Unavailable",
30213                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(),
30214            )),
30215            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
30216                "200 OK",
30217                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30218            )),
30219            _ => None,
30220        }
30221    }
30222
30223    fn activity_completion_stale_after_backend_recovery(
30224        path: &str,
30225        body: &str,
30226        request_number: usize,
30227    ) -> Option<(&'static str, String)> {
30228        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
30229            return Some((
30230                "409 Conflict",
30231                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(),
30232            ));
30233        }
30234        activity_completion_backend_recovery(path, body, request_number)
30235    }
30236
30237    fn activity_completion_remains_unavailable(
30238        path: &str,
30239        body: &str,
30240        request_number: usize,
30241    ) -> Option<(&'static str, String)> {
30242        if path == "/api/worker/activity-tasks/recover-activity/complete" {
30243            return activity_completion_backend_recovery(path, body, 1);
30244        }
30245        activity_completion_backend_recovery(path, body, request_number)
30246    }
30247
30248    #[tokio::test]
30249    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
30250        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30251            request_override: Some(activity_completion_backend_recovery),
30252            ..MockWorkerBehavior::default()
30253        });
30254        let client = Client::builder(server.base_url())
30255            .timeout(Duration::from_secs(2))
30256            .build()
30257            .expect("client");
30258        let handler_calls = Arc::new(AtomicUsize::new(0));
30259        let mut worker = Worker::new(client, "recover-queue")
30260            .worker_id("recover-worker")
30261            .poll_timeout(Duration::from_millis(10));
30262        worker.register_activity("recover.activity", {
30263            let handler_calls = Arc::clone(&handler_calls);
30264            move |_ctx, _args| {
30265                let handler_calls = Arc::clone(&handler_calls);
30266                async move {
30267                    handler_calls.fetch_add(1, Ordering::SeqCst);
30268                    Ok(json!("done"))
30269                }
30270            }
30271        });
30272
30273        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30274        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30275        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
30276        assert_eq!(bodies.len(), 2);
30277        assert_eq!(bodies[0], bodies[1]);
30278    }
30279
30280    #[tokio::test]
30281    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
30282        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30283            request_override: Some(workflow_completion_backend_recovery),
30284            ..MockWorkerBehavior::default()
30285        });
30286        let client = Client::builder(server.base_url())
30287            .timeout(Duration::from_secs(2))
30288            .build()
30289            .expect("client");
30290        let handler_calls = Arc::new(AtomicUsize::new(0));
30291        let mut worker = Worker::new(client, "recover-queue")
30292            .worker_id("recover-worker")
30293            .poll_timeout(Duration::from_millis(10));
30294        worker.register_workflow("recover.workflow", {
30295            let handler_calls = Arc::clone(&handler_calls);
30296            move |_ctx, _args| {
30297                let handler_calls = Arc::clone(&handler_calls);
30298                async move {
30299                    handler_calls.fetch_add(1, Ordering::SeqCst);
30300                    Ok(json!("done"))
30301                }
30302            }
30303        });
30304
30305        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
30306        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30307        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30308        assert_eq!(bodies.len(), 2);
30309        assert_eq!(bodies[0], bodies[1]);
30310    }
30311
30312    #[tokio::test]
30313    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
30314        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30315            request_override: Some(activity_completion_stale_after_backend_recovery),
30316            ..MockWorkerBehavior::default()
30317        });
30318        let client = Client::builder(server.base_url())
30319            .timeout(Duration::from_secs(2))
30320            .build()
30321            .expect("client");
30322        let handler_calls = Arc::new(AtomicUsize::new(0));
30323        let mut worker = Worker::new(client, "recover-queue")
30324            .worker_id("recover-worker")
30325            .poll_timeout(Duration::from_millis(10));
30326        worker.register_activity("recover.activity", {
30327            let handler_calls = Arc::clone(&handler_calls);
30328            move |_ctx, _args| {
30329                let handler_calls = Arc::clone(&handler_calls);
30330                async move {
30331                    handler_calls.fetch_add(1, Ordering::SeqCst);
30332                    Ok(json!("done"))
30333                }
30334            }
30335        });
30336
30337        assert_eq!(
30338            worker
30339                .run_once()
30340                .await
30341                .expect("authoritative stale outcome"),
30342            1
30343        );
30344        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30345        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
30346        assert_eq!(bodies.len(), 2);
30347        assert_eq!(bodies[0], bodies[1]);
30348    }
30349
30350    #[test]
30351    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
30352        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
30353        let response = json!({
30354            "reason":"backend_unavailable", "operation":"complete_activity_task",
30355            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
30356            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
30357            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
30358        });
30359        let path = "/worker/activity-tasks/recover-activity/complete";
30360        let error = |body: Value| Error::Http {
30361            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30362            body: body.to_string(),
30363        };
30364        assert_eq!(
30365            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
30366            Some(Duration::from_secs(1))
30367        );
30368
30369        for (field, invalid) in [
30370            ("operation", json!("poll_activity_task")),
30371            ("outcome", json!("rejected")),
30372            ("worker_id", json!("another-worker")),
30373            ("task_queue", json!("recover-queue")),
30374            ("retryable", json!(false)),
30375            ("retry_after_seconds", json!(0)),
30376            ("task_id", json!("another-task")),
30377            ("lease_owner", json!("another-worker")),
30378            ("activity_attempt_id", json!("another-attempt")),
30379        ] {
30380            let mut invalid_response = response.clone();
30381            invalid_response[field] = invalid;
30382            assert_eq!(
30383                worker_fenced_completion_retry_after(
30384                    &error(invalid_response),
30385                    path,
30386                    Some(&request)
30387                ),
30388                None,
30389                "must not retry mismatched {field}"
30390            );
30391        }
30392        assert_eq!(
30393            worker_fenced_completion_retry_after(&error(response), path, None),
30394            None
30395        );
30396    }
30397
30398    #[tokio::test]
30399    async fn shutdown_interrupts_fenced_completion_backend_wait() {
30400        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30401            request_override: Some(activity_completion_remains_unavailable),
30402            ..MockWorkerBehavior::default()
30403        });
30404        let client = Client::builder(server.base_url())
30405            .timeout(Duration::from_secs(2))
30406            .build()
30407            .expect("client");
30408        let stop = Arc::new(AtomicBool::new(false));
30409        let worker = Worker::new(client, "recover-queue")
30410            .worker_id("recover-worker")
30411            .with_storage_admission(Arc::clone(&stop));
30412        let completion = tokio::spawn(async move {
30413            worker
30414                .client
30415                .complete_activity_task(
30416                    "recover-activity",
30417                    "recover-attempt",
30418                    "recover-worker",
30419                    json!("done"),
30420                    DEFAULT_CODEC,
30421                )
30422                .await
30423        });
30424        let path = "/api/worker/activity-tasks/recover-activity/complete";
30425        tokio::time::timeout(Duration::from_secs(2), async {
30426            while server.request_count(path) == 0 {
30427                tokio::time::sleep(Duration::from_millis(10)).await;
30428            }
30429        })
30430        .await
30431        .expect("first completion request");
30432        stop.store(true, Ordering::SeqCst);
30433        let error = tokio::time::timeout(Duration::from_secs(1), completion)
30434            .await
30435            .expect("shutdown must interrupt retry wait")
30436            .expect("completion task")
30437            .expect_err("backend is still unavailable");
30438        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
30439        assert_eq!(server.request_count(path), 1);
30440    }
30441}