Skip to main content

durable_workflow/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod activity_hydration;
4mod cancellation_context;
5mod cancellation_replay_clock;
6mod cancellation_scope;
7mod cancellation_scope_history;
8mod cancellation_scope_replay;
9mod cooperative_cancellation;
10mod local_activity;
11mod runtime_payloads;
12mod runtime_uploads;
13mod sticky_worker;
14mod sticky_workflow_cache;
15mod worker_session;
16mod workflow_hydration;
17
18pub use cancellation_context::{
19    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
20};
21pub use cancellation_scope::CancellationScopeOpenReceipt;
22#[doc(hidden)]
23pub use cancellation_scope_history::{
24    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
25};
26#[doc(hidden)]
27pub use cancellation_scope_replay::CancellationScopeRequested;
28
29pub use cooperative_cancellation::{
30    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
31    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
32    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
33    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
34};
35
36use std::{
37    any::{type_name, Any, TypeId},
38    collections::{BTreeMap, BTreeSet, HashMap},
39    future::Future,
40    io::{self, Read},
41    pin::Pin,
42    sync::{
43        atomic::{AtomicBool, Ordering},
44        Arc, Mutex, OnceLock,
45    },
46    task::{Context as TaskContext, Poll},
47    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
48};
49
50use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
51use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
52use chrono::DateTime;
53use futures_util::{
54    future::OptionFuture, stream::FuturesUnordered, task::noop_waker_ref, StreamExt,
55};
56pub use local_activity::LocalActivityOptions;
57use serde::{
58    de::DeserializeOwned,
59    ser::{SerializeMap, SerializeSeq},
60    Deserialize, Deserializer, Serialize, Serializer,
61};
62pub use serde_json::{json, Value};
63use sha2::{Digest, Sha256};
64pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
65use thiserror::Error;
66pub use uuid::Uuid;
67pub use worker_session::{WorkerSession, WorkerSessionOptions};
68
69pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
70pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
71
72/// Select the worker request protocol without enabling optional capabilities.
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum WorkerProtocolVersion {
76    /// Compatibility with Servers that implement only worker protocol 1.19.
77    V119,
78    /// The default worker protocol.
79    #[default]
80    V120,
81}
82
83impl WorkerProtocolVersion {
84    fn as_str(self) -> &'static str {
85        match self {
86            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
87            Self::V120 => WORKER_PROTOCOL_VERSION,
88        }
89    }
90}
91const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
92/// First additive worker protocol that defines portable worker-affinity features.
93pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
94pub const CONTROL_PLANE_VERSION: &str = "2";
95pub const DEFAULT_CODEC: &str = "avro";
96pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
97/// Worker-registration capability for authored condition-wait occurrence identity.
98pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
99    "condition_wait_occurrence_identity";
100/// Worker-registration capability for portable memo upserts.
101pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
102/// Worker-registration capability for server-routed read-only queries.
103pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
104/// Worker-registration capability for canonical typed search attributes.
105pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
106/// Worker-registration capability for synchronous workflow updates.
107pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
108/// Worker-registration capability for durable named input streams.
109pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
110/// Worker-registration capability for persisted first-completion selection.
111pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
112pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
113pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
114pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
115pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
116pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
117/// First additive worker protocol that defines query-task transport.
118pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
119/// First additive worker protocol that defines typed search-attribute upserts.
120pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
121/// First additive worker protocol that defines portable memo upserts.
122pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
123/// First additive worker protocol that preserves declared search-attribute types.
124pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
125/// First additive worker protocol that defines external durable condition waits.
126pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
127/// First additive worker protocol that preserves authored condition-wait occurrences.
128pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
129/// First additive worker protocol that defines durable selection groups.
130pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
131
132pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
133    let Some((major, minor)) = version.split_once('.') else {
134        return false;
135    };
136    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
137}
138
139fn validate_user_signal_name(signal_name: &str) -> Result<()> {
140    if signal_name == MESSAGE_STREAM_SIGNAL {
141        return Err(Error::Codec(format!(
142            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
143        )));
144    }
145    Ok(())
146}
147
148const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
149const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
150    "Workflow task waiting for scheduled history.";
151const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
152const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
153const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
154const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
155const MAX_MEMO_ENTRIES: usize = 100;
156const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
157const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
158
159const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
160    "lease_expired",
161    "query_task_not_found",
162    "query_task_not_leased",
163    "query_task_timed_out",
164];
165
166/// Manifest for the default service-worker profile.
167///
168/// Inline local execution is enabled separately by [`Worker::local_activities`].
169/// Local execution, sessions and caching require explicit Worker configuration.
170pub fn portable_worker_affinity_capability_manifest() -> Value {
171    json!({
172        "local_activities": {
173            "supported": false,
174            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
175            "reason": "rust_worker_does_not_execute_record_local_activity",
176        },
177        "worker_sessions": {
178            "supported": false,
179            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
180            "reason": "rust_worker_has_no_typed_session_lifecycle",
181        },
182        "sticky_execution": {
183            "supported": false,
184            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
185            "reason": "rust_worker_uses_complete_durable_history_replay",
186        },
187    })
188}
189
190/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
191pub const AVRO_VALUE_SCHEMA_JSON: &str =
192    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
193pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
194pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
195const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
196
197static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
198static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
199    OnceLock::new();
200
201#[derive(Clone, Copy)]
202enum RequestProtocol {
203    ControlPlane,
204    DefaultWorker,
205    Worker(&'static str),
206}
207
208pub type Result<T> = std::result::Result<T, Error>;
209
210#[derive(Debug, Error)]
211pub enum Error {
212    #[error("transport error: {0}")]
213    Transport(#[from] reqwest::Error),
214    #[error(
215        "invalid Durable Workflow base URL: omit the SDK-owned /api suffix and pass the Server or Cloud runtime base URL; the SDK appends /api automatically"
216    )]
217    InvalidBaseUrl,
218    #[error("json error: {0}")]
219    Json(#[from] serde_json::Error),
220    #[error("http {status}: {body}")]
221    Http {
222        status: reqwest::StatusCode,
223        body: String,
224    },
225    #[error("codec error: {0}")]
226    Codec(String),
227    #[error(transparent)]
228    QueryFailed(QueryFailure),
229    #[error(transparent)]
230    Protocol(ProtocolFailure),
231    #[error(transparent)]
232    NonDeterministicReplay(ReplayFailure),
233    #[error(transparent)]
234    ChildWorkflowFailed(ChildWorkflowFailure),
235    #[error(transparent)]
236    ActivityFailed(ActivityFailure),
237    #[error(transparent)]
238    ParallelFailed(ParallelFailure),
239    #[error(transparent)]
240    SagaCompensationFailed(SagaCompensationFailure),
241    #[error(transparent)]
242    InvalidParallelGroup(ParallelGroupError),
243    #[error(transparent)]
244    DurableOperationCancelled(DurableOperationCancelled),
245    #[error(transparent)]
246    WorkflowCancellationRequested(WorkflowCancellationRequested),
247    #[error(transparent)]
248    CooperativeCancellationRequested(CooperativeCancellationRequested),
249    #[error(transparent)]
250    CancellationScopeRequested(CancellationScopeRequested),
251    #[error(transparent)]
252    WorkflowCommandRejected(WorkflowCommandRejection),
253    #[error(transparent)]
254    WorkflowFailed(WorkflowTerminalOutcome),
255    #[error(transparent)]
256    WorkflowCancelled(WorkflowTerminalOutcome),
257    #[error(transparent)]
258    WorkflowTerminated(WorkflowTerminalOutcome),
259    #[error(transparent)]
260    WorkflowTimedOut(WorkflowTerminalOutcome),
261    #[error(transparent)]
262    ActivityTaskRejected(ActivityTaskRejection),
263    #[error("workflow handler {0:?} is not registered")]
264    WorkflowNotRegistered(String),
265    #[error("activity handler {0:?} is not registered")]
266    ActivityNotRegistered(String),
267    #[error(
268        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
269    )]
270    HandlerType {
271        handler_kind: HandlerKind,
272        handler_name: String,
273        value_kind: HandlerValueKind,
274        rust_type: &'static str,
275        message: String,
276    },
277    #[error("workflow future yielded without emitting a durable command")]
278    WorkflowYieldedWithoutCommand,
279    #[error(
280        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
281    )]
282    MissingWorkflowCommandIdentity,
283    #[error("workflow state lock is poisoned")]
284    WorkflowStatePoisoned,
285    #[error("timer duration is too large for the worker protocol")]
286    TimerDurationOverflow,
287    #[error(transparent)]
288    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
289    #[error(transparent)]
290    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
291    #[error("operation timed out")]
292    Timeout,
293    #[error(
294        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
295    )]
296    MissingRoleCredentials {
297        role: &'static str,
298        opposite_role: &'static str,
299    },
300    #[error("worker loop error: {0}")]
301    WorkerLoop(String),
302    #[error(
303        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
304    )]
305    UnsupportedUpdateValidators { workflow_type: String },
306    #[error("{primary}; worker deregistration also failed: {deregistration}")]
307    WorkerShutdown {
308        primary: Box<Error>,
309        deregistration: Box<Error>,
310    },
311    #[error("invalid child workflow options: {0}")]
312    InvalidChildWorkflowOptions(String),
313    #[error("invalid workflow memo update: {0}")]
314    InvalidMemoUpdate(String),
315    #[error(
316        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
317    )]
318    WorkflowMemoUpdatesUnavailable,
319    #[error("cooperative cancellation is unavailable: {0}")]
320    CooperativeCancellationUnavailable(String),
321    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
322    CancellationScopeExecutionUnavailable,
323    #[error("invalid cooperative cancellation: {0}")]
324    InvalidCooperativeCancellation(String),
325    #[error("activity execution no longer owns its claim: {0}")]
326    ActivityExecutionAbandoned(String),
327    #[error(transparent)]
328    InvalidActivityOptions(ActivityOptionsError),
329    #[error(transparent)]
330    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
331    #[doc(hidden)]
332    #[error("workflow requested continue as new")]
333    ContinueAsNew(ContinueAsNewRequest),
334}
335
336/// Handler namespaces checked independently within a Worker.
337#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
338pub enum RegistrationKind {
339    Workflow,
340    Activity,
341    Query,
342    Update,
343}
344
345impl std::fmt::Display for RegistrationKind {
346    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347        formatter.write_str(match self {
348            Self::Workflow => "workflow",
349            Self::Activity => "activity",
350            Self::Query => "query",
351            Self::Update => "update",
352        })
353    }
354}
355
356/// The authoring adapter and source location of a handler registration.
357#[derive(Clone, Debug, PartialEq, Eq)]
358pub struct HandlerRegistration {
359    pub method: &'static str,
360    pub handler_type: &'static str,
361    pub file: &'static str,
362    pub line: u32,
363    pub column: u32,
364}
365
366impl std::fmt::Display for HandlerRegistration {
367    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368        write!(
369            formatter,
370            "{} at {}:{}:{} ({})",
371            self.method, self.file, self.line, self.column, self.handler_type
372        )
373    }
374}
375
376/// Ambiguous local configuration, rejected before contacting Server.
377#[derive(Clone, Debug, Error, PartialEq, Eq)]
378#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
379pub struct DuplicateRegistrationError {
380    pub handler_kind: RegistrationKind,
381    pub handler_name: String,
382    /// Query/update registrations are scoped to their owning workflow type.
383    pub workflow_type: Option<String>,
384    pub first_definition: HandlerRegistration,
385    pub second_definition: HandlerRegistration,
386}
387
388impl From<DuplicateRegistrationError> for Error {
389    fn from(error: DuplicateRegistrationError) -> Self {
390        Self::WorkerLoop(error.to_string())
391    }
392}
393
394/// Validation failure for a durable condition-wait definition.
395#[derive(Clone, Debug, Error, PartialEq, Eq)]
396pub enum ConditionWaitOptionsError {
397    #[error("condition_key must be non-empty")]
398    EmptyKey,
399    #[error("condition_definition_fingerprint must be non-empty")]
400    EmptyPredicateIdentity,
401    #[error("condition timeout is too large for the worker protocol")]
402    TimeoutOverflow,
403}
404
405/// Stable identity and optional durable timeout for a condition wait.
406///
407/// `predicate_identity` is recorded as the worker protocol's
408/// `condition_definition_fingerprint` and must change whenever predicate
409/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
410/// is written inline; it derives this identity from the predicate tokens.
411#[derive(Clone, Debug, PartialEq, Eq)]
412pub struct ConditionWaitOptions {
413    condition_key: String,
414    predicate_identity: String,
415    timeout: Option<Duration>,
416}
417
418impl ConditionWaitOptions {
419    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
420        Self {
421            condition_key: condition_key.into(),
422            predicate_identity: predicate_identity.into(),
423            timeout: None,
424        }
425    }
426
427    pub fn timeout(mut self, timeout: Duration) -> Self {
428        self.timeout = Some(timeout);
429        self
430    }
431
432    fn validate(
433        &self,
434    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
435        let condition_key = self.condition_key.trim();
436        if condition_key.is_empty() {
437            return Err(ConditionWaitOptionsError::EmptyKey);
438        }
439        let predicate_identity = self.predicate_identity.trim();
440        if predicate_identity.is_empty() {
441            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
442        }
443        let timeout_seconds = self
444            .timeout
445            .map(|timeout| {
446                timeout
447                    .as_secs()
448                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
449                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
450            })
451            .transpose()?;
452
453        Ok(ValidatedConditionWaitOptions {
454            condition_key: condition_key.to_string(),
455            predicate_identity: predicate_identity.to_string(),
456            timeout_seconds,
457        })
458    }
459}
460
461#[derive(Clone, Debug, PartialEq, Eq)]
462struct ValidatedConditionWaitOptions {
463    condition_key: String,
464    predicate_identity: String,
465    timeout_seconds: Option<u64>,
466}
467
468const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
469
470/// Unambiguous terminal result of a durable condition wait.
471#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
472#[serde(rename_all = "snake_case")]
473pub enum ConditionWaitResult {
474    Satisfied,
475    TimedOut,
476}
477
478impl ConditionWaitResult {
479    pub fn is_satisfied(self) -> bool {
480        self == Self::Satisfied
481    }
482
483    pub fn is_timed_out(self) -> bool {
484        self == Self::TimedOut
485    }
486}
487
488/// Build the stable condition definition identity used by [`wait_condition!`].
489#[doc(hidden)]
490pub fn __condition_definition_fingerprint(source: &str) -> String {
491    let mut digest = Sha256::new();
492    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
493    digest.update(source.as_bytes());
494    format!("sha256:{:x}", digest.finalize())
495}
496
497/// Create a durable condition wait whose predicate definition is fingerprinted
498/// from its inline Rust tokens.
499///
500/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
501/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
502#[macro_export]
503macro_rules! wait_condition {
504    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
505        $ctx.wait_condition(
506            $crate::ConditionWaitOptions::new(
507                $key,
508                $crate::__condition_definition_fingerprint(concat!(
509                    module_path!(),
510                    "\0",
511                    stringify!($predicate)
512                )),
513            )
514            .timeout($timeout),
515            $predicate,
516        )
517    }};
518    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
519        $ctx.wait_condition(
520            $crate::ConditionWaitOptions::new(
521                $key,
522                $crate::__condition_definition_fingerprint(concat!(
523                    module_path!(),
524                    "\0",
525                    stringify!($predicate)
526                )),
527            ),
528            $predicate,
529        )
530    }};
531}
532
533const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
534const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
535const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
536const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
537const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
538
539/// Validation failure for a typed workflow search-attribute update.
540#[derive(Clone, Debug, Error, PartialEq, Eq)]
541pub enum SearchAttributeUpdateError {
542    #[error("search-attribute update requires at least one attribute")]
543    Empty,
544    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
545    InvalidKey(String),
546    #[error("search-attribute update exceeds the limit of 100 attributes")]
547    TooManyAttributes,
548    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
549    ValueTooLong {
550        key: String,
551        kind: &'static str,
552        limit: usize,
553    },
554    #[error(
555        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
556    )]
557    EmptyString(String),
558    #[error("search attribute {0:?} has a non-finite float value")]
559    NonFiniteFloat(String),
560    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
561    InvalidDateTime(String),
562    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
563    PayloadTooLarge,
564}
565
566/// One public typed search-attribute value.
567#[derive(Clone, Debug, PartialEq)]
568pub enum SearchAttributeValue {
569    String(String),
570    Keyword(String),
571    KeywordList(Vec<String>),
572    Int(i64),
573    Float(f64),
574    Bool(bool),
575    DateTime(String),
576    Delete,
577}
578
579impl SearchAttributeValue {
580    fn type_name(&self) -> Option<&'static str> {
581        match self {
582            Self::String(_) => Some("string"),
583            Self::Keyword(_) => Some("keyword"),
584            Self::KeywordList(_) => Some("keyword_list"),
585            Self::Int(_) => Some("int"),
586            Self::Float(_) => Some("float"),
587            Self::Bool(_) => Some("bool"),
588            Self::DateTime(_) => Some("datetime"),
589            Self::Delete => None,
590        }
591    }
592
593    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
594        let normalize_string = |value: String, kind: &'static str, limit: usize| {
595            let value = value.trim().to_string();
596            if value.is_empty() {
597                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
598            }
599            if value.len() > limit {
600                return Err(SearchAttributeUpdateError::ValueTooLong {
601                    key: key.to_string(),
602                    kind,
603                    limit,
604                });
605            }
606            Ok(value)
607        };
608
609        match self {
610            Self::String(value) => Ok(Self::String(normalize_string(
611                value,
612                "string",
613                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
614            )?)),
615            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
616                value,
617                "keyword",
618                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
619            )?)),
620            Self::KeywordList(values) => {
621                let values = values
622                    .into_iter()
623                    .map(|value| {
624                        let value = value.trim().to_string();
625                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
626                            return Err(SearchAttributeUpdateError::ValueTooLong {
627                                key: key.to_string(),
628                                kind: "keyword-list entry",
629                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
630                            });
631                        }
632                        Ok(value)
633                    })
634                    .collect::<std::result::Result<Vec<_>, _>>()?;
635                Ok(Self::KeywordList(values))
636            }
637            Self::Float(value) if !value.is_finite() => {
638                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
639            }
640            Self::DateTime(value) => {
641                let value =
642                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
643                if DateTime::parse_from_rfc3339(&value).is_err() {
644                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
645                }
646                Ok(Self::DateTime(value))
647            }
648            value => Ok(value),
649        }
650    }
651
652    fn into_json(self) -> Value {
653        match self {
654            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
655                Value::String(value)
656            }
657            Self::KeywordList(values) => {
658                Value::Array(values.into_iter().map(Value::String).collect())
659            }
660            Self::Int(value) => json!(value),
661            Self::Float(value) => json!(value),
662            Self::Bool(value) => json!(value),
663            Self::Delete => Value::Null,
664        }
665    }
666}
667
668/// Validated typed workflow-side search-attribute mutation.
669#[derive(Clone, Debug, Default, PartialEq)]
670pub struct SearchAttributeUpdate {
671    attributes: BTreeMap<String, SearchAttributeValue>,
672}
673
674impl SearchAttributeUpdate {
675    pub fn new() -> Self {
676        Self::default()
677    }
678
679    pub fn set(
680        mut self,
681        key: impl Into<String>,
682        value: SearchAttributeValue,
683    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
684        let key = key.into();
685        validate_search_attribute_key(&key)?;
686        if !self.attributes.contains_key(&key)
687            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
688        {
689            return Err(SearchAttributeUpdateError::TooManyAttributes);
690        }
691        self.attributes.insert(key.clone(), value.normalized(&key)?);
692        self.validate_size()?;
693        Ok(self)
694    }
695
696    pub fn string(
697        self,
698        key: impl Into<String>,
699        value: impl Into<String>,
700    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
701        self.set(key, SearchAttributeValue::String(value.into()))
702    }
703
704    pub fn keyword(
705        self,
706        key: impl Into<String>,
707        value: impl Into<String>,
708    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
709        self.set(key, SearchAttributeValue::Keyword(value.into()))
710    }
711
712    pub fn keyword_list<I, V>(
713        self,
714        key: impl Into<String>,
715        values: I,
716    ) -> std::result::Result<Self, SearchAttributeUpdateError>
717    where
718        I: IntoIterator<Item = V>,
719        V: Into<String>,
720    {
721        self.set(
722            key,
723            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
724        )
725    }
726
727    pub fn int(
728        self,
729        key: impl Into<String>,
730        value: i64,
731    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
732        self.set(key, SearchAttributeValue::Int(value))
733    }
734
735    pub fn float(
736        self,
737        key: impl Into<String>,
738        value: f64,
739    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
740        self.set(key, SearchAttributeValue::Float(value))
741    }
742
743    pub fn bool(
744        self,
745        key: impl Into<String>,
746        value: bool,
747    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
748        self.set(key, SearchAttributeValue::Bool(value))
749    }
750
751    pub fn datetime(
752        self,
753        key: impl Into<String>,
754        value: impl Into<String>,
755    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
756        self.set(key, SearchAttributeValue::DateTime(value.into()))
757    }
758
759    pub fn delete(
760        self,
761        key: impl Into<String>,
762    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
763        self.set(key, SearchAttributeValue::Delete)
764    }
765
766    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
767        let (attributes, _) = self.clone().into_wire_parts();
768        if serde_json::to_vec(&attributes)
769            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
770            .unwrap_or(true)
771        {
772            return Err(SearchAttributeUpdateError::PayloadTooLarge);
773        }
774        Ok(())
775    }
776
777    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
778        let mut attributes = serde_json::Map::new();
779        let mut attribute_types = BTreeMap::new();
780        for (key, value) in self.attributes {
781            if let Some(type_name) = value.type_name() {
782                attribute_types.insert(key.clone(), type_name.to_string());
783            }
784            attributes.insert(key, value.into_json());
785        }
786        (Value::Object(attributes), attribute_types)
787    }
788
789    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
790        if self.attributes.is_empty() {
791            return Err(SearchAttributeUpdateError::Empty);
792        }
793        self.validate_size()
794    }
795}
796
797fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
798    let valid = !key.is_empty()
799        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
800        && key
801            .bytes()
802            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
803    if valid {
804        Ok(())
805    } else {
806        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
807    }
808}
809
810/// The registered handler family reported by [`Error::HandlerType`].
811#[derive(Clone, Copy, Debug, PartialEq, Eq)]
812pub enum HandlerKind {
813    Workflow,
814    Activity,
815}
816
817impl std::fmt::Display for HandlerKind {
818    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
819        formatter.write_str(match self {
820            Self::Workflow => "workflow",
821            Self::Activity => "activity",
822        })
823    }
824}
825
826/// Whether a typed handler failed to adapt its input or result.
827#[derive(Clone, Copy, Debug, PartialEq, Eq)]
828pub enum HandlerValueKind {
829    Input,
830    Result,
831}
832
833impl std::fmt::Display for HandlerValueKind {
834    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
835        formatter.write_str(match self {
836            Self::Input => "input",
837            Self::Result => "result",
838        })
839    }
840}
841
842/// The lifecycle command sent to a workflow execution.
843#[derive(Clone, Copy, Debug, PartialEq, Eq)]
844pub enum WorkflowCommandKind {
845    Cancel,
846    Terminate,
847}
848
849impl WorkflowCommandKind {
850    fn as_str(self) -> &'static str {
851        match self {
852            Self::Cancel => "cancel",
853            Self::Terminate => "terminate",
854        }
855    }
856}
857
858/// Optional structured fields for a cancellation or termination request.
859#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
860pub struct WorkflowCommandOptions {
861    #[serde(skip_serializing_if = "Option::is_none")]
862    pub reason: Option<String>,
863    #[serde(skip_serializing_if = "Option::is_none")]
864    pub request_id: Option<String>,
865}
866
867/// Server-enforced timeout policy for a workflow start.
868///
869/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
870/// only bounds how long the caller waits. A server deadline produces a terminal
871/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
872/// `run_timeout`.
873#[derive(Clone, Debug, PartialEq, Eq)]
874pub struct WorkflowStartOptions {
875    pub execution_timeout_seconds: u64,
876    pub run_timeout_seconds: u64,
877}
878
879impl Default for WorkflowStartOptions {
880    fn default() -> Self {
881        Self {
882            execution_timeout_seconds: 3600,
883            run_timeout_seconds: 600,
884        }
885    }
886}
887
888impl WorkflowStartOptions {
889    pub fn new() -> Self {
890        Self::default()
891    }
892
893    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
894        self.execution_timeout_seconds = seconds;
895        self
896    }
897
898    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
899        self.run_timeout_seconds = seconds;
900        self
901    }
902
903    fn validate(&self) -> Result<()> {
904        if self.execution_timeout_seconds == 0 {
905            return Err(Error::Codec(
906                "execution_timeout_seconds must be at least 1".to_string(),
907            ));
908        }
909        if self.run_timeout_seconds == 0 {
910            return Err(Error::Codec(
911                "run_timeout_seconds must be at least 1".to_string(),
912            ));
913        }
914        if self.run_timeout_seconds > self.execution_timeout_seconds {
915            return Err(Error::Codec(
916                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
917            ));
918        }
919
920        Ok(())
921    }
922}
923
924/// Optional routing overrides for a continue-as-new transition.
925///
926/// Omitted values retain the current workflow type and task queue. Server-owned
927/// instance metadata is not accepted here and is carried by the server.
928#[derive(Clone, Debug, Default, PartialEq, Eq)]
929pub struct ContinueAsNewOptions {
930    pub workflow_type: Option<String>,
931    pub task_queue: Option<String>,
932}
933
934impl ContinueAsNewOptions {
935    pub fn new() -> Self {
936        Self::default()
937    }
938
939    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
940        self.workflow_type = Some(workflow_type.into());
941        self
942    }
943
944    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
945        self.task_queue = Some(task_queue.into());
946        self
947    }
948
949    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
950        for (field, value) in [
951            ("workflow_type", self.workflow_type.as_deref()),
952            ("task_queue", self.task_queue.as_deref()),
953        ] {
954            if value.is_some_and(|value| value.trim().is_empty()) {
955                return Err(ContinueAsNewOptionsError {
956                    field,
957                    message: format!("{field} must not be empty"),
958                });
959            }
960        }
961        Ok(())
962    }
963}
964
965/// A stable validation error raised before a continue-as-new command is emitted.
966#[derive(Clone, Debug, Error, PartialEq, Eq)]
967#[error("invalid continue-as-new option {field}: {message}")]
968pub struct ContinueAsNewOptionsError {
969    pub field: &'static str,
970    pub message: String,
971}
972
973/// Public history-budget information attached to the current workflow task.
974#[derive(Clone, Debug, Default, PartialEq, Eq)]
975pub struct WorkflowHistoryBudget {
976    pub event_count: u64,
977    pub size_bytes: Option<u64>,
978    pub continue_as_new_recommended: bool,
979    pub pressure: Option<String>,
980}
981
982#[doc(hidden)]
983#[derive(Clone, Debug)]
984pub struct ContinueAsNewRequest {
985    arguments: AvroValue,
986    options: ContinueAsNewOptions,
987}
988
989impl WorkflowCommandOptions {
990    pub fn new() -> Self {
991        Self::default()
992    }
993
994    pub fn reason(mut self, reason: impl Into<String>) -> Self {
995        self.reason = Some(reason.into());
996        self
997    }
998
999    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1000        self.request_id = Some(request_id.into());
1001        self
1002    }
1003}
1004
1005/// The accepted, machine-readable result of a lifecycle command.
1006#[derive(Clone, Debug, PartialEq)]
1007pub struct WorkflowCommandResult {
1008    pub command: WorkflowCommandKind,
1009    pub workflow_id: String,
1010    pub run_id: Option<String>,
1011    pub outcome: Option<String>,
1012    pub reason: Option<String>,
1013    pub command_status: Option<String>,
1014    pub raw: Value,
1015}
1016
1017/// A new run continuing a failed run from its recorded activity boundary.
1018#[derive(Clone, Debug, PartialEq)]
1019pub struct WorkflowRedriveResult {
1020    pub workflow_id: String,
1021    pub source_run_id: String,
1022    pub run_id: String,
1023    pub resume_step_sequence: u64,
1024    pub raw: Value,
1025}
1026
1027/// A stable rejection returned by instance- or selected-run lifecycle commands.
1028#[derive(Clone, Debug, Error)]
1029#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1030pub struct WorkflowCommandRejection {
1031    pub command: WorkflowCommandKind,
1032    pub status: u16,
1033    pub reason: String,
1034    pub message: String,
1035    pub workflow_id: String,
1036    pub run_id: Option<String>,
1037    pub target_scope: Option<String>,
1038    pub body: Value,
1039}
1040
1041/// Stable terminal categories returned by [`WorkflowHandle::result`].
1042#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1043pub enum WorkflowTerminalKind {
1044    Failed,
1045    Cancelled,
1046    Terminated,
1047    TimedOut,
1048}
1049
1050/// A typed terminal workflow outcome with durable identity and failure metadata.
1051///
1052/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1053/// of parsing its display representation. Fields remain `None` when an older
1054/// server did not publish that metadata.
1055#[derive(Clone, Debug, Error)]
1056#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1057pub struct WorkflowTerminalOutcome {
1058    pub kind: WorkflowTerminalKind,
1059    pub workflow_id: String,
1060    pub run_id: Option<String>,
1061    pub reason: String,
1062    pub failure_category: Option<String>,
1063    pub failure_id: Option<String>,
1064    pub exception_type: Option<String>,
1065    pub exception_class: Option<String>,
1066    pub non_retryable: Option<bool>,
1067    pub message: Option<String>,
1068    pub exception: Option<Value>,
1069    pub raw: Value,
1070}
1071
1072/// A worker-side activity settlement or heartbeat rejected by durable state.
1073#[derive(Clone, Debug, Error)]
1074#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1075pub struct ActivityTaskRejection {
1076    pub operation: String,
1077    pub status: u16,
1078    pub reason: String,
1079    pub task_id: String,
1080    pub activity_attempt_id: String,
1081    pub cancel_requested: bool,
1082    pub can_continue: Option<bool>,
1083    pub run_closed_reason: Option<String>,
1084    pub body: Value,
1085}
1086
1087/// Stable validation categories for [`ActivityOptions`].
1088#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1089pub enum ActivityOptionsErrorKind {
1090    EmptyTaskQueue,
1091    EmptyRetryPolicy,
1092    InvalidMaxAttempts,
1093    BackoffWithoutRetryBudget,
1094    TooManyBackoffIntervals,
1095    InvalidBackoffCoefficient,
1096    BackoffGenerationTooLarge,
1097    BackoffOverflow,
1098    EmptyNonRetryableErrorType,
1099    TimeoutNotPositive,
1100    MissingTotalTimeout,
1101    TimeoutOverflow,
1102    TimeoutOrder,
1103}
1104
1105/// A machine-readable activity-options validation failure.
1106#[derive(Clone, Debug, Error, PartialEq, Eq)]
1107#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1108pub struct ActivityOptionsError {
1109    pub kind: ActivityOptionsErrorKind,
1110    pub field: Option<&'static str>,
1111    pub message: String,
1112}
1113
1114impl ActivityOptionsError {
1115    fn new(
1116        kind: ActivityOptionsErrorKind,
1117        field: Option<&'static str>,
1118        message: impl Into<String>,
1119    ) -> Self {
1120        Self {
1121            kind,
1122            field,
1123            message: message.into(),
1124        }
1125    }
1126}
1127
1128/// Stable terminal categories returned when an awaited activity does not succeed.
1129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1130pub enum ActivityFailureKind {
1131    Failed,
1132    Cancelled,
1133    TimedOut,
1134}
1135
1136/// A stable, machine-readable terminal activity failure.
1137///
1138/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1139/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1140#[derive(Clone, Debug, Error, PartialEq)]
1141#[error("activity failed ({reason}): {message}")]
1142pub struct ActivityFailure {
1143    pub kind: ActivityFailureKind,
1144    pub reason: String,
1145    pub message: String,
1146    pub activity_execution_id: Option<String>,
1147    pub activity_attempt_id: Option<String>,
1148    pub activity_type: Option<String>,
1149    pub activity_class: Option<String>,
1150    pub attempt_number: Option<u64>,
1151    pub failure_id: Option<String>,
1152    pub failure_category: Option<String>,
1153    pub timeout_kind: Option<String>,
1154    pub non_retryable: bool,
1155    pub exception_type: Option<String>,
1156    pub exception_class: Option<String>,
1157    pub code: Option<Value>,
1158    pub exception: Option<Value>,
1159}
1160
1161/// Stable terminal categories returned when an awaited child does not succeed.
1162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1163pub enum ChildWorkflowFailureKind {
1164    Failed,
1165    Cancelled,
1166    Terminated,
1167}
1168
1169/// A stable, machine-readable child workflow failure delivered to its parent.
1170///
1171/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1172/// of parsing the display message. Child and parent identifiers retain the
1173/// relationship recorded in durable history across worker restarts.
1174#[derive(Clone, Debug, Error)]
1175#[error("child workflow failed ({reason}): {message}")]
1176pub struct ChildWorkflowFailure {
1177    pub kind: ChildWorkflowFailureKind,
1178    pub reason: String,
1179    pub message: String,
1180    pub parent_workflow_id: Option<String>,
1181    pub parent_workflow_run_id: Option<String>,
1182    pub child_workflow_id: Option<String>,
1183    pub child_workflow_run_id: Option<String>,
1184    pub child_workflow_type: Option<String>,
1185    pub failure_id: Option<String>,
1186    pub failure_category: Option<String>,
1187    pub exception_type: Option<String>,
1188    pub exception_class: Option<String>,
1189    pub non_retryable: bool,
1190    pub code: Option<Value>,
1191    pub exception: Option<Value>,
1192}
1193
1194/// The identity of one durable workflow execution.
1195#[derive(Clone, Debug, PartialEq, Eq)]
1196pub struct WorkflowIdentity {
1197    pub workflow_id: Option<String>,
1198    pub run_id: Option<String>,
1199}
1200
1201/// A successful child result together with its durable parent-child identity.
1202#[derive(Clone, Debug, PartialEq)]
1203pub struct ChildWorkflowResult {
1204    pub parent: WorkflowIdentity,
1205    pub child: WorkflowIdentity,
1206    pub child_workflow_type: Option<String>,
1207    pub result: Value,
1208}
1209
1210/// Lossless successful child result for fixed Avro Value workflows.
1211#[derive(Clone, Debug, PartialEq)]
1212pub struct ChildWorkflowAvroResult {
1213    pub parent: WorkflowIdentity,
1214    pub child: WorkflowIdentity,
1215    pub child_workflow_type: Option<String>,
1216    pub result: AvroValue,
1217}
1218
1219/// Stable user-facing identity for one member of a durable selection group.
1220#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1221#[serde(untagged)]
1222pub enum SelectionKey {
1223    Index(usize),
1224    Name(String),
1225}
1226
1227impl From<usize> for SelectionKey {
1228    fn from(value: usize) -> Self {
1229        Self::Index(value)
1230    }
1231}
1232
1233impl From<String> for SelectionKey {
1234    fn from(value: String) -> Self {
1235        Self::Name(value)
1236    }
1237}
1238
1239impl From<&str> for SelectionKey {
1240    fn from(value: &str) -> Self {
1241        Self::Name(value.to_string())
1242    }
1243}
1244
1245/// Typed result of explicitly awaiting a cancelled non-winning operation.
1246#[derive(Clone, Debug, Error, PartialEq, Eq)]
1247#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1248pub struct DurableOperationCancelled {
1249    pub selection_group_id: String,
1250    pub member_key: SelectionKey,
1251    pub member_index: usize,
1252    pub operation_kind: String,
1253    pub operation_identity: String,
1254}
1255
1256/// Stable identity for one enclosing deterministic parallel group.
1257///
1258/// The same fields are attached to every ordinary activity, timer, or child
1259/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1260/// no Rust-specific wire command is introduced.
1261#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1262pub struct ParallelGroupMetadata {
1263    pub parallel_group_id: String,
1264    pub parallel_group_kind: String,
1265    pub parallel_group_base_sequence: u64,
1266    pub parallel_group_size: usize,
1267    pub parallel_group_index: usize,
1268    #[serde(default, skip_serializing_if = "Option::is_none")]
1269    pub parallel_group_mode: Option<String>,
1270    #[serde(default, skip_serializing_if = "Option::is_none")]
1271    pub selection_member_key: Option<SelectionKey>,
1272    #[serde(default, skip_serializing_if = "Option::is_none")]
1273    pub selection_member_index: Option<usize>,
1274    #[serde(default, skip_serializing_if = "Option::is_none")]
1275    pub selection_member_base_sequence: Option<u64>,
1276    #[serde(default, skip_serializing_if = "Option::is_none")]
1277    pub selection_member_size: Option<usize>,
1278    #[serde(default, skip_serializing_if = "Option::is_none")]
1279    pub selection_member_kind: Option<String>,
1280}
1281
1282/// One input-ordered result returned by [`WorkflowContext::parallel`].
1283#[derive(Clone, Debug, PartialEq)]
1284pub enum ParallelResult {
1285    Activity(Value),
1286    ChildWorkflow(ChildWorkflowResult),
1287    Timer,
1288    Signal(Vec<Value>),
1289    Condition(ConditionWaitResult),
1290    Group(Vec<ParallelResult>),
1291}
1292
1293/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1294#[derive(Clone, Debug, PartialEq)]
1295pub enum ParallelAvroResult {
1296    Activity(AvroValue),
1297    ChildWorkflow(ChildWorkflowAvroResult),
1298    Timer,
1299    Signal(Vec<AvroValue>),
1300    Condition(ConditionWaitResult),
1301    Group(Vec<ParallelAvroResult>),
1302}
1303
1304impl ParallelAvroResult {
1305    fn into_json_result(self) -> Result<ParallelResult> {
1306        match self {
1307            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1308            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1309                parent: result.parent,
1310                child: result.child,
1311                child_workflow_type: result.child_workflow_type,
1312                result: result.result.into_json()?,
1313            })),
1314            Self::Timer => Ok(ParallelResult::Timer),
1315            Self::Signal(values) => Ok(ParallelResult::Signal(
1316                values
1317                    .into_iter()
1318                    .map(AvroValue::into_json)
1319                    .collect::<Result<Vec<_>>>()?,
1320            )),
1321            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1322            Self::Group(results) => Ok(ParallelResult::Group(
1323                results
1324                    .into_iter()
1325                    .map(Self::into_json_result)
1326                    .collect::<Result<Vec<_>>>()?,
1327            )),
1328        }
1329    }
1330}
1331
1332/// One successful leaf retained when another parallel member failed.
1333#[derive(Clone, Debug, PartialEq)]
1334pub struct ParallelCompletion {
1335    pub member_path: Vec<usize>,
1336    pub result: ParallelResult,
1337}
1338
1339/// A deterministic join failed after some siblings had already completed.
1340///
1341/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1342/// error. `completed` is declaration ordered and contains only durable
1343/// successes observed in the same replay. Late sibling completions can add
1344/// entries on a later replay without changing `member_path` or the selected
1345/// positional failure.
1346#[derive(Debug, Error)]
1347#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1348pub struct ParallelFailure {
1349    pub group_id: String,
1350    pub member_path: Vec<usize>,
1351    pub group_path: Vec<ParallelGroupMetadata>,
1352    pub completed: Vec<ParallelCompletion>,
1353    #[source]
1354    pub cause: Box<Error>,
1355}
1356
1357/// Stable validation error returned before an invalid group emits commands.
1358#[derive(Clone, Debug, Error, PartialEq, Eq)]
1359#[error("invalid deterministic parallel group ({reason}): {message}")]
1360pub struct ParallelGroupError {
1361    pub reason: &'static str,
1362    pub member_path: Vec<usize>,
1363    pub message: String,
1364}
1365
1366/// Cooperative workflow cancellation observed at an author-controlled point.
1367#[derive(Clone, Debug, Error, PartialEq, Eq)]
1368#[error("workflow cancellation was requested")]
1369pub struct WorkflowCancellationRequested;
1370
1371/// A forward saga failure followed by a terminal compensation failure.
1372#[derive(Debug, Error)]
1373#[error(
1374    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1375)]
1376pub struct SagaCompensationFailure {
1377    pub initiating_failure: Box<Error>,
1378    pub compensation_failure: Box<Error>,
1379    pub compensation_activity_type: String,
1380    pub compensation_registration_order: usize,
1381}
1382
1383/// Server behavior when a parent closes while its child is still open.
1384#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1385pub enum ParentClosePolicy {
1386    #[default]
1387    Abandon,
1388    /// Legacy terminal cancellation without cooperative cleanup.
1389    RequestCancel,
1390    /// Request cooperative cleanup with the original lineage and deadline.
1391    RequestCancellation,
1392    Terminate,
1393}
1394
1395impl ParentClosePolicy {
1396    fn as_str(self) -> &'static str {
1397        match self {
1398            Self::Abandon => "abandon",
1399            Self::RequestCancel => "request_cancel",
1400            Self::RequestCancellation => "request_cancellation",
1401            Self::Terminate => "terminate",
1402        }
1403    }
1404}
1405
1406/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1407#[non_exhaustive]
1408#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1409pub enum CancellationPolicy {
1410    /// Request cancellation and continue without waiting. Historical Activity default.
1411    TryCancel,
1412    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1413    WaitCancellationCompleted,
1414    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1415    #[default]
1416    Abandon,
1417}
1418
1419impl CancellationPolicy {
1420    fn as_str(self) -> &'static str {
1421        match self {
1422            Self::TryCancel => "try_cancel",
1423            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1424            Self::Abandon => "abandon",
1425        }
1426    }
1427}
1428
1429/// Durable retry policy for one child workflow invocation.
1430#[derive(Clone, Debug, Default, PartialEq, Eq)]
1431pub struct ChildWorkflowRetryPolicy {
1432    pub max_attempts: Option<u32>,
1433    pub backoff_seconds: Vec<u64>,
1434    pub non_retryable_error_types: Vec<String>,
1435}
1436
1437/// Options recorded with a child-workflow command.
1438///
1439/// The task queue is mandatory so routing is explicit and replay-stable.
1440#[derive(Clone, Debug, PartialEq, Eq)]
1441pub struct ChildWorkflowOptions {
1442    pub task_queue: String,
1443    pub parent_close_policy: ParentClosePolicy,
1444    pub cancellation_policy: CancellationPolicy,
1445    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1446    pub execution_timeout_seconds: Option<u64>,
1447    pub run_timeout_seconds: Option<u64>,
1448}
1449
1450impl ChildWorkflowOptions {
1451    pub fn new(task_queue: impl Into<String>) -> Self {
1452        Self {
1453            task_queue: task_queue.into(),
1454            parent_close_policy: ParentClosePolicy::Abandon,
1455            cancellation_policy: CancellationPolicy::Abandon,
1456            retry_policy: None,
1457            execution_timeout_seconds: None,
1458            run_timeout_seconds: None,
1459        }
1460    }
1461
1462    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1463        self.parent_close_policy = policy;
1464        self
1465    }
1466
1467    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1468        self.cancellation_policy = policy;
1469        self
1470    }
1471
1472    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1473        self.retry_policy = Some(policy);
1474        self
1475    }
1476
1477    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1478        self.execution_timeout_seconds = Some(seconds);
1479        self
1480    }
1481
1482    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1483        self.run_timeout_seconds = Some(seconds);
1484        self
1485    }
1486}
1487
1488/// Backoff intervals for one durable activity retry policy.
1489#[derive(Clone, Debug, PartialEq, Eq)]
1490pub enum ActivityBackoff {
1491    /// Use these intervals between attempts. The server repeats the final
1492    /// interval if the retry budget contains more attempts than entries.
1493    Explicit(Vec<Duration>),
1494    /// Generate one interval for every retry using integer exponential growth.
1495    Exponential {
1496        initial_interval: Duration,
1497        coefficient: u32,
1498        maximum_interval: Option<Duration>,
1499    },
1500}
1501
1502/// Durable server-side retry policy for one activity execution.
1503#[derive(Clone, Debug, Default, PartialEq, Eq)]
1504pub struct ActivityRetryPolicy {
1505    pub max_attempts: Option<u32>,
1506    pub backoff: Option<ActivityBackoff>,
1507    pub non_retryable_error_types: Vec<String>,
1508}
1509
1510impl ActivityRetryPolicy {
1511    /// Start a policy with a finite attempt budget, including the first attempt.
1512    pub fn new(max_attempts: u32) -> Self {
1513        Self {
1514            max_attempts: Some(max_attempts),
1515            ..Self::default()
1516        }
1517    }
1518
1519    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1520        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1521        self
1522    }
1523
1524    pub fn exponential_backoff(
1525        mut self,
1526        initial_interval: Duration,
1527        coefficient: u32,
1528        maximum_interval: Option<Duration>,
1529    ) -> Self {
1530        self.backoff = Some(ActivityBackoff::Exponential {
1531            initial_interval,
1532            coefficient,
1533            maximum_interval,
1534        });
1535        self
1536    }
1537
1538    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1539        self.non_retryable_error_types.push(error_type.into());
1540        self
1541    }
1542
1543    pub fn non_retryable_error_types(
1544        mut self,
1545        error_types: impl IntoIterator<Item = impl Into<String>>,
1546    ) -> Self {
1547        self.non_retryable_error_types
1548            .extend(error_types.into_iter().map(Into::into));
1549        self
1550    }
1551}
1552
1553/// Options recorded atomically on one deterministic `schedule_activity` command.
1554///
1555/// Durations are rounded up to whole seconds when encoded, so the server never
1556/// receives a shorter timeout or backoff than the caller requested.
1557#[derive(Clone, Debug, Default, PartialEq, Eq)]
1558pub struct ActivityOptions {
1559    pub task_queue: Option<String>,
1560    pub retry_policy: Option<ActivityRetryPolicy>,
1561    pub start_to_close_timeout: Option<Duration>,
1562    pub schedule_to_start_timeout: Option<Duration>,
1563    pub schedule_to_close_timeout: Option<Duration>,
1564    pub heartbeat_timeout: Option<Duration>,
1565    pub cancellation_policy: Option<CancellationPolicy>,
1566}
1567
1568impl ActivityOptions {
1569    pub fn new() -> Self {
1570        Self::default()
1571    }
1572
1573    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1574        self.task_queue = Some(task_queue.into());
1575        self
1576    }
1577
1578    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1579        self.retry_policy = Some(policy);
1580        self
1581    }
1582
1583    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1584        self.start_to_close_timeout = Some(timeout);
1585        self
1586    }
1587
1588    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1589        self.schedule_to_start_timeout = Some(timeout);
1590        self
1591    }
1592
1593    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1594        self.schedule_to_close_timeout = Some(timeout);
1595        self
1596    }
1597
1598    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1599        self.heartbeat_timeout = Some(timeout);
1600        self
1601    }
1602
1603    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1604        self.cancellation_policy = Some(policy);
1605        self
1606    }
1607
1608    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1609        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1610            && self.schedule_to_close_timeout.is_none()
1611        {
1612            return Err(ActivityOptionsError::new(
1613                ActivityOptionsErrorKind::MissingTotalTimeout,
1614                Some("schedule_to_close_timeout"),
1615                "remote Activity Abandon requires a finite positive total timeout",
1616            ));
1617        }
1618        if self
1619            .task_queue
1620            .as_deref()
1621            .is_some_and(|queue| queue.trim().is_empty())
1622        {
1623            return Err(ActivityOptionsError::new(
1624                ActivityOptionsErrorKind::EmptyTaskQueue,
1625                Some("task_queue"),
1626                "task_queue must not be empty",
1627            ));
1628        }
1629
1630        for (field, value) in [
1631            ("start_to_close_timeout", self.start_to_close_timeout),
1632            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1633            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1634            ("heartbeat_timeout", self.heartbeat_timeout),
1635        ] {
1636            if value.is_some_and(|value| value.is_zero()) {
1637                return Err(ActivityOptionsError::new(
1638                    ActivityOptionsErrorKind::TimeoutNotPositive,
1639                    Some(field),
1640                    format!("{field} must be positive"),
1641                ));
1642            }
1643        }
1644
1645        validate_timeout_order(
1646            "heartbeat_timeout",
1647            self.heartbeat_timeout,
1648            "start_to_close_timeout",
1649            self.start_to_close_timeout,
1650        )?;
1651        validate_timeout_order(
1652            "start_to_close_timeout",
1653            self.start_to_close_timeout,
1654            "schedule_to_close_timeout",
1655            self.schedule_to_close_timeout,
1656        )?;
1657        validate_timeout_order(
1658            "schedule_to_start_timeout",
1659            self.schedule_to_start_timeout,
1660            "schedule_to_close_timeout",
1661            self.schedule_to_close_timeout,
1662        )?;
1663
1664        Ok(ValidatedActivityOptions {
1665            task_queue: self.task_queue.clone(),
1666            retry_policy: self
1667                .retry_policy
1668                .as_ref()
1669                .map(validate_activity_retry_policy)
1670                .transpose()?,
1671            start_to_close_timeout: timeout_seconds(
1672                "start_to_close_timeout",
1673                self.start_to_close_timeout,
1674            )?,
1675            schedule_to_start_timeout: timeout_seconds(
1676                "schedule_to_start_timeout",
1677                self.schedule_to_start_timeout,
1678            )?,
1679            schedule_to_close_timeout: timeout_seconds(
1680                "schedule_to_close_timeout",
1681                self.schedule_to_close_timeout,
1682            )?,
1683            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1684            cancellation_policy: self.cancellation_policy,
1685        })
1686    }
1687}
1688
1689/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1690///
1691/// Constructors capture arguments but perform no I/O. The join validates the
1692/// complete tree, attaches the existing parallel-group metadata to every
1693/// ordinary command, schedules all leaves, and then suspends.
1694pub enum ParallelOperation {
1695    Activity {
1696        activity_type: String,
1697        options: ActivityOptions,
1698        arguments: Result<AvroValue>,
1699    },
1700    ChildWorkflow {
1701        workflow_type: String,
1702        options: ChildWorkflowOptions,
1703        arguments: Result<AvroValue>,
1704    },
1705    Timer(Duration),
1706    Signal(String),
1707    Condition {
1708        options: ConditionWaitOptions,
1709        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1710    },
1711    Group(Vec<ParallelOperation>),
1712}
1713
1714impl ParallelOperation {
1715    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1716        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1717    }
1718
1719    pub fn activity_with_options<T: Serialize>(
1720        activity_type: impl Into<String>,
1721        options: ActivityOptions,
1722        args: T,
1723    ) -> Self {
1724        Self::Activity {
1725            activity_type: activity_type.into(),
1726            options,
1727            arguments: AvroValue::from_serialize(&args),
1728        }
1729    }
1730
1731    pub fn child_workflow<T: Serialize>(
1732        workflow_type: impl Into<String>,
1733        options: ChildWorkflowOptions,
1734        args: T,
1735    ) -> Self {
1736        Self::ChildWorkflow {
1737            workflow_type: workflow_type.into(),
1738            options,
1739            arguments: AvroValue::from_serialize(&args),
1740        }
1741    }
1742
1743    pub fn timer(duration: Duration) -> Self {
1744        Self::Timer(duration)
1745    }
1746
1747    pub fn signal(signal_name: impl Into<String>) -> Self {
1748        Self::Signal(signal_name.into())
1749    }
1750
1751    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1752    where
1753        F: Fn() -> Result<bool> + Send + 'static,
1754    {
1755        Self::Condition {
1756            options,
1757            predicate: Box::new(predicate),
1758        }
1759    }
1760
1761    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1762        Self::Group(operations)
1763    }
1764}
1765
1766#[derive(Clone, Debug)]
1767struct ValidatedActivityOptions {
1768    task_queue: Option<String>,
1769    retry_policy: Option<Value>,
1770    start_to_close_timeout: Option<u64>,
1771    schedule_to_start_timeout: Option<u64>,
1772    schedule_to_close_timeout: Option<u64>,
1773    heartbeat_timeout: Option<u64>,
1774    cancellation_policy: Option<CancellationPolicy>,
1775}
1776
1777fn validate_timeout_order(
1778    smaller_name: &'static str,
1779    smaller: Option<Duration>,
1780    larger_name: &'static str,
1781    larger: Option<Duration>,
1782) -> std::result::Result<(), ActivityOptionsError> {
1783    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1784        return Err(ActivityOptionsError::new(
1785            ActivityOptionsErrorKind::TimeoutOrder,
1786            Some(smaller_name),
1787            format!("{smaller_name} must be <= {larger_name}"),
1788        ));
1789    }
1790    Ok(())
1791}
1792
1793fn timeout_seconds(
1794    field: &'static str,
1795    value: Option<Duration>,
1796) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1797    value
1798        .map(|value| {
1799            activity_protocol_seconds(value).ok_or_else(|| {
1800                ActivityOptionsError::new(
1801                    ActivityOptionsErrorKind::TimeoutOverflow,
1802                    Some(field),
1803                    format!("{field} is too large for the worker protocol"),
1804                )
1805            })
1806        })
1807        .transpose()
1808}
1809
1810fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1811    value
1812        .as_secs()
1813        .checked_add(u64::from(value.subsec_nanos() > 0))
1814}
1815
1816fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1817    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1818}
1819
1820fn validate_activity_retry_policy(
1821    policy: &ActivityRetryPolicy,
1822) -> std::result::Result<Value, ActivityOptionsError> {
1823    if policy.max_attempts.is_none()
1824        && policy.backoff.is_none()
1825        && policy.non_retryable_error_types.is_empty()
1826    {
1827        return Err(ActivityOptionsError::new(
1828            ActivityOptionsErrorKind::EmptyRetryPolicy,
1829            Some("retry_policy"),
1830            "retry_policy must configure at least one field",
1831        ));
1832    }
1833    if policy.max_attempts == Some(0) {
1834        return Err(ActivityOptionsError::new(
1835            ActivityOptionsErrorKind::InvalidMaxAttempts,
1836            Some("retry_policy.max_attempts"),
1837            "max_attempts must be >= 1",
1838        ));
1839    }
1840    if policy
1841        .non_retryable_error_types
1842        .iter()
1843        .any(|error_type| error_type.trim().is_empty())
1844    {
1845        return Err(ActivityOptionsError::new(
1846            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
1847            Some("retry_policy.non_retryable_error_types"),
1848            "non_retryable_error_types must not contain empty values",
1849        ));
1850    }
1851
1852    let backoff_seconds = match &policy.backoff {
1853        None => None,
1854        Some(backoff) => {
1855            let max_attempts = policy.max_attempts.ok_or_else(|| {
1856                ActivityOptionsError::new(
1857                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
1858                    Some("retry_policy.backoff"),
1859                    "backoff requires max_attempts",
1860                )
1861            })?;
1862            let retry_count = max_attempts.saturating_sub(1) as usize;
1863            let intervals = match backoff {
1864                ActivityBackoff::Explicit(intervals) => {
1865                    if intervals.len() > retry_count {
1866                        return Err(ActivityOptionsError::new(
1867                            ActivityOptionsErrorKind::TooManyBackoffIntervals,
1868                            Some("retry_policy.backoff"),
1869                            "backoff interval count must not exceed max_attempts - 1",
1870                        ));
1871                    }
1872                    intervals.clone()
1873                }
1874                ActivityBackoff::Exponential {
1875                    initial_interval,
1876                    coefficient,
1877                    maximum_interval,
1878                } => {
1879                    if *coefficient < 1 {
1880                        return Err(ActivityOptionsError::new(
1881                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
1882                            Some("retry_policy.backoff.coefficient"),
1883                            "backoff coefficient must be >= 1",
1884                        ));
1885                    }
1886                    if retry_count > 10_000 {
1887                        return Err(ActivityOptionsError::new(
1888                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
1889                            Some("retry_policy.max_attempts"),
1890                            "generated backoff supports at most 10000 retry intervals",
1891                        ));
1892                    }
1893                    let mut current = *initial_interval;
1894                    let mut intervals = Vec::with_capacity(retry_count);
1895                    for _ in 0..retry_count {
1896                        let interval = maximum_interval
1897                            .map(|maximum| current.min(maximum))
1898                            .unwrap_or(current);
1899                        intervals.push(interval);
1900                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
1901                            break;
1902                        }
1903                        current = current.checked_mul(*coefficient).ok_or_else(|| {
1904                            ActivityOptionsError::new(
1905                                ActivityOptionsErrorKind::BackoffOverflow,
1906                                Some("retry_policy.backoff"),
1907                                "generated backoff interval overflowed",
1908                            )
1909                        })?;
1910                    }
1911                    intervals
1912                }
1913            };
1914            Some(
1915                intervals
1916                    .into_iter()
1917                    .map(|interval| {
1918                        activity_protocol_seconds(interval).ok_or_else(|| {
1919                            ActivityOptionsError::new(
1920                                ActivityOptionsErrorKind::BackoffOverflow,
1921                                Some("retry_policy.backoff"),
1922                                "backoff interval is too large for the worker protocol",
1923                            )
1924                        })
1925                    })
1926                    .collect::<std::result::Result<Vec<_>, _>>()?,
1927            )
1928        }
1929    };
1930
1931    let mut encoded = serde_json::Map::new();
1932    if let Some(max_attempts) = policy.max_attempts {
1933        encoded.insert("max_attempts".to_string(), json!(max_attempts));
1934    }
1935    if let Some(backoff_seconds) = backoff_seconds {
1936        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
1937    }
1938    if !policy.non_retryable_error_types.is_empty() {
1939        let mut canonical_error_types = Vec::new();
1940        for error_type in policy
1941            .non_retryable_error_types
1942            .iter()
1943            .map(|error_type| error_type.trim())
1944        {
1945            if !canonical_error_types.contains(&error_type) {
1946                canonical_error_types.push(error_type);
1947            }
1948        }
1949        encoded.insert(
1950            "non_retryable_error_types".to_string(),
1951            json!(canonical_error_types),
1952        );
1953    }
1954    Ok(Value::Object(encoded))
1955}
1956
1957/// A stable, machine-readable failure raised when workflow code no longer
1958/// reconstructs the durable command stream recorded in history.
1959#[derive(Clone, Debug, Error)]
1960#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
1961pub struct ReplayFailure {
1962    pub reason: String,
1963    pub sequence: Option<u64>,
1964    pub expected: Option<String>,
1965    pub actual: Option<String>,
1966    pub message: String,
1967}
1968
1969impl ReplayFailure {
1970    fn new(
1971        reason: impl Into<String>,
1972        sequence: Option<u64>,
1973        expected: Option<String>,
1974        actual: Option<String>,
1975        message: impl Into<String>,
1976    ) -> Self {
1977        Self {
1978            reason: reason.into(),
1979            sequence,
1980            expected,
1981            actual,
1982            message: message.into(),
1983        }
1984    }
1985}
1986
1987/// A stable, machine-readable workflow query or query-task settlement failure.
1988#[derive(Clone, Debug, Error)]
1989#[error("query failed ({reason}, HTTP {status}): {message}")]
1990pub struct QueryFailure {
1991    pub status: u16,
1992    pub reason: String,
1993    pub message: String,
1994    pub body: Value,
1995}
1996
1997/// A stable failure returned when a server rejects an SDK protocol version.
1998#[derive(Clone, Debug, Error)]
1999#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
2000pub struct ProtocolFailure {
2001    pub status: u16,
2002    pub reason: String,
2003    pub message: String,
2004    pub supported_version: Option<String>,
2005    pub requested_version: Option<String>,
2006    pub body: Value,
2007}
2008
2009#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2010pub struct PayloadEnvelope {
2011    pub codec: String,
2012    pub blob: String,
2013}
2014
2015impl PayloadEnvelope {
2016    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2017        encode_payload(value, DEFAULT_CODEC)
2018    }
2019
2020    /// Encode an explicit typed value, including the bytes branch that JSON
2021    /// serialization cannot represent.
2022    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2023        encode_avro_value(value)
2024    }
2025}
2026
2027/// Native adapter for the fixed language-neutral Avro Value schema.
2028#[derive(Clone, Debug)]
2029pub enum AvroValue {
2030    Null,
2031    Boolean(bool),
2032    Long(i64),
2033    Double(f64),
2034    Bytes(Vec<u8>),
2035    String(String),
2036    Array(Vec<AvroValue>),
2037    Map(BTreeMap<String, AvroValue>),
2038}
2039
2040impl PartialEq for AvroValue {
2041    fn eq(&self, other: &Self) -> bool {
2042        match (self, other) {
2043            (Self::Null, Self::Null) => true,
2044            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2045            (Self::Long(left), Self::Long(right)) => left == right,
2046            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2047            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2048            (Self::String(left), Self::String(right)) => left == right,
2049            (Self::Array(left), Self::Array(right)) => left == right,
2050            (Self::Map(left), Self::Map(right)) => left == right,
2051            _ => false,
2052        }
2053    }
2054}
2055
2056impl AvroValue {
2057    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2058        Self::from_serde_value(
2059            serde_value::to_value(value).map_err(|error| {
2060                Error::Codec(format!("could not adapt value for Avro: {error}"))
2061            })?,
2062        )
2063    }
2064
2065    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2066        use serde_value::Value as SerdeValue;
2067
2068        match value {
2069            SerdeValue::Unit => Ok(Self::Null),
2070            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2071            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2072            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2073            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2074            SerdeValue::I64(value) => Ok(Self::Long(value)),
2075            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2076            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2077            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2078            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2079                Error::Codec(
2080                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2081                        .to_string(),
2082                )
2083            }),
2084            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2085            SerdeValue::F64(value) => Self::finite_double(value),
2086            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2087            SerdeValue::String(value) => Ok(Self::String(value)),
2088            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2089            SerdeValue::Option(None) => Ok(Self::Null),
2090            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2091                Self::from_serde_value(*value)
2092            }
2093            SerdeValue::Seq(values) => values
2094                .into_iter()
2095                .map(Self::from_serde_value)
2096                .collect::<Result<Vec<_>>>()
2097                .map(Self::Array),
2098            SerdeValue::Map(values) => values
2099                .into_iter()
2100                .map(|(key, value)| {
2101                    let SerdeValue::String(key) = key else {
2102                        return Err(Error::Codec(
2103                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2104                        ));
2105                    };
2106
2107                    Ok((key, Self::from_serde_value(value)?))
2108                })
2109                .collect::<Result<BTreeMap<_, _>>>()
2110                .map(Self::Map),
2111        }
2112    }
2113
2114    fn finite_double(value: f64) -> Result<Self> {
2115        if !value.is_finite() {
2116            return Err(Error::Codec(
2117                "non_finite_float: Avro Value doubles must be finite".to_string(),
2118            ));
2119        }
2120
2121        Ok(Self::Double(value))
2122    }
2123
2124    fn into_json(self) -> Result<Value> {
2125        match self {
2126            Self::Null => Ok(Value::Null),
2127            Self::Boolean(value) => Ok(Value::Bool(value)),
2128            Self::Long(value) => Ok(Value::Number(value.into())),
2129            Self::Double(value) => serde_json::Number::from_f64(value)
2130                .map(Value::Number)
2131                .ok_or_else(|| {
2132                    Error::Codec(
2133                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2134                    )
2135                }),
2136            Self::Bytes(value) => Ok(json!({
2137                "$type": "bytes",
2138                "base64": BASE64.encode(value),
2139            })),
2140            Self::String(value) => Ok(Value::String(value)),
2141            Self::Array(values) => values
2142                .into_iter()
2143                .map(Self::into_json)
2144                .collect::<Result<Vec<_>>>()
2145                .map(Value::Array),
2146            Self::Map(values) => values
2147                .into_iter()
2148                .map(|(key, value)| Ok((key, value.into_json()?)))
2149                .collect::<Result<serde_json::Map<_, _>>>()
2150                .map(Value::Object),
2151        }
2152    }
2153
2154    fn into_serde_value(self) -> serde_value::Value {
2155        use serde_value::Value as SerdeValue;
2156
2157        match self {
2158            Self::Null => SerdeValue::Unit,
2159            Self::Boolean(value) => SerdeValue::Bool(value),
2160            Self::Long(value) => SerdeValue::I64(value),
2161            Self::Double(value) => SerdeValue::F64(value),
2162            Self::Bytes(value) => SerdeValue::Bytes(value),
2163            Self::String(value) => SerdeValue::String(value),
2164            Self::Array(values) => {
2165                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2166            }
2167            Self::Map(values) => SerdeValue::Map(
2168                values
2169                    .into_iter()
2170                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2171                    .collect(),
2172            ),
2173        }
2174    }
2175
2176    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2177        self.into_serde_value().deserialize_into().map_err(|error| {
2178            Error::Codec(format!(
2179                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2180            ))
2181        })
2182    }
2183}
2184
2185impl Serialize for AvroValue {
2186    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2187    where
2188        S: Serializer,
2189    {
2190        match self {
2191            Self::Null => serializer.serialize_unit(),
2192            Self::Boolean(value) => serializer.serialize_bool(*value),
2193            Self::Long(value) => serializer.serialize_i64(*value),
2194            Self::Double(value) => serializer.serialize_f64(*value),
2195            Self::Bytes(value) => serializer.serialize_bytes(value),
2196            Self::String(value) => serializer.serialize_str(value),
2197            Self::Array(values) => {
2198                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2199                for value in values {
2200                    sequence.serialize_element(value)?;
2201                }
2202                sequence.end()
2203            }
2204            Self::Map(values) => {
2205                let mut map = serializer.serialize_map(Some(values.len()))?;
2206                for (key, value) in values {
2207                    map.serialize_entry(key, value)?;
2208                }
2209                map.end()
2210            }
2211        }
2212    }
2213}
2214
2215pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2216    let datum = avro_value_to_datum(value)?;
2217    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2218        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2219    let mut bytes = Vec::with_capacity(datum.len() + 10);
2220    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2221    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2222    bytes.extend_from_slice(&datum);
2223    Ok(PayloadEnvelope {
2224        codec: DEFAULT_CODEC.to_string(),
2225        blob: BASE64.encode(bytes),
2226    })
2227}
2228
2229pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2230    if envelope.codec != DEFAULT_CODEC {
2231        return Err(unsupported_payload_codec(&envelope.codec));
2232    }
2233    decode_avro_value_blob(&envelope.blob)
2234}
2235
2236pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2237    let blob = match codec {
2238        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2239        other => return Err(unsupported_payload_codec(other)),
2240    };
2241
2242    Ok(PayloadEnvelope {
2243        codec: codec.to_string(),
2244        blob,
2245    })
2246}
2247
2248pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2249    match envelope.codec.as_str() {
2250        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2251        other => Err(unsupported_payload_codec(other)),
2252    }
2253}
2254
2255fn handler_type_error<T>(
2256    handler_kind: HandlerKind,
2257    handler_name: &str,
2258    value_kind: HandlerValueKind,
2259    message: impl Into<String>,
2260) -> Error {
2261    Error::HandlerType {
2262        handler_kind,
2263        handler_name: handler_name.to_string(),
2264        value_kind,
2265        rust_type: type_name::<T>(),
2266        message: message.into(),
2267    }
2268}
2269
2270fn decode_handler_input<T: DeserializeOwned>(
2271    arguments: AvroValue,
2272    handler_kind: HandlerKind,
2273    handler_name: &str,
2274) -> Result<T> {
2275    let argument = match arguments {
2276        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2277            arguments.pop().expect("one typed handler argument")
2278        }
2279        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2280        AvroValue::Array(arguments) => {
2281            return Err(handler_type_error::<T>(
2282                handler_kind,
2283                handler_name,
2284                HandlerValueKind::Input,
2285                format!(
2286                    "typed handlers accept one request value, but the task carried {} arguments",
2287                    arguments.len()
2288                ),
2289            ));
2290        }
2291        argument => argument,
2292    };
2293
2294    argument.deserialize().map_err(|error| {
2295        handler_type_error::<T>(
2296            handler_kind,
2297            handler_name,
2298            HandlerValueKind::Input,
2299            error.to_string(),
2300        )
2301    })
2302}
2303
2304fn encode_handler_result<T: Serialize>(
2305    result: &T,
2306    handler_kind: HandlerKind,
2307    handler_name: &str,
2308) -> Result<AvroValue> {
2309    AvroValue::from_serialize(result).map_err(|error| {
2310        handler_type_error::<T>(
2311            handler_kind,
2312            handler_name,
2313            HandlerValueKind::Result,
2314            error.to_string(),
2315        )
2316    })
2317}
2318
2319fn decode_handler_result<T: DeserializeOwned>(
2320    result: AvroValue,
2321    handler_kind: HandlerKind,
2322    handler_name: &str,
2323) -> Result<T> {
2324    result.deserialize().map_err(|error| {
2325        handler_type_error::<T>(
2326            handler_kind,
2327            handler_name,
2328            HandlerValueKind::Result,
2329            error.to_string(),
2330        )
2331    })
2332}
2333
2334#[cfg(test)]
2335fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2336    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2337}
2338
2339fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2340    validate_payload_codec(fallback_codec)?;
2341
2342    if value.is_null() {
2343        return Ok(Value::Null);
2344    }
2345
2346    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2347        return decode_blob(blob, codec);
2348    }
2349
2350    if let Some(blob) = value.as_str() {
2351        return decode_blob(blob, fallback_codec);
2352    }
2353
2354    Err(untagged_payload_value())
2355}
2356
2357fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2358    let envelope = match codec {
2359        DEFAULT_CODEC => encode_avro_value(value)?,
2360        other => return Err(unsupported_payload_codec(other)),
2361    };
2362    Ok(serde_json::to_value(envelope)?)
2363}
2364
2365fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2366    validate_payload_codec(fallback_codec)?;
2367
2368    if value.is_null() {
2369        return Ok(AvroValue::Null);
2370    }
2371
2372    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2373        validate_payload_codec(codec)?;
2374        return decode_avro_value_blob(blob);
2375    }
2376
2377    if let Some(blob) = value.as_str() {
2378        return match fallback_codec {
2379            DEFAULT_CODEC => decode_avro_value_blob(blob),
2380            other => Err(unsupported_payload_codec(other)),
2381        };
2382    }
2383
2384    Err(untagged_payload_value())
2385}
2386
2387fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2388    match value {
2389        AvroValue::Null => AvroValue::Array(Vec::new()),
2390        AvroValue::Array(_) => value,
2391        other => AvroValue::Array(vec![other]),
2392    }
2393}
2394
2395fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2396    match codec {
2397        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2398        other => Err(unsupported_payload_codec(other)),
2399    }
2400}
2401
2402fn validate_payload_codec(codec: &str) -> Result<()> {
2403    match codec {
2404        DEFAULT_CODEC => Ok(()),
2405        MISSING_TASK_PAYLOAD_CODEC => {
2406            Err(invalid_task_payload_codec("task payload_codec is missing"))
2407        }
2408        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2409        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2410            "task payload_codec must be a string",
2411        )),
2412        other => Err(unsupported_payload_codec(other)),
2413    }
2414}
2415
2416fn invalid_task_payload_codec(reason: &str) -> Error {
2417    Error::Codec(format!(
2418        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2419    ))
2420}
2421
2422fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2423    let Some(object) = value.as_object() else {
2424        return Ok(None);
2425    };
2426    if !object.contains_key("codec") && !object.contains_key("blob") {
2427        return Ok(None);
2428    }
2429
2430    let codec = object
2431        .get("codec")
2432        .and_then(Value::as_str)
2433        .ok_or_else(invalid_payload_envelope)?;
2434    validate_payload_codec(codec)?;
2435    let blob = object
2436        .get("blob")
2437        .and_then(Value::as_str)
2438        .ok_or_else(invalid_payload_envelope)?;
2439    Ok(Some((codec, blob)))
2440}
2441
2442fn invalid_payload_envelope() -> Error {
2443    Error::Codec(
2444        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2445            .to_string(),
2446    )
2447}
2448
2449fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2450    for command in commands {
2451        let Some(command) = command.as_object() else {
2452            continue;
2453        };
2454        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2455            continue;
2456        };
2457        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2458            continue;
2459        };
2460
2461        if let Some(codec) = command.get("payload_codec") {
2462            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2463            validate_payload_codec(codec)?;
2464        }
2465
2466        let payload = command
2467            .get(payload_field)
2468            .ok_or_else(invalid_payload_envelope)?;
2469        if runtime_payloads::Reference::parse(payload)?.is_none() {
2470            validate_outbound_payload_envelope(payload)?;
2471        }
2472    }
2473    Ok(())
2474}
2475
2476fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2477    if commands.iter().any(|command| {
2478        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2479            && command
2480                .get("condition_wait_occurrence_id")
2481                .and_then(Value::as_str)
2482                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2483    }) {
2484        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2485    } else if commands.iter().any(|command| {
2486        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2487            && command.get("attribute_types").is_some()
2488    }) {
2489        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2490    } else if commands
2491        .iter()
2492        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2493    {
2494        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2495    } else if commands
2496        .iter()
2497        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2498    {
2499        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2500    } else if commands.iter().any(|command| {
2501        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2502    }) {
2503        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2504    } else {
2505        MINIMUM_WORKER_PROTOCOL_VERSION
2506    }
2507}
2508
2509fn workflow_completion_protocol_version_with_message_streams(
2510    commands: &[Value],
2511    has_message_stream_metadata: bool,
2512) -> &'static str {
2513    let command_protocol = workflow_completion_protocol_version(commands);
2514    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2515        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2516    } else {
2517        command_protocol
2518    }
2519}
2520
2521fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2522    match command_type {
2523        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2524        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2525        "start_service_operation" => Some("request_payload"),
2526        "upsert_memo" => Some("entries"),
2527        _ => None,
2528    }
2529}
2530
2531fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2532    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2533        return Err(untagged_payload_value());
2534    };
2535    validate_payload_codec(codec)?;
2536    decode_avro_value_blob(blob)?;
2537    Ok(())
2538}
2539
2540fn unsupported_payload_codec(codec: &str) -> Error {
2541    Error::Codec(format!(
2542        "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"
2543    ))
2544}
2545
2546fn untagged_payload_value() -> Error {
2547    Error::Codec(
2548        "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"
2549            .to_string(),
2550    )
2551}
2552
2553fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2554    let bytes = BASE64.decode(blob).map_err(|err| {
2555        Error::Codec(format!(
2556            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2557        ))
2558    })?;
2559
2560    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2561        return Err(unsupported_payload_codec("json"));
2562    }
2563
2564    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2565        return Err(Error::Codec(
2566            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2567        ));
2568    }
2569
2570    let fingerprint: [u8; 8] = bytes[2..10]
2571        .try_into()
2572        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2573    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2574        return Err(Error::Codec(format!(
2575            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2576            fingerprint
2577                .iter()
2578                .map(|byte| format!("{byte:02x}"))
2579                .collect::<String>()
2580        )));
2581    }
2582
2583    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2584    // The current fingerprint selects the current immutable schema, so reader
2585    // resolution would only re-walk the same recursive union. Future retained
2586    // writer fingerprints supply a distinct reader schema in this branch.
2587    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2588    if datum_reader.truncated {
2589        return Err(Error::Codec(
2590            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2591        ));
2592    }
2593    let datum = datum.map_err(|err| {
2594        Error::Codec(format!(
2595            "invalid_payload_framing: malformed Avro Value datum: {err}"
2596        ))
2597    })?;
2598    if datum_reader.remaining() != 0 {
2599        return Err(Error::Codec(format!(
2600            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2601            datum_reader.remaining()
2602        )));
2603    }
2604    avro_value_from_datum(datum)
2605}
2606
2607struct StrictAvroDatumReader<'a> {
2608    bytes: &'a [u8],
2609    offset: usize,
2610    truncated: bool,
2611}
2612
2613impl<'a> StrictAvroDatumReader<'a> {
2614    fn new(bytes: &'a [u8]) -> Self {
2615        Self {
2616            bytes,
2617            offset: 0,
2618            truncated: false,
2619        }
2620    }
2621
2622    fn remaining(&self) -> usize {
2623        self.bytes.len() - self.offset
2624    }
2625}
2626
2627impl Read for StrictAvroDatumReader<'_> {
2628    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2629        let count = buffer.len().min(self.remaining());
2630        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2631        self.offset += count;
2632        if count < buffer.len() {
2633            self.truncated = true;
2634        }
2635
2636        Ok(count)
2637    }
2638}
2639
2640fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2641    let branch = match value {
2642        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2643        AvroValue::Boolean(value) => AvroDatum::Union(
2644            1,
2645            Box::new(AvroDatum::Record(vec![(
2646                "boolean".to_string(),
2647                AvroDatum::Boolean(*value),
2648            )])),
2649        ),
2650        AvroValue::Long(value) => AvroDatum::Union(
2651            2,
2652            Box::new(AvroDatum::Record(vec![(
2653                "long".to_string(),
2654                AvroDatum::Long(*value),
2655            )])),
2656        ),
2657        AvroValue::Double(value) => {
2658            if !value.is_finite() {
2659                return Err(Error::Codec(
2660                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2661                ));
2662            }
2663            AvroDatum::Union(
2664                3,
2665                Box::new(AvroDatum::Record(vec![(
2666                    "double".to_string(),
2667                    AvroDatum::Double(*value),
2668                )])),
2669            )
2670        }
2671        AvroValue::Bytes(value) => AvroDatum::Union(
2672            4,
2673            Box::new(AvroDatum::Record(vec![(
2674                "bytes".to_string(),
2675                AvroDatum::Bytes(value.clone()),
2676            )])),
2677        ),
2678        AvroValue::String(value) => AvroDatum::Union(
2679            5,
2680            Box::new(AvroDatum::Record(vec![(
2681                "string".to_string(),
2682                AvroDatum::String(value.clone()),
2683            )])),
2684        ),
2685        AvroValue::Array(values) => AvroDatum::Union(
2686            6,
2687            Box::new(AvroDatum::Record(vec![(
2688                "items".to_string(),
2689                AvroDatum::Array(
2690                    values
2691                        .iter()
2692                        .map(avro_value_to_datum)
2693                        .collect::<Result<Vec<_>>>()?,
2694                ),
2695            )])),
2696        ),
2697        AvroValue::Map(values) => AvroDatum::Union(
2698            7,
2699            Box::new(AvroDatum::Record(vec![(
2700                "entries".to_string(),
2701                AvroDatum::Array(
2702                    values
2703                        .iter()
2704                        .map(|(key, value)| {
2705                            Ok(AvroDatum::Record(vec![
2706                                ("key".to_string(), AvroDatum::String(key.clone())),
2707                                ("value".to_string(), avro_value_to_datum(value)?),
2708                            ]))
2709                        })
2710                        .collect::<Result<Vec<_>>>()?,
2711                ),
2712            )])),
2713        ),
2714    };
2715    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2716}
2717
2718fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2719    let AvroDatum::Record(mut outer) = datum else {
2720        return Err(Error::Codec(
2721            "invalid_payload_framing: datum is not a Value record".to_string(),
2722        ));
2723    };
2724    let (_, branch) = outer
2725        .pop()
2726        .filter(|(name, _)| name == "value")
2727        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2728    let AvroDatum::Union(_, branch) = branch else {
2729        return Err(Error::Codec(
2730            "invalid_payload_framing: invalid Value union".to_string(),
2731        ));
2732    };
2733    match *branch {
2734        AvroDatum::Null => Ok(AvroValue::Null),
2735        AvroDatum::Record(mut fields) => {
2736            let (name, value) = fields.pop().ok_or_else(|| {
2737                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2738            })?;
2739            match (name.as_str(), value) {
2740                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2741                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2742                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2743                    Ok(AvroValue::Double(value))
2744                }
2745                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2746                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2747                ("items", AvroDatum::Array(values)) => values
2748                    .into_iter()
2749                    .map(avro_value_from_datum)
2750                    .collect::<Result<Vec<_>>>()
2751                    .map(AvroValue::Array),
2752                ("entries", AvroDatum::Map(values)) => values
2753                    .into_iter()
2754                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2755                    .collect::<Result<BTreeMap<_, _>>>()
2756                    .map(AvroValue::Map),
2757                _ => Err(Error::Codec(
2758                    "invalid_payload_framing: unknown Value branch".to_string(),
2759                )),
2760            }
2761        }
2762        _ => Err(Error::Codec(
2763            "invalid_payload_framing: invalid Value branch".to_string(),
2764        )),
2765    }
2766}
2767
2768fn avro_value_schema() -> Result<&'static Schema> {
2769    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2770        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2771            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2772    }) {
2773        Ok(schema) => Ok(schema),
2774        Err(message) => Err(Error::Codec(message.clone())),
2775    }
2776}
2777
2778fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2779    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2780        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2781        // have the same block representation when each ordered array record
2782        // contains the map key followed by its value, so this encoding-only
2783        // adaptation lets the official encoder retain BTreeMap wire order.
2784        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2785            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2786        let entries_schema = schema
2787            .pointer_mut("/fields/0/type/7/fields/0/type")
2788            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2789        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2790            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2791        }
2792        *entries_schema = json!({
2793            "type": "array",
2794            "items": {
2795                "type": "record",
2796                "name": "MapEntry",
2797                "fields": [
2798                    {"name": "key", "type": "string"},
2799                    {"name": "value", "type": "Value"}
2800                ]
2801            }
2802        });
2803        Schema::parse_str(&schema.to_string())
2804            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2805    }) {
2806        Ok(schema) => Ok(schema),
2807        Err(message) => Err(Error::Codec(message.clone())),
2808    }
2809}
2810
2811#[derive(Clone, Debug)]
2812pub struct Client {
2813    http: reqwest::Client,
2814    hydration_timeout: Duration,
2815    base_url: String,
2816    token: Option<String>,
2817    control_token: Option<String>,
2818    worker_token: Option<String>,
2819    namespace: String,
2820    max_external_payload_bytes: usize,
2821    worker_storage_admission: Option<WorkerStorageAdmission>,
2822    cooperative_worker_protocol: bool,
2823    worker_protocol_version: WorkerProtocolVersion,
2824    local_activities_enabled: bool,
2825    worker_sessions_enabled: bool,
2826    max_concurrent_worker_sessions: usize,
2827    worker_build_id: Option<String>,
2828    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
2829    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
2830}
2831
2832impl Client {
2833    pub fn new(base_url: impl Into<String>) -> Result<Self> {
2834        Self::builder(base_url).build()
2835    }
2836
2837    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
2838        ClientBuilder {
2839            base_url: base_url.into(),
2840            token: None,
2841            control_token: None,
2842            worker_token: None,
2843            namespace: "default".to_string(),
2844            timeout: Duration::from_secs(60),
2845            max_external_payload_bytes: 64 * 1024 * 1024,
2846            worker_protocol_version: WorkerProtocolVersion::default(),
2847        }
2848    }
2849
2850    pub async fn health(&self) -> Result<Value> {
2851        self.request_json(
2852            reqwest::Method::GET,
2853            "/health",
2854            RequestProtocol::ControlPlane,
2855            Option::<&Value>::None,
2856        )
2857        .await
2858    }
2859
2860    pub async fn cluster_info(&self) -> Result<Value> {
2861        self.request_json(
2862            reqwest::Method::GET,
2863            "/cluster/info",
2864            RequestProtocol::ControlPlane,
2865            Option::<&Value>::None,
2866        )
2867        .await
2868    }
2869
2870    pub async fn start_workflow<T: Serialize>(
2871        &self,
2872        workflow_type: &str,
2873        task_queue: &str,
2874        workflow_id: &str,
2875        input: T,
2876    ) -> Result<WorkflowHandle> {
2877        self.start_workflow_with_options(
2878            workflow_type,
2879            task_queue,
2880            workflow_id,
2881            WorkflowStartOptions::default(),
2882            input,
2883        )
2884        .await
2885    }
2886
2887    /// Start a workflow with explicit server-enforced execution and run
2888    /// deadlines.
2889    pub async fn start_workflow_with_options<T: Serialize>(
2890        &self,
2891        workflow_type: &str,
2892        task_queue: &str,
2893        workflow_id: &str,
2894        options: WorkflowStartOptions,
2895        input: T,
2896    ) -> Result<WorkflowHandle> {
2897        options.validate()?;
2898        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2899        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2900        let body = json!({
2901            "workflow_id": workflow_id,
2902            "workflow_type": workflow_type,
2903            "task_queue": task_queue,
2904            "input": input_envelope,
2905            "execution_timeout_seconds": options.execution_timeout_seconds,
2906            "run_timeout_seconds": options.run_timeout_seconds
2907        });
2908
2909        let data: Value = self
2910            .request_json(
2911                reqwest::Method::POST,
2912                "/workflows",
2913                RequestProtocol::ControlPlane,
2914                Some(&body),
2915            )
2916            .await?;
2917
2918        Ok(WorkflowHandle {
2919            client: self.clone(),
2920            workflow_id: data
2921                .get("workflow_id")
2922                .and_then(Value::as_str)
2923                .unwrap_or(workflow_id)
2924                .to_string(),
2925            run_id: data
2926                .get("run_id")
2927                .and_then(Value::as_str)
2928                .map(str::to_string),
2929            workflow_type: data
2930                .get("workflow_type")
2931                .and_then(Value::as_str)
2932                .unwrap_or(workflow_type)
2933                .to_string(),
2934        })
2935    }
2936
2937    pub async fn signal_workflow<T: Serialize>(
2938        &self,
2939        workflow_id: &str,
2940        signal_name: &str,
2941        input: T,
2942    ) -> Result<Value> {
2943        self.signal_workflow_target(workflow_id, None, signal_name, input)
2944            .await
2945    }
2946
2947    /// Append one idempotently identified item to an instance-scoped input stream.
2948    pub async fn append_message_stream<T: Serialize>(
2949        &self,
2950        workflow_id: &str,
2951        stream_name: &str,
2952        message_id: &str,
2953        input: T,
2954    ) -> Result<Value> {
2955        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2956        let body = json!({
2957            "message_id": message_id,
2958            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
2959        });
2960        self.request_json(
2961            reqwest::Method::POST,
2962            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
2963            RequestProtocol::ControlPlane,
2964            Some(&body),
2965        )
2966        .await
2967    }
2968
2969    /// Signal only if `run_id` is still the current run for this instance.
2970    pub async fn signal_workflow_run<T: Serialize>(
2971        &self,
2972        workflow_id: &str,
2973        run_id: &str,
2974        signal_name: &str,
2975        input: T,
2976    ) -> Result<Value> {
2977        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input)
2978            .await
2979    }
2980
2981    async fn signal_workflow_target<T: Serialize>(
2982        &self,
2983        workflow_id: &str,
2984        run_id: Option<&str>,
2985        signal_name: &str,
2986        input: T,
2987    ) -> Result<Value> {
2988        validate_user_signal_name(signal_name)?;
2989        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
2990        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
2991        let body = json!({
2992            "input": input_envelope
2993        });
2994        let path = match run_id {
2995            Some(run_id) => {
2996                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
2997            }
2998            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
2999        };
3000        self.request_json(
3001            reqwest::Method::POST,
3002            &path,
3003            RequestProtocol::ControlPlane,
3004            Some(&body),
3005        )
3006        .await
3007    }
3008
3009    /// Close the current run as cancelled immediately.
3010    ///
3011    /// Server revokes open tasks and timers without resuming workflow code for
3012    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3013    /// request on a supporting runtime and opted-in worker.
3014    pub async fn cancel_workflow(
3015        &self,
3016        workflow_id: &str,
3017        options: WorkflowCommandOptions,
3018    ) -> Result<WorkflowCommandResult> {
3019        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3020            .await
3021    }
3022
3023    /// Close the selected run as cancelled, only if `run_id` is still current.
3024    pub async fn cancel_workflow_run(
3025        &self,
3026        workflow_id: &str,
3027        run_id: &str,
3028        options: WorkflowCommandOptions,
3029    ) -> Result<WorkflowCommandResult> {
3030        self.workflow_command(
3031            workflow_id,
3032            Some(run_id),
3033            WorkflowCommandKind::Cancel,
3034            options,
3035        )
3036        .await
3037    }
3038
3039    /// Forcefully terminate the current run for an instance.
3040    pub async fn terminate_workflow(
3041        &self,
3042        workflow_id: &str,
3043        options: WorkflowCommandOptions,
3044    ) -> Result<WorkflowCommandResult> {
3045        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3046            .await
3047    }
3048
3049    /// Forcefully terminate only if `run_id` is still current.
3050    pub async fn terminate_workflow_run(
3051        &self,
3052        workflow_id: &str,
3053        run_id: &str,
3054        options: WorkflowCommandOptions,
3055    ) -> Result<WorkflowCommandResult> {
3056        self.workflow_command(
3057            workflow_id,
3058            Some(run_id),
3059            WorkflowCommandKind::Terminate,
3060            options,
3061        )
3062        .await
3063    }
3064
3065    /// Continue a failed run from its recorded activity failure boundary.
3066    pub async fn redrive_workflow_run(
3067        &self,
3068        workflow_id: &str,
3069        failed_run_id: &str,
3070        request_id: Option<&str>,
3071    ) -> Result<WorkflowRedriveResult> {
3072        let body = request_id
3073            .map(|id| json!({"request_id": id}))
3074            .unwrap_or_else(|| json!({}));
3075        let data: Value = self
3076            .request_json(
3077                reqwest::Method::POST,
3078                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3079                RequestProtocol::ControlPlane,
3080                Some(&body),
3081            )
3082            .await?;
3083        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3084            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3085        {
3086            return Err(Error::Codec(
3087                "redrive response was not accepted".to_string(),
3088            ));
3089        }
3090        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3091            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3092        {
3093            return Err(Error::Codec(
3094                "redrive response does not match the requested source run".to_string(),
3095            ));
3096        }
3097        let run_id = data
3098            .get("run_id")
3099            .and_then(Value::as_str)
3100            .filter(|id| !id.is_empty() && *id != failed_run_id)
3101            .ok_or_else(|| {
3102                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3103            })?;
3104        let resume_step_sequence = data
3105            .get("resume_step_sequence")
3106            .and_then(Value::as_u64)
3107            .filter(|sequence| *sequence > 0)
3108            .ok_or_else(|| {
3109                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3110            })?;
3111        Ok(WorkflowRedriveResult {
3112            workflow_id: workflow_id.to_string(),
3113            source_run_id: failed_run_id.to_string(),
3114            run_id: run_id.to_string(),
3115            resume_step_sequence,
3116            raw: data,
3117        })
3118    }
3119
3120    async fn workflow_command(
3121        &self,
3122        workflow_id: &str,
3123        run_id: Option<&str>,
3124        command: WorkflowCommandKind,
3125        options: WorkflowCommandOptions,
3126    ) -> Result<WorkflowCommandResult> {
3127        let path = match run_id {
3128            Some(run_id) => format!(
3129                "/workflows/{workflow_id}/runs/{run_id}/{}",
3130                command.as_str()
3131            ),
3132            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3133        };
3134        let data = match self
3135            .request_json(
3136                reqwest::Method::POST,
3137                &path,
3138                RequestProtocol::ControlPlane,
3139                Some(&options),
3140            )
3141            .await
3142        {
3143            Ok(data) => data,
3144            Err(Error::Http { status, body }) => {
3145                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3146                    command,
3147                    status,
3148                    body,
3149                    workflow_id,
3150                    run_id,
3151                )));
3152            }
3153            Err(error) => return Err(error),
3154        };
3155
3156        Ok(workflow_command_result(command, data, workflow_id, run_id))
3157    }
3158
3159    /// Execute a named, read-only query against a running or completed workflow.
3160    ///
3161    /// Arguments and results use the platform payload envelope. Server and
3162    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3163    /// reason, HTTP status, and original response body.
3164    pub async fn query_workflow<T: Serialize>(
3165        &self,
3166        workflow_id: &str,
3167        query_name: &str,
3168        input: T,
3169    ) -> Result<Value> {
3170        self.query_workflow_target(workflow_id, None, query_name, input)
3171            .await
3172    }
3173
3174    /// Query only if `run_id` is still current, preventing accidental retargeting.
3175    pub async fn query_workflow_run<T: Serialize>(
3176        &self,
3177        workflow_id: &str,
3178        run_id: &str,
3179        query_name: &str,
3180        input: T,
3181    ) -> Result<Value> {
3182        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3183            .await
3184    }
3185
3186    /// Query a workflow and return the lossless fixed Avro Value result.
3187    pub async fn query_workflow_avro_value<T: Serialize>(
3188        &self,
3189        workflow_id: &str,
3190        query_name: &str,
3191        input: T,
3192    ) -> Result<AvroValue> {
3193        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3194            .await
3195    }
3196
3197    /// Query a selected run and return the lossless fixed Avro Value result.
3198    pub async fn query_workflow_run_avro_value<T: Serialize>(
3199        &self,
3200        workflow_id: &str,
3201        run_id: &str,
3202        query_name: &str,
3203        input: T,
3204    ) -> Result<AvroValue> {
3205        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3206            .await
3207    }
3208
3209    async fn query_workflow_avro_value_target<T: Serialize>(
3210        &self,
3211        workflow_id: &str,
3212        run_id: Option<&str>,
3213        query_name: &str,
3214        input: T,
3215    ) -> Result<AvroValue> {
3216        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3217        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3218        let path = match run_id {
3219            Some(run_id) => {
3220                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3221            }
3222            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3223        };
3224        let response: Value = match self
3225            .request_json(
3226                reqwest::Method::POST,
3227                &path,
3228                RequestProtocol::ControlPlane,
3229                Some(&body),
3230            )
3231            .await
3232        {
3233            Ok(response) => response,
3234            Err(Error::Http { status, body }) => {
3235                return Err(Error::QueryFailed(query_failure(status, body)));
3236            }
3237            Err(error) => return Err(error),
3238        };
3239
3240        let envelope = response
3241            .get("result_envelope")
3242            .filter(|envelope| !envelope.is_null())
3243            .ok_or_else(|| {
3244                Error::Codec(
3245                    "missing_payload_envelope: typed query result requires result_envelope"
3246                        .to_string(),
3247                )
3248            })?;
3249        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3250    }
3251
3252    async fn query_workflow_target<T: Serialize>(
3253        &self,
3254        workflow_id: &str,
3255        run_id: Option<&str>,
3256        query_name: &str,
3257        input: T,
3258    ) -> Result<Value> {
3259        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3260        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3261        let body = json!({
3262            "input": input_envelope
3263        });
3264        let path = match run_id {
3265            Some(run_id) => {
3266                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3267            }
3268            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3269        };
3270        let response: Value = match self
3271            .request_json(
3272                reqwest::Method::POST,
3273                &path,
3274                RequestProtocol::ControlPlane,
3275                Some(&body),
3276            )
3277            .await
3278        {
3279            Ok(response) => response,
3280            Err(Error::Http { status, body }) => {
3281                return Err(Error::QueryFailed(query_failure(status, body)));
3282            }
3283            Err(error) => return Err(error),
3284        };
3285
3286        if let Some(envelope) = response
3287            .get("result_envelope")
3288            .filter(|envelope| !envelope.is_null())
3289        {
3290            return decode_wire_value(envelope, DEFAULT_CODEC);
3291        }
3292
3293        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3294    }
3295
3296    /// Send a synchronous update using fixed Avro Value arguments.
3297    pub async fn update_workflow<T: Serialize>(
3298        &self,
3299        workflow_id: &str,
3300        update_name: &str,
3301        input: T,
3302        request_id: Option<&str>,
3303    ) -> Result<Value> {
3304        let response = self
3305            .update_workflow_response(workflow_id, update_name, input, request_id)
3306            .await?;
3307        if let Some(envelope) = response
3308            .get("result_envelope")
3309            .filter(|envelope| !envelope.is_null())
3310        {
3311            return decode_wire_value(envelope, DEFAULT_CODEC);
3312        }
3313        Ok(response.get("result").cloned().unwrap_or(response))
3314    }
3315
3316    /// Send a synchronous update and retain a bytes-capable Avro result.
3317    pub async fn update_workflow_avro_value<T: Serialize>(
3318        &self,
3319        workflow_id: &str,
3320        update_name: &str,
3321        input: T,
3322        request_id: Option<&str>,
3323    ) -> Result<AvroValue> {
3324        let response = self
3325            .update_workflow_response(workflow_id, update_name, input, request_id)
3326            .await?;
3327        let envelope = response
3328            .get("result_envelope")
3329            .filter(|envelope| !envelope.is_null())
3330            .ok_or_else(|| {
3331                Error::Codec(
3332                    "missing_payload_envelope: typed update result requires result_envelope"
3333                        .to_string(),
3334                )
3335            })?;
3336        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3337    }
3338
3339    async fn update_workflow_response<T: Serialize>(
3340        &self,
3341        workflow_id: &str,
3342        update_name: &str,
3343        input: T,
3344        request_id: Option<&str>,
3345    ) -> Result<Value> {
3346        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3347        let mut body = json!({
3348            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3349            "wait_for": "completed",
3350        });
3351        if let Some(request_id) = request_id {
3352            body["request_id"] = json!(request_id);
3353        }
3354        self.request_json(
3355            reqwest::Method::POST,
3356            &format!("/workflows/{workflow_id}/update/{update_name}"),
3357            RequestProtocol::ControlPlane,
3358            Some(&body),
3359        )
3360        .await
3361    }
3362
3363    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3364        let path = format!("/workflows/{workflow_id}");
3365        let mut data: WorkflowDescription = self
3366            .request_json(
3367                reqwest::Method::GET,
3368                &path,
3369                RequestProtocol::ControlPlane,
3370                Option::<&Value>::None,
3371            )
3372            .await?;
3373        data.decode_payloads()?;
3374        Ok(data)
3375    }
3376
3377    /// Describe one selected run, including historical terminal runs.
3378    pub async fn describe_workflow_run(
3379        &self,
3380        workflow_id: &str,
3381        run_id: &str,
3382    ) -> Result<WorkflowDescription> {
3383        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3384        let mut data: WorkflowDescription = self
3385            .request_json(
3386                reqwest::Method::GET,
3387                &path,
3388                RequestProtocol::ControlPlane,
3389                Option::<&Value>::None,
3390            )
3391            .await?;
3392        data.decode_payloads()?;
3393        Ok(data)
3394    }
3395
3396    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3397        let mut path = format!(
3398            "/workflows/{}/runs/{}/streams",
3399            percent_encode_path_segment(workflow_id),
3400            percent_encode_path_segment(run_id),
3401        );
3402        if let Some(stream_name) = stream_name {
3403            path.push('/');
3404            path.push_str(&percent_encode_path_segment(stream_name));
3405        }
3406        path
3407    }
3408
3409    /// List the run-scoped output streams already opened by a workflow.
3410    pub async fn list_workflow_streams(
3411        &self,
3412        workflow_id: &str,
3413        run_id: &str,
3414    ) -> Result<Vec<WorkflowStreamDescription>> {
3415        let response: WorkflowStreamListResponse = self
3416            .request_json(
3417                reqwest::Method::GET,
3418                &Self::workflow_stream_path(workflow_id, run_id, None),
3419                RequestProtocol::ControlPlane,
3420                Option::<&Value>::None,
3421            )
3422            .await?;
3423        Ok(response.streams)
3424    }
3425
3426    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3427    pub async fn describe_workflow_stream(
3428        &self,
3429        workflow_id: &str,
3430        run_id: &str,
3431        stream_name: &str,
3432    ) -> Result<WorkflowStreamDescription> {
3433        let response: WorkflowStreamDescriptionResponse = self
3434            .request_json(
3435                reqwest::Method::GET,
3436                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3437                RequestProtocol::ControlPlane,
3438                Option::<&Value>::None,
3439            )
3440            .await?;
3441        Ok(response.stream)
3442    }
3443
3444    /// Read one bounded page beginning at a zero-based offset.
3445    ///
3446    /// Delivery is at least once: persist `next_offset` only after processing
3447    /// the page. The future is cancellation-safe; dropping it cancels the
3448    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3449    /// service contract.
3450    pub async fn subscribe_workflow_stream(
3451        &self,
3452        workflow_id: &str,
3453        run_id: &str,
3454        stream_name: &str,
3455        from_offset: u64,
3456        max_items: usize,
3457        wait: Duration,
3458    ) -> Result<WorkflowStreamPage> {
3459        let max_items = max_items.clamp(1, 500);
3460        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3461        let path = format!(
3462            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3463            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3464        );
3465        let response: WorkflowStreamPageResponse = self
3466            .request_json_with_timeout(
3467                reqwest::Method::GET,
3468                &path,
3469                RequestProtocol::ControlPlane,
3470                Option::<&Value>::None,
3471                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3472            )
3473            .await?;
3474
3475        let items = response
3476            .items
3477            .into_iter()
3478            .map(|raw| {
3479                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3480                let envelope = raw.get("payload").cloned();
3481                let payload = envelope
3482                    .as_ref()
3483                    .filter(|value| value.get("blob").is_some())
3484                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3485                    .transpose()?
3486                    .map(AvroValue::into_json)
3487                    .transpose()?;
3488                Ok(WorkflowStreamItem {
3489                    offset,
3490                    payload,
3491                    payload_envelope: envelope,
3492                    payload_reference: raw
3493                        .get("payload_reference")
3494                        .and_then(Value::as_str)
3495                        .map(str::to_string),
3496                    payload_codec: raw
3497                        .get("payload_codec")
3498                        .and_then(Value::as_str)
3499                        .map(str::to_string),
3500                    idempotency_key: raw
3501                        .get("idempotency_key")
3502                        .and_then(Value::as_str)
3503                        .map(str::to_string),
3504                    item_type: raw
3505                        .get("item_type")
3506                        .and_then(Value::as_str)
3507                        .map(str::to_string),
3508                    content_type: raw
3509                        .get("content_type")
3510                        .and_then(Value::as_str)
3511                        .map(str::to_string),
3512                    origin: raw
3513                        .get("origin")
3514                        .and_then(Value::as_str)
3515                        .map(str::to_string),
3516                    origin_reference: raw
3517                        .get("origin_reference")
3518                        .and_then(Value::as_str)
3519                        .map(str::to_string),
3520                    emitted_at: raw
3521                        .get("emitted_at")
3522                        .and_then(Value::as_str)
3523                        .map(str::to_string),
3524                    raw,
3525                })
3526            })
3527            .collect::<Result<Vec<_>>>()?;
3528        Ok(WorkflowStreamPage {
3529            stream: response.stream,
3530            items,
3531            next_offset: response.next_offset,
3532            terminal: response.terminal,
3533        })
3534    }
3535
3536    /// Append inline Avro envelopes or opaque external payload references.
3537    pub async fn append_workflow_stream(
3538        &self,
3539        workflow_id: &str,
3540        run_id: &str,
3541        stream_name: &str,
3542        items: &[WorkflowStreamAppendItem],
3543        max_pending_items: Option<u64>,
3544    ) -> Result<WorkflowStreamAppendResult> {
3545        if items.is_empty() {
3546            return Err(Error::Codec(
3547                "workflow_stream_items_empty: append requires at least one item".to_string(),
3548            ));
3549        }
3550        let mut body = json!({
3551            "items": items
3552                .iter()
3553                .map(|item| item.wire_value(None))
3554                .collect::<Vec<_>>(),
3555        });
3556        if let Some(max_pending_items) = max_pending_items {
3557            if max_pending_items == 0 {
3558                return Err(Error::Codec(
3559                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3560                        .to_string(),
3561                ));
3562            }
3563            body["max_pending_items"] = json!(max_pending_items);
3564        }
3565        let response: WorkflowStreamAppendResponse = self
3566            .request_json(
3567                reqwest::Method::POST,
3568                &format!(
3569                    "{}/items",
3570                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3571                ),
3572                RequestProtocol::ControlPlane,
3573                Some(&body),
3574            )
3575            .await?;
3576        Ok(WorkflowStreamAppendResult {
3577            stream: response.stream,
3578            accepted_offsets: response.accepted_offsets,
3579            accepted: response.accepted,
3580            deduped: response.deduped,
3581        })
3582    }
3583
3584    /// Close a stream, or mark it errored when `error_reason` is supplied.
3585    pub async fn close_workflow_stream(
3586        &self,
3587        workflow_id: &str,
3588        run_id: &str,
3589        stream_name: &str,
3590        error_reason: Option<&str>,
3591        retention_seconds: Option<u64>,
3592    ) -> Result<WorkflowStreamDescription> {
3593        let mut body = json!({});
3594        if let Some(error_reason) = error_reason {
3595            body["error_reason"] = json!(error_reason);
3596        }
3597        if let Some(retention_seconds) = retention_seconds {
3598            if retention_seconds == 0 {
3599                return Err(Error::Codec(
3600                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3601                        .to_string(),
3602                ));
3603            }
3604            body["retention_seconds"] = json!(retention_seconds);
3605        }
3606        let response: WorkflowStreamDescriptionResponse = self
3607            .request_json(
3608                reqwest::Method::POST,
3609                &format!(
3610                    "{}/close",
3611                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3612                ),
3613                RequestProtocol::ControlPlane,
3614                Some(&body),
3615            )
3616            .await?;
3617        Ok(response.stream)
3618    }
3619
3620    pub async fn register_worker(
3621        &self,
3622        worker_id: &str,
3623        task_queue: &str,
3624        supported_workflow_types: Vec<String>,
3625        supported_activity_types: Vec<String>,
3626        max_concurrent_workflow_tasks: usize,
3627        max_concurrent_activity_tasks: usize,
3628    ) -> Result<RegisterWorkerResponse> {
3629        self.register_worker_with_capabilities(
3630            worker_id,
3631            task_queue,
3632            supported_workflow_types,
3633            supported_activity_types,
3634            max_concurrent_workflow_tasks,
3635            max_concurrent_activity_tasks,
3636            Vec::new(),
3637        )
3638        .await
3639    }
3640
3641    /// Register a worker and explicitly advertise additive worker capabilities.
3642    pub async fn register_worker_with_capabilities(
3643        &self,
3644        worker_id: &str,
3645        task_queue: &str,
3646        supported_workflow_types: Vec<String>,
3647        supported_activity_types: Vec<String>,
3648        max_concurrent_workflow_tasks: usize,
3649        max_concurrent_activity_tasks: usize,
3650        capabilities: Vec<String>,
3651    ) -> Result<RegisterWorkerResponse> {
3652        self.register_worker_with_command_contracts(
3653            worker_id,
3654            task_queue,
3655            supported_workflow_types,
3656            supported_activity_types,
3657            max_concurrent_workflow_tasks,
3658            max_concurrent_activity_tasks,
3659            capabilities,
3660            Value::Object(serde_json::Map::new()),
3661        )
3662        .await
3663    }
3664
3665    /// Register a worker and advertise its named query and update handlers.
3666    ///
3667    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3668    /// so a workflow contract with a non-empty or malformed
3669    /// `update_validators` declaration returns
3670    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3671    #[allow(clippy::too_many_arguments)]
3672    pub async fn register_worker_with_command_contracts(
3673        &self,
3674        worker_id: &str,
3675        task_queue: &str,
3676        supported_workflow_types: Vec<String>,
3677        supported_activity_types: Vec<String>,
3678        max_concurrent_workflow_tasks: usize,
3679        max_concurrent_activity_tasks: usize,
3680        capabilities: Vec<String>,
3681        workflow_command_contracts: Value,
3682    ) -> Result<RegisterWorkerResponse> {
3683        self.register_worker_with_definition_fingerprints(
3684            worker_id,
3685            task_queue,
3686            supported_workflow_types,
3687            supported_activity_types,
3688            max_concurrent_workflow_tasks,
3689            max_concurrent_activity_tasks,
3690            capabilities,
3691            workflow_command_contracts,
3692            None,
3693        )
3694        .await
3695    }
3696
3697    #[allow(clippy::too_many_arguments)]
3698    async fn register_worker_with_definition_fingerprints(
3699        &self,
3700        worker_id: &str,
3701        task_queue: &str,
3702        supported_workflow_types: Vec<String>,
3703        supported_activity_types: Vec<String>,
3704        max_concurrent_workflow_tasks: usize,
3705        max_concurrent_activity_tasks: usize,
3706        capabilities: Vec<String>,
3707        workflow_command_contracts: Value,
3708        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
3709    ) -> Result<RegisterWorkerResponse> {
3710        if let Some(contracts) = workflow_command_contracts.as_object() {
3711            for (workflow_type, contract) in contracts {
3712                let Some(update_validators) = contract.get("update_validators") else {
3713                    continue;
3714                };
3715                if !update_validators
3716                    .as_array()
3717                    .is_some_and(|validators| validators.is_empty())
3718                {
3719                    return Err(Error::UnsupportedUpdateValidators {
3720                        workflow_type: workflow_type.clone(),
3721                    });
3722                }
3723            }
3724        }
3725
3726        let mut body = json!({
3727            "worker_id": worker_id,
3728            "task_queue": task_queue,
3729            "runtime": "rust",
3730            "sdk_version": SDK_VERSION,
3731            "supported_workflow_types": supported_workflow_types,
3732            "supported_activity_types": supported_activity_types,
3733            "capabilities": capabilities,
3734            "capability_manifest": portable_worker_affinity_capability_manifest(),
3735            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
3736            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
3737        });
3738        if let Some(build_id) = &self.worker_build_id {
3739            if build_id.is_empty() || build_id.len() > 255 {
3740                return Err(Error::WorkerLoop(
3741                    "worker build ID must contain 1 to 255 bytes".into(),
3742                ));
3743            }
3744            body["build_id"] = json!(build_id);
3745        }
3746        if self.sticky_cache.is_some() {
3747            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
3748                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
3749                "implementation":"bounded_durable_history_cache"});
3750        }
3751        if self.local_activities_enabled {
3752            body["capability_manifest"]["local_activities"] = json!({"supported":true,
3753                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3754        }
3755        if self.worker_sessions_enabled {
3756            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
3757                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
3758            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
3759        }
3760        if workflow_command_contracts
3761            .as_object()
3762            .is_some_and(|contracts| !contracts.is_empty())
3763        {
3764            body["workflow_command_contracts"] = workflow_command_contracts;
3765        }
3766        if let Some(fingerprints) = workflow_definition_fingerprints {
3767            body["workflow_definition_fingerprints"] = json!(fingerprints);
3768        }
3769
3770        let response: Value = self
3771            .request_json(
3772                reqwest::Method::POST,
3773                "/worker/register",
3774                RequestProtocol::DefaultWorker,
3775                Some(&body),
3776            )
3777            .await?;
3778        if self.sticky_cache.is_some() {
3779            self.confirm_sticky_registration(&response, worker_id, task_queue)
3780                .await?;
3781        }
3782        if self.local_activities_enabled || self.worker_sessions_enabled {
3783            let compatible = response["registered"].as_bool() == Some(true)
3784                && response["worker_id"].as_str() == Some(worker_id)
3785                && response["namespace"].as_str() == Some(self.namespace.as_str())
3786                && response["task_queue"].as_str() == Some(task_queue)
3787                && response["protocol_version"]
3788                    .as_str()
3789                    .and_then(|version| version.strip_prefix("1."))
3790                    .and_then(|minor| minor.parse::<u64>().ok())
3791                    .is_some_and(|minor| minor >= 18)
3792                && (!self.local_activities_enabled
3793                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
3794                        == Some(true))
3795                && (!self.worker_sessions_enabled
3796                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
3797                        == Some(true)
3798                        && response["capabilities"].as_array().is_some_and(|accepted| {
3799                            capabilities.iter().all(|capability| {
3800                                accepted
3801                                    .iter()
3802                                    .any(|value| value.as_str() == Some(capability.as_str()))
3803                            })
3804                        })));
3805            if !compatible {
3806                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
3807                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
3808                } else {
3809                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
3810                });
3811                if response["registered"] == true
3812                    && response["worker_id"].as_str() == Some(worker_id)
3813                {
3814                    if let Err(deregistration) =
3815                        self.deregister_worker_registration(worker_id).await
3816                    {
3817                        return Err(Error::WorkerShutdown {
3818                            primary: Box::new(error),
3819                            deregistration: Box::new(deregistration),
3820                        });
3821                    }
3822                }
3823                return Err(error);
3824            }
3825        }
3826        if self.cooperative_worker_protocol {
3827            let compatible = response["registered"].as_bool() == Some(true)
3828                && response["worker_id"].as_str() == Some(worker_id)
3829                && response["namespace"].as_str() == Some(self.namespace.as_str())
3830                && response["task_queue"].as_str() == Some(task_queue)
3831                && response["protocol_version"]
3832                    .as_str()
3833                    .is_some_and(cooperative_cancellation::supports_protocol)
3834                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
3835                    == Some(true)
3836                && response["capabilities"].as_array().is_some_and(|accepted| {
3837                    capabilities.iter().all(|capability| {
3838                        accepted
3839                            .iter()
3840                            .any(|value| value.as_str() == Some(capability.as_str()))
3841                    })
3842                });
3843            if !compatible {
3844                let error = Error::CooperativeCancellationUnavailable(
3845                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
3846                );
3847                if response["registered"].as_bool() == Some(true)
3848                    && response["worker_id"].as_str() == Some(worker_id)
3849                {
3850                    if let Err(deregistration) =
3851                        self.deregister_worker_registration(worker_id).await
3852                    {
3853                        return Err(Error::WorkerShutdown {
3854                            primary: Box::new(error),
3855                            deregistration: Box::new(deregistration),
3856                        });
3857                    }
3858                }
3859                return Err(error);
3860            }
3861        }
3862        Ok(serde_json::from_value(response)?)
3863    }
3864
3865    /// Gracefully remove one worker's registration through the worker plane.
3866    ///
3867    /// This operation is separate from operator-facing worker management. It
3868    /// uses worker-protocol authentication and returns the server's lease
3869    /// recovery result.
3870    pub async fn deregister_worker_registration(
3871        &self,
3872        worker_id: &str,
3873    ) -> Result<WorkerDeregistrationEnvelope> {
3874        let path = format!(
3875            "/worker/registrations/{}",
3876            percent_encode_path_segment(worker_id)
3877        );
3878        self.request_json(
3879            reqwest::Method::DELETE,
3880            &path,
3881            RequestProtocol::DefaultWorker,
3882            Option::<&Value>::None,
3883        )
3884        .await
3885    }
3886
3887    /// Long-poll for an ephemeral, read-only workflow query task.
3888    pub async fn poll_query_task(
3889        &self,
3890        worker_id: &str,
3891        task_queue: &str,
3892        timeout: Duration,
3893    ) -> Result<Option<QueryTask>> {
3894        Ok(self
3895            .poll_query_task_response(worker_id, task_queue, timeout)
3896            .await?
3897            .task)
3898    }
3899
3900    /// Poll a query task while preserving server stop and drain metadata.
3901    pub async fn poll_query_task_response(
3902        &self,
3903        worker_id: &str,
3904        task_queue: &str,
3905        timeout: Duration,
3906    ) -> Result<PollQueryTaskResponse> {
3907        let poll_request_id = unique_request_id("rust-query-poll");
3908        self.poll_query_task_response_with_request_id(
3909            worker_id,
3910            task_queue,
3911            timeout,
3912            &poll_request_id,
3913            1,
3914        )
3915        .await
3916    }
3917
3918    async fn poll_query_task_response_with_request_id(
3919        &self,
3920        worker_id: &str,
3921        task_queue: &str,
3922        timeout: Duration,
3923        poll_request_id: &str,
3924        transport_retries: usize,
3925    ) -> Result<PollQueryTaskResponse> {
3926        let timeout_seconds = long_poll_timeout_seconds(timeout);
3927        let body = json!({
3928            "worker_id": worker_id,
3929            "task_queue": task_queue,
3930            "poll_request_id": poll_request_id,
3931            "timeout_seconds": timeout_seconds,
3932        });
3933        self.poll_request_json(
3934            "/worker/query-tasks/poll",
3935            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3936            &body,
3937            timeout + Duration::from_secs(5),
3938            transport_retries,
3939        )
3940        .await
3941    }
3942
3943    /// Complete a query task without appending workflow history.
3944    pub async fn complete_query_task<T: Serialize>(
3945        &self,
3946        query_task_id: &str,
3947        lease_owner: &str,
3948        query_task_attempt: u64,
3949        result: T,
3950        codec: &str,
3951    ) -> Result<Value> {
3952        let typed_result = AvroValue::from_serialize(&result)?;
3953        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
3954        self.complete_query_task_with_envelope(
3955            query_task_id,
3956            lease_owner,
3957            query_task_attempt,
3958            typed_result.into_json()?,
3959            result_envelope,
3960        )
3961        .await
3962    }
3963
3964    async fn complete_query_task_with_envelope(
3965        &self,
3966        query_task_id: &str,
3967        lease_owner: &str,
3968        query_task_attempt: u64,
3969        result: Value,
3970        result_envelope: Value,
3971    ) -> Result<Value> {
3972        let body = json!({
3973            "lease_owner": lease_owner,
3974            "query_task_attempt": query_task_attempt,
3975            "result": result,
3976            "result_envelope": result_envelope,
3977        });
3978        let path = format!("/worker/query-tasks/{query_task_id}/complete");
3979        let response = self
3980            .request_json(
3981                reqwest::Method::POST,
3982                &path,
3983                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
3984                Some(&body),
3985            )
3986            .await;
3987        query_task_response(response)
3988    }
3989
3990    /// Report a stable machine-readable query-task failure.
3991    pub async fn fail_query_task(
3992        &self,
3993        query_task_id: &str,
3994        lease_owner: &str,
3995        query_task_attempt: u64,
3996        message: impl Into<String>,
3997        reason: impl Into<String>,
3998        failure_type: impl Into<String>,
3999    ) -> Result<Value> {
4000        let body = json!({
4001            "lease_owner": lease_owner,
4002            "query_task_attempt": query_task_attempt,
4003            "failure": {
4004                "message": message.into(),
4005                "reason": reason.into(),
4006                "type": failure_type.into(),
4007            }
4008        });
4009        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4010        let response = self
4011            .request_json(
4012                reqwest::Method::POST,
4013                &path,
4014                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4015                Some(&body),
4016            )
4017            .await;
4018        query_task_response(response)
4019    }
4020
4021    pub async fn heartbeat_worker(
4022        &self,
4023        worker_id: &str,
4024        workflow_available: usize,
4025        activity_available: usize,
4026    ) -> Result<Value> {
4027        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4028            .await
4029    }
4030
4031    async fn heartbeat_worker_with_sessions(
4032        &self,
4033        worker_id: &str,
4034        workflow_available: usize,
4035        activity_available: usize,
4036        session_available: Option<usize>,
4037    ) -> Result<Value> {
4038        let mut body = json!({
4039            "worker_id": worker_id,
4040            "task_slots": {
4041                "workflow_available": workflow_available,
4042                "activity_available": activity_available
4043            },
4044            "process_metrics": {
4045                "process_id": std::process::id(),
4046                "process_uptime_seconds": 0
4047            }
4048        });
4049
4050        if let Some(available) = session_available {
4051            body["task_slots"]["session_available"] = json!(available);
4052        }
4053
4054        self.request_json(
4055            reqwest::Method::POST,
4056            "/worker/heartbeat",
4057            RequestProtocol::DefaultWorker,
4058            Some(&body),
4059        )
4060        .await
4061    }
4062
4063    pub async fn poll_workflow_task(
4064        &self,
4065        worker_id: &str,
4066        task_queue: &str,
4067        timeout: Duration,
4068    ) -> Result<Option<WorkflowTask>> {
4069        Ok(self
4070            .poll_workflow_task_response(worker_id, task_queue, timeout)
4071            .await?
4072            .task)
4073    }
4074
4075    pub async fn poll_workflow_task_response(
4076        &self,
4077        worker_id: &str,
4078        task_queue: &str,
4079        timeout: Duration,
4080    ) -> Result<PollWorkflowTaskResponse> {
4081        let poll_request_id = unique_request_id("rust-workflow-poll");
4082        self.poll_workflow_task_response_with_request_id(
4083            worker_id,
4084            task_queue,
4085            timeout,
4086            &poll_request_id,
4087            1,
4088        )
4089        .await
4090    }
4091
4092    async fn poll_workflow_task_response_with_request_id(
4093        &self,
4094        worker_id: &str,
4095        task_queue: &str,
4096        timeout: Duration,
4097        poll_request_id: &str,
4098        transport_retries: usize,
4099    ) -> Result<PollWorkflowTaskResponse> {
4100        let body = json!({
4101            "worker_id": worker_id,
4102            "task_queue": task_queue,
4103            "poll_request_id": poll_request_id,
4104            "timeout_seconds": long_poll_timeout_seconds(timeout),
4105            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4106        });
4107        let mut wire: Value = self
4108            .poll_request_json_unresolved(
4109                "/worker/workflow-tasks/poll",
4110                RequestProtocol::DefaultWorker,
4111                &body,
4112                timeout + Duration::from_secs(5),
4113                transport_retries,
4114            )
4115            .await?;
4116        let claim =
4117            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4118        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4119            self.resolve_runtime_payloads(
4120                &mut wire,
4121                "/worker/workflow-tasks/poll",
4122                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4123            )
4124            .await?;
4125            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4126            if let Some(task) = data.task.as_mut() {
4127                self.fetch_remaining_workflow_history(worker_id, task)
4128                    .await?;
4129            }
4130            Ok(data)
4131        })
4132        .await?;
4133        Ok(data)
4134    }
4135
4136    async fn fetch_remaining_workflow_history(
4137        &self,
4138        worker_id: &str,
4139        task: &mut WorkflowTask,
4140    ) -> Result<()> {
4141        let mut next_token = task.next_history_page_token.clone();
4142        let mut seen = BTreeSet::new();
4143
4144        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4145            if seen.len() >= 128 || !seen.insert(token.clone()) {
4146                return Err(Error::Codec(
4147                    "workflow history pagination exceeded its page bound or repeated a token"
4148                        .into(),
4149                ));
4150            }
4151            let lease_owner = task
4152                .lease_owner
4153                .clone()
4154                .unwrap_or_else(|| worker_id.to_string());
4155            let page = self
4156                .workflow_task_history_page(
4157                    &task.task_id,
4158                    &lease_owner,
4159                    task.workflow_task_attempt,
4160                    &token,
4161                )
4162                .await?;
4163
4164            task.append_history_page(page);
4165
4166            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4167                return Err(Error::Codec(
4168                    "workflow history pagination returned the same page token".to_string(),
4169                ));
4170            }
4171
4172            next_token = task.next_history_page_token.clone();
4173        }
4174
4175        Ok(())
4176    }
4177
4178    async fn workflow_task_history_page(
4179        &self,
4180        task_id: &str,
4181        lease_owner: &str,
4182        workflow_task_attempt: u64,
4183        next_history_page_token: &str,
4184    ) -> Result<WorkflowTaskHistoryPage> {
4185        let body = json!({
4186            "lease_owner": lease_owner,
4187            "workflow_task_attempt": workflow_task_attempt,
4188            "next_history_page_token": next_history_page_token
4189        });
4190        let path = format!("/worker/workflow-tasks/{task_id}/history");
4191
4192        self.request_json(
4193            reqwest::Method::POST,
4194            &path,
4195            RequestProtocol::DefaultWorker,
4196            Some(&body),
4197        )
4198        .await
4199    }
4200
4201    pub async fn complete_workflow_task(
4202        &self,
4203        task_id: &str,
4204        lease_owner: &str,
4205        workflow_task_attempt: u64,
4206        commands: Vec<Value>,
4207    ) -> Result<Value> {
4208        self.complete_workflow_task_with_message_streams(
4209            task_id,
4210            lease_owner,
4211            workflow_task_attempt,
4212            commands,
4213            Vec::new(),
4214            Vec::new(),
4215            None,
4216        )
4217        .await
4218    }
4219
4220    #[allow(clippy::too_many_arguments)]
4221    async fn complete_workflow_task_with_message_streams(
4222        &self,
4223        task_id: &str,
4224        lease_owner: &str,
4225        workflow_task_attempt: u64,
4226        commands: Vec<Value>,
4227        message_stream_cursors: Vec<Value>,
4228        message_stream_waits: Vec<Value>,
4229        sticky_cache: Option<Value>,
4230    ) -> Result<Value> {
4231        validate_workflow_task_commands(&commands)?;
4232        let has_message_stream_metadata =
4233            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4234        if has_message_stream_metadata
4235            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4236        {
4237            return Err(Error::Codec(
4238                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4239                    .to_string(),
4240            ));
4241        }
4242        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4243            &commands,
4244            has_message_stream_metadata,
4245        );
4246        let protocol_version = if sticky_cache.is_some()
4247            && protocol_version
4248                .strip_prefix("1.")
4249                .and_then(|minor| minor.parse::<u64>().ok())
4250                .is_some_and(|minor| minor < 18)
4251        {
4252            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4253        } else {
4254            protocol_version
4255        };
4256        let mut body = json!({
4257            "lease_owner": lease_owner,
4258            "workflow_task_attempt": workflow_task_attempt,
4259            "commands": commands
4260        });
4261        if !message_stream_cursors.is_empty() {
4262            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4263        }
4264        if !message_stream_waits.is_empty() {
4265            body["message_stream_waits"] = Value::Array(message_stream_waits);
4266        }
4267        if let Some(claim) = sticky_cache {
4268            body["sticky_cache"] = claim;
4269        }
4270        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4271        self.request_json(
4272            reqwest::Method::POST,
4273            &path,
4274            RequestProtocol::Worker(protocol_version),
4275            Some(&body),
4276        )
4277        .await
4278    }
4279
4280    pub async fn fail_workflow_task(
4281        &self,
4282        task_id: &str,
4283        lease_owner: &str,
4284        workflow_task_attempt: u64,
4285        message: impl Into<String>,
4286    ) -> Result<Value> {
4287        self.fail_workflow_task_with_type(
4288            task_id,
4289            lease_owner,
4290            workflow_task_attempt,
4291            message,
4292            "RustWorkflowTaskFailure",
4293        )
4294        .await
4295    }
4296
4297    async fn fail_workflow_task_with_type(
4298        &self,
4299        task_id: &str,
4300        lease_owner: &str,
4301        workflow_task_attempt: u64,
4302        message: impl Into<String>,
4303        failure_type: &str,
4304    ) -> Result<Value> {
4305        let body = json!({
4306            "lease_owner": lease_owner,
4307            "workflow_task_attempt": workflow_task_attempt,
4308            "failure": {
4309                "message": message.into(),
4310                "type": failure_type
4311            }
4312        });
4313        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4314        self.request_json(
4315            reqwest::Method::POST,
4316            &path,
4317            RequestProtocol::DefaultWorker,
4318            Some(&body),
4319        )
4320        .await
4321    }
4322
4323    pub async fn poll_activity_task(
4324        &self,
4325        worker_id: &str,
4326        task_queue: &str,
4327        timeout: Duration,
4328    ) -> Result<Option<ActivityTask>> {
4329        Ok(self
4330            .poll_activity_task_response(worker_id, task_queue, timeout)
4331            .await?
4332            .task)
4333    }
4334
4335    /// Poll an activity task while preserving server stop and drain metadata.
4336    pub async fn poll_activity_task_response(
4337        &self,
4338        worker_id: &str,
4339        task_queue: &str,
4340        timeout: Duration,
4341    ) -> Result<PollActivityTaskResponse> {
4342        let poll_request_id = unique_request_id("rust-activity-poll");
4343        self.poll_activity_task_response_with_request_id(
4344            worker_id,
4345            task_queue,
4346            timeout,
4347            &poll_request_id,
4348            1,
4349        )
4350        .await
4351        .map(worker_session::SessionPollResponse::ordinary)
4352    }
4353
4354    async fn poll_activity_task_response_with_request_id(
4355        &self,
4356        worker_id: &str,
4357        task_queue: &str,
4358        timeout: Duration,
4359        poll_request_id: &str,
4360        transport_retries: usize,
4361    ) -> Result<worker_session::SessionPollResponse> {
4362        let body = json!({
4363            "worker_id": worker_id,
4364            "task_queue": task_queue,
4365            "poll_request_id": poll_request_id,
4366            "timeout_seconds": long_poll_timeout_seconds(timeout),
4367        });
4368        let mut wire: Value = self
4369            .poll_request_json_unresolved(
4370                "/worker/activity-tasks/poll",
4371                RequestProtocol::DefaultWorker,
4372                &body,
4373                timeout + Duration::from_secs(5),
4374                transport_retries,
4375            )
4376            .await?;
4377        let claim = activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?;
4378        let mut data: worker_session::SessionPollResponse =
4379            activity_hydration::HydrationClaim::protect(claim.as_ref(), self, async {
4380                self.resolve_runtime_payloads(
4381                    &mut wire,
4382                    "/worker/activity-tasks/poll",
4383                    RequestProtocol::DefaultWorker,
4384                )
4385                .await?;
4386                Ok(serde_json::from_value(wire)?)
4387            })
4388            .await?;
4389        if let Some(task) = data.task.as_mut() {
4390            task.hydration_claim = claim;
4391        }
4392        Ok(data)
4393    }
4394
4395    pub async fn complete_activity_task<T: Serialize>(
4396        &self,
4397        task_id: &str,
4398        activity_attempt_id: &str,
4399        lease_owner: &str,
4400        result: T,
4401        codec: &str,
4402    ) -> Result<Value> {
4403        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4404        let body = json!({
4405            "activity_attempt_id": activity_attempt_id,
4406            "lease_owner": lease_owner,
4407            "result": result
4408        });
4409        let path = format!("/worker/activity-tasks/{task_id}/complete");
4410        activity_task_response(
4411            self.request_json(
4412                reqwest::Method::POST,
4413                &path,
4414                RequestProtocol::DefaultWorker,
4415                Some(&body),
4416            )
4417            .await,
4418            "complete",
4419            task_id,
4420            activity_attempt_id,
4421        )
4422    }
4423
4424    pub async fn fail_activity_task(
4425        &self,
4426        task_id: &str,
4427        activity_attempt_id: &str,
4428        lease_owner: &str,
4429        message: impl Into<String>,
4430        non_retryable: bool,
4431    ) -> Result<Value> {
4432        let body = json!({
4433            "activity_attempt_id": activity_attempt_id,
4434            "lease_owner": lease_owner,
4435            "failure": {
4436                "message": message.into(),
4437                "type": "RustActivityFailure",
4438                "non_retryable": non_retryable
4439            }
4440        });
4441        let path = format!("/worker/activity-tasks/{task_id}/fail");
4442        activity_task_response(
4443            self.request_json(
4444                reqwest::Method::POST,
4445                &path,
4446                RequestProtocol::DefaultWorker,
4447                Some(&body),
4448            )
4449            .await,
4450            "fail",
4451            task_id,
4452            activity_attempt_id,
4453        )
4454    }
4455
4456    /// Record a flat map of scalar/null activity progress metadata.
4457    ///
4458    /// Heartbeat details use the Server's bounded JSON progress contract.
4459    /// They are not workflow payload envelopes.
4460    pub async fn heartbeat_activity_task<T: Serialize>(
4461        &self,
4462        task_id: &str,
4463        activity_attempt_id: &str,
4464        lease_owner: &str,
4465        details: T,
4466    ) -> Result<ActivityHeartbeatResponse> {
4467        serde_json::from_value(
4468            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4469                .await?,
4470        )
4471        .map_err(Error::from)
4472    }
4473
4474    async fn heartbeat_activity_task_value<T: Serialize>(
4475        &self,
4476        task_id: &str,
4477        activity_attempt_id: &str,
4478        lease_owner: &str,
4479        details: T,
4480    ) -> Result<Value> {
4481        let details = AvroValue::from_serialize(&details)?.into_json()?;
4482        let body = json!({
4483            "activity_attempt_id": activity_attempt_id,
4484            "lease_owner": lease_owner,
4485            "details": details
4486        });
4487        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4488        activity_task_response(
4489            self.request_json(
4490                reqwest::Method::POST,
4491                &path,
4492                RequestProtocol::DefaultWorker,
4493                Some(&body),
4494            )
4495            .await,
4496            "heartbeat",
4497            task_id,
4498            activity_attempt_id,
4499        )
4500    }
4501
4502    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4503        &self,
4504        method: reqwest::Method,
4505        path: &str,
4506        protocol: RequestProtocol,
4507        body: Option<&B>,
4508    ) -> Result<T> {
4509        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4510            .await
4511    }
4512
4513    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4514        &self,
4515        method: reqwest::Method,
4516        path: &str,
4517        protocol: RequestProtocol,
4518        body: Option<&B>,
4519        timeout: Duration,
4520    ) -> Result<T> {
4521        let mut value: Value = self
4522            .request_json_unresolved_with_timeout(method, path, protocol, body, timeout)
4523            .await?;
4524        let protocol = match protocol {
4525            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4526                RequestProtocol::Worker(self.worker_protocol_version.as_str())
4527            }
4528            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4529        };
4530        self.resolve_runtime_payloads(&mut value, path, protocol)
4531            .await?;
4532        Ok(serde_json::from_value(value)?)
4533    }
4534
4535    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4536        &self,
4537        method: reqwest::Method,
4538        path: &str,
4539        protocol: RequestProtocol,
4540        body: Option<&B>,
4541        timeout: Duration,
4542    ) -> Result<T> {
4543        let protocol = match protocol {
4544            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4545                let selected = self.worker_protocol_version.as_str();
4546                if self.cooperative_worker_protocol
4547                    && !cooperative_cancellation::supports_protocol(selected)
4548                {
4549                    return Err(Error::CooperativeCancellationUnavailable(
4550                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4551                    ));
4552                }
4553                if let RequestProtocol::Worker(minimum) = protocol {
4554                    let supported = minimum
4555                        .strip_prefix("1.")
4556                        .and_then(|minor| minor.parse::<u64>().ok())
4557                        .zip(
4558                            selected
4559                                .strip_prefix("1.")
4560                                .and_then(|minor| minor.parse::<u64>().ok()),
4561                        )
4562                        .is_some_and(|(minimum, selected)| selected >= minimum);
4563                    if !supported {
4564                        return Err(Error::WorkerLoop(format!(
4565                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4566                        )));
4567                    }
4568                }
4569                RequestProtocol::Worker(selected)
4570            }
4571            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4572        };
4573        let auth_token = self.auth_token(protocol)?;
4574        let mut request = self
4575            .http
4576            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4577            .timeout(timeout)
4578            .header(reqwest::header::ACCEPT, "application/json")
4579            .header(reqwest::header::CONTENT_TYPE, "application/json")
4580            .header("X-Namespace", &self.namespace);
4581
4582        match protocol {
4583            RequestProtocol::DefaultWorker => {
4584                request = request.header(
4585                    "X-Durable-Workflow-Protocol-Version",
4586                    self.worker_protocol_version.as_str(),
4587                );
4588            }
4589            RequestProtocol::Worker(version) => {
4590                request = request.header("X-Durable-Workflow-Protocol-Version", version);
4591            }
4592            RequestProtocol::ControlPlane => {
4593                request = request.header(
4594                    "X-Durable-Workflow-Control-Plane-Version",
4595                    CONTROL_PLANE_VERSION,
4596                );
4597            }
4598        }
4599
4600        if let Some(token) = auth_token {
4601            request = request.bearer_auth(token);
4602        }
4603
4604        if let Some(body) = body {
4605            let mut body = serde_json::to_value(body)?;
4606            if matches!(
4607                method,
4608                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
4609            ) {
4610                self.externalize_runtime_payloads(&mut body, path, protocol)
4611                    .await?;
4612            }
4613            request = request.json(&body);
4614        }
4615
4616        let request = request.build()?;
4617        let request_body = request
4618            .body()
4619            .and_then(reqwest::Body::as_bytes)
4620            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
4621        let poll_request_id = path.ends_with("/poll").then(|| {
4622            request_body
4623                .as_ref()
4624                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
4625                .unwrap_or_default()
4626        });
4627        let mut storage_retries = 0_usize;
4628
4629        loop {
4630            // Keep the serialized body and lease/poll identity across admission pauses.
4631            let response = self
4632                .http
4633                .execute(request.try_clone().ok_or_else(|| {
4634                    Error::WorkerLoop("worker request body cannot be retried".to_string())
4635                })?)
4636                .await?;
4637            let status = response.status();
4638            let bytes = response.bytes().await?;
4639
4640            if !status.is_success() {
4641                let body = String::from_utf8_lossy(&bytes).to_string();
4642                if let Some(protocol) = protocol_failure(status, &body) {
4643                    return Err(Error::Protocol(protocol));
4644                }
4645                let error = Error::Http { status, body };
4646                if self
4647                    .wait_for_storage_admission(
4648                        &error,
4649                        protocol,
4650                        Some(path),
4651                        poll_request_id.as_deref(),
4652                        request_body.as_ref(),
4653                        &mut storage_retries,
4654                    )
4655                    .await
4656                {
4657                    continue;
4658                }
4659                return Err(error);
4660            }
4661
4662            if bytes.is_empty() {
4663                return Ok(serde_json::from_value(Value::Null)?);
4664            }
4665
4666            return Ok(serde_json::from_slice(&bytes)?);
4667        }
4668    }
4669
4670    async fn wait_for_storage_admission(
4671        &self,
4672        error: &Error,
4673        protocol: RequestProtocol,
4674        path: Option<&str>,
4675        poll_request_id: Option<&str>,
4676        request_body: Option<&Value>,
4677        retries: &mut usize,
4678    ) -> bool {
4679        let Some(admission) = self
4680            .worker_storage_admission
4681            .as_ref()
4682            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
4683        else {
4684            return false;
4685        };
4686        let Some(advertised_delay) = worker_storage_admission_retry_after(error, poll_request_id)
4687            .or_else(|| {
4688                path.and_then(|path| {
4689                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
4690                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
4691                })
4692            })
4693        else {
4694            return false;
4695        };
4696        *retries = retries.saturating_add(1);
4697        let delay = worker_retry_delay(admission.policy, *retries)
4698            .max(advertised_delay)
4699            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
4700        let deadline = tokio::time::Instant::now() + delay;
4701        loop {
4702            if admission.stop.load(Ordering::SeqCst) {
4703                return false;
4704            }
4705            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
4706            if remaining.is_zero() {
4707                return true;
4708            }
4709            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
4710        }
4711    }
4712
4713    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4714        &self,
4715        path: &str,
4716        protocol: RequestProtocol,
4717        body: &B,
4718        timeout: Duration,
4719        max_retries: usize,
4720    ) -> Result<T> {
4721        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
4722            .await
4723    }
4724
4725    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
4726        &self,
4727        path: &str,
4728        protocol: RequestProtocol,
4729        body: &B,
4730        timeout: Duration,
4731        max_retries: usize,
4732    ) -> Result<T> {
4733        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
4734            .await
4735    }
4736
4737    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
4738        &self,
4739        path: &str,
4740        protocol: RequestProtocol,
4741        body: &B,
4742        timeout: Duration,
4743        max_retries: usize,
4744        resolve: bool,
4745    ) -> Result<T> {
4746        let mut retries = 0;
4747
4748        loop {
4749            let response = if resolve {
4750                self.request_json_with_timeout(
4751                    reqwest::Method::POST,
4752                    path,
4753                    protocol,
4754                    Some(body),
4755                    timeout,
4756                )
4757                .await
4758            } else {
4759                self.request_json_unresolved_with_timeout(
4760                    reqwest::Method::POST,
4761                    path,
4762                    protocol,
4763                    Some(body),
4764                    timeout,
4765                )
4766                .await
4767            };
4768
4769            match response {
4770                Err(Error::Transport(_)) if retries < max_retries => retries += 1,
4771                response => return worker_poll_response(response),
4772            }
4773        }
4774    }
4775
4776    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
4777        match protocol {
4778            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4779                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
4780                    return Ok(Some(token));
4781                }
4782                if self.control_token.is_some() {
4783                    return Err(Error::MissingRoleCredentials {
4784                        role: "worker",
4785                        opposite_role: "control",
4786                    });
4787                }
4788                Ok(None)
4789            }
4790            RequestProtocol::ControlPlane => {
4791                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
4792                    return Ok(Some(token));
4793                }
4794                if self.worker_token.is_some() {
4795                    return Err(Error::MissingRoleCredentials {
4796                        role: "control",
4797                        opposite_role: "worker",
4798                    });
4799                }
4800                Ok(None)
4801            }
4802        }
4803    }
4804}
4805
4806fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
4807    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4808    let reason = body
4809        .get("reason")
4810        .and_then(Value::as_str)
4811        .unwrap_or("query_rejected")
4812        .to_string();
4813    let message = body
4814        .get("message")
4815        .or_else(|| body.get("error"))
4816        .and_then(Value::as_str)
4817        .unwrap_or("workflow query was rejected")
4818        .to_string();
4819
4820    QueryFailure {
4821        status: status.as_u16(),
4822        reason,
4823        message,
4824        body,
4825    }
4826}
4827
4828fn workflow_command_result(
4829    command: WorkflowCommandKind,
4830    data: Value,
4831    workflow_id: &str,
4832    run_id: Option<&str>,
4833) -> WorkflowCommandResult {
4834    WorkflowCommandResult {
4835        command,
4836        workflow_id: data
4837            .get("workflow_id")
4838            .and_then(Value::as_str)
4839            .unwrap_or(workflow_id)
4840            .to_string(),
4841        run_id: data
4842            .get("run_id")
4843            .and_then(Value::as_str)
4844            .or(run_id)
4845            .map(str::to_string),
4846        outcome: data
4847            .get("outcome")
4848            .and_then(Value::as_str)
4849            .map(str::to_string),
4850        reason: data
4851            .get("reason")
4852            .and_then(Value::as_str)
4853            .map(str::to_string),
4854        command_status: data
4855            .get("command_status")
4856            .and_then(Value::as_str)
4857            .map(str::to_string),
4858        raw: data,
4859    }
4860}
4861
4862fn workflow_command_rejection(
4863    command: WorkflowCommandKind,
4864    status: reqwest::StatusCode,
4865    raw_body: String,
4866    workflow_id: &str,
4867    run_id: Option<&str>,
4868) -> WorkflowCommandRejection {
4869    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
4870    WorkflowCommandRejection {
4871        command,
4872        status: status.as_u16(),
4873        reason: body
4874            .get("reason")
4875            .and_then(Value::as_str)
4876            .unwrap_or("workflow_command_rejected")
4877            .to_string(),
4878        message: body
4879            .get("message")
4880            .or_else(|| body.get("error"))
4881            .and_then(Value::as_str)
4882            .unwrap_or("workflow lifecycle command was rejected")
4883            .to_string(),
4884        workflow_id: body
4885            .get("workflow_id")
4886            .and_then(Value::as_str)
4887            .unwrap_or(workflow_id)
4888            .to_string(),
4889        run_id: body
4890            .get("run_id")
4891            .and_then(Value::as_str)
4892            .or(run_id)
4893            .map(str::to_string),
4894        target_scope: body
4895            .get("target_scope")
4896            .and_then(Value::as_str)
4897            .map(str::to_string),
4898        body,
4899    }
4900}
4901
4902fn query_task_response(response: Result<Value>) -> Result<Value> {
4903    match response {
4904        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
4905        response => response,
4906    }
4907}
4908
4909fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
4910    match response {
4911        Err(Error::Http { status, body })
4912            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
4913        {
4914            Ok(serde_json::from_str(&body)?)
4915        }
4916        response => response,
4917    }
4918}
4919
4920fn worker_poll_body_is_stop(body: &str) -> bool {
4921    serde_json::from_str::<Value>(body)
4922        .ok()
4923        .is_some_and(|body| {
4924            worker_poll_is_stop(
4925                body.get("poll_status").and_then(Value::as_str),
4926                body.get("reason").and_then(Value::as_str),
4927            )
4928        })
4929}
4930
4931fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
4932    matches!(poll_status, Some("draining" | "stopped"))
4933        || matches!(reason, Some("worker_draining" | "worker_stopped"))
4934}
4935
4936fn query_task_rejection_is_final(error: &Error) -> bool {
4937    matches!(
4938        error,
4939        Error::QueryFailed(failure)
4940            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
4941    )
4942}
4943
4944fn activity_task_response<T>(
4945    response: Result<T>,
4946    operation: &str,
4947    task_id: &str,
4948    activity_attempt_id: &str,
4949) -> Result<T> {
4950    match response {
4951        Err(Error::Http { status, body }) => {
4952            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
4953            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
4954                operation: operation.to_string(),
4955                status: status.as_u16(),
4956                reason: body
4957                    .get("reason")
4958                    .and_then(Value::as_str)
4959                    .unwrap_or("activity_task_rejected")
4960                    .to_string(),
4961                task_id: body
4962                    .get("task_id")
4963                    .and_then(Value::as_str)
4964                    .unwrap_or(task_id)
4965                    .to_string(),
4966                activity_attempt_id: body
4967                    .get("activity_attempt_id")
4968                    .and_then(Value::as_str)
4969                    .unwrap_or(activity_attempt_id)
4970                    .to_string(),
4971                cancel_requested: body
4972                    .get("cancel_requested")
4973                    .and_then(Value::as_bool)
4974                    .unwrap_or(false),
4975                can_continue: body.get("can_continue").and_then(Value::as_bool),
4976                run_closed_reason: body
4977                    .get("run_closed_reason")
4978                    .and_then(Value::as_str)
4979                    .map(str::to_string),
4980                body,
4981            }))
4982        }
4983        response => response,
4984    }
4985}
4986
4987fn activity_task_rejection_is_final(error: &Error) -> bool {
4988    matches!(
4989        error,
4990        Error::ActivityTaskRejected(rejection)
4991            if matches!(
4992                rejection.reason.as_str(),
4993                "run_cancelled"
4994                    | "run_terminated"
4995                    | "attempt_closed"
4996                    | "stale_attempt"
4997                    | "activity_cancelled"
4998                    | "task_cancelled"
4999                    | "run_closed"
5000                    | "activity_not_running"
5001                    | "attempt_not_found"
5002            )
5003    )
5004}
5005
5006fn workflow_task_completion_is_terminal_timeout(
5007    error: &Error,
5008    task_id: &str,
5009    workflow_task_attempt: u64,
5010    run_id: Option<&str>,
5011) -> bool {
5012    let Error::Http { status, body } = error else {
5013        return false;
5014    };
5015    if *status != reqwest::StatusCode::CONFLICT {
5016        return false;
5017    }
5018
5019    let Some(run_id) = run_id else {
5020        return false;
5021    };
5022    let Ok(body) = serde_json::from_str::<Value>(body) else {
5023        return false;
5024    };
5025
5026    body.get("recorded").and_then(Value::as_bool) == Some(false)
5027        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5028        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5029        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5030        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5031        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5032}
5033
5034fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5035    let body: Value = serde_json::from_str(raw_body).ok()?;
5036    let reason = body.get("reason")?.as_str()?;
5037    if !matches!(
5038        reason,
5039        "missing_protocol_version"
5040            | "unsupported_protocol_version"
5041            | "missing_control_plane_version"
5042            | "unsupported_control_plane_version"
5043    ) {
5044        return None;
5045    }
5046
5047    Some(ProtocolFailure {
5048        status: status.as_u16(),
5049        reason: reason.to_string(),
5050        message: body
5051            .get("message")
5052            .or_else(|| body.get("error"))
5053            .and_then(Value::as_str)
5054            .unwrap_or("protocol version rejected")
5055            .to_string(),
5056        supported_version: body
5057            .get("supported_version")
5058            .and_then(Value::as_str)
5059            .map(str::to_string),
5060        requested_version: body
5061            .get("requested_version")
5062            .and_then(Value::as_str)
5063            .map(str::to_string),
5064        body,
5065    })
5066}
5067
5068fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5069    timeout
5070        .as_secs()
5071        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5072        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5073}
5074
5075fn worker_operation_is_retryable(error: &Error) -> bool {
5076    if worker_poll_capacity_retry_after(error).is_some()
5077        || worker_storage_admission_body(error).is_some()
5078        || worker_backend_unavailable_body(error).is_some()
5079        || worker_operation_is_explicitly_non_retryable(error)
5080    {
5081        return false;
5082    }
5083
5084    match error {
5085        Error::Transport(error) => {
5086            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5087        }
5088        Error::Http { status, .. } => {
5089            matches!(
5090                *status,
5091                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5092            ) || status.is_server_error()
5093        }
5094        _ => false,
5095    }
5096}
5097
5098fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5099    let body: Value = match error {
5100        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5101        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5102        _ => return None,
5103    };
5104    matches!(
5105        body.get("reason").and_then(Value::as_str),
5106        Some("storage_pressure" | "storage_admission_unavailable")
5107    )
5108    .then_some(body)
5109}
5110
5111fn worker_storage_admission_retry_after(
5112    error: &Error,
5113    poll_request_id: Option<&str>,
5114) -> Option<Duration> {
5115    let Error::Http { status, .. } = error else {
5116        return None;
5117    };
5118    let body = worker_storage_admission_body(error)?;
5119    let delay = body.get("retry_after_seconds")?.as_u64()?;
5120    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5121        || delay == 0
5122        || body.get("retryable") != Some(&Value::Bool(true))
5123        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5124        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5125        || body
5126            .get("request_admitted")
5127            .is_some_and(|admitted| admitted != &Value::Bool(false))
5128    {
5129        return None;
5130    }
5131    match poll_request_id {
5132        Some(id) => {
5133            if id.is_empty()
5134                || body.get("task") != Some(&Value::Null)
5135                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5136                || body.get("poll_status") != body.get("reason")
5137                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5138                || body.get("claim_admitted") != Some(&Value::Bool(false))
5139            {
5140                return None;
5141            }
5142        }
5143        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5144        None => {}
5145    }
5146    Some(Duration::from_secs(delay))
5147}
5148
5149fn worker_backend_unavailable_retry_after(
5150    error: &Error,
5151    path: &str,
5152    poll_request_id: Option<&str>,
5153) -> Option<Duration> {
5154    let operation = match path {
5155        "/worker/register" => "register_worker",
5156        "/worker/heartbeat" => "heartbeat_worker",
5157        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5158        "/worker/activity-tasks/poll" => "poll_activity_task",
5159        "/worker/query-tasks/poll" => "poll_query_task",
5160        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5161        _ => return None,
5162    };
5163    let body = worker_backend_unavailable_body(error)?;
5164    let delay = body.get("retry_after_seconds")?.as_u64()?;
5165    if delay == 0
5166        || body.get("operation")?.as_str()? != operation
5167        || body.get("outcome")?.as_str()? != "unknown"
5168        || body.get("retryable") != Some(&Value::Bool(true))
5169        || body.get("worker_id")?.as_str()?.is_empty()
5170    {
5171        return None;
5172    }
5173    if let Some(id) = poll_request_id {
5174        if id.is_empty()
5175            || body.get("task") != Some(&Value::Null)
5176            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5177            || body.get("poll_request_id")?.as_str()? != id
5178            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5179        {
5180            return None;
5181        }
5182    } else if path.ends_with("/poll") {
5183        return None;
5184    }
5185    Some(Duration::from_secs(delay))
5186}
5187
5188fn worker_fenced_completion_retry_after(
5189    error: &Error,
5190    path: &str,
5191    request_body: Option<&Value>,
5192) -> Option<Duration> {
5193    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5194        .strip_prefix("/worker/workflow-tasks/")
5195        .and_then(|tail| tail.strip_suffix("/complete"))
5196    {
5197        ("complete_workflow_task", task_id, "workflow_task_attempt")
5198    } else if let Some(task_id) = path
5199        .strip_prefix("/worker/activity-tasks/")
5200        .and_then(|tail| tail.strip_suffix("/complete"))
5201    {
5202        ("complete_activity_task", task_id, "activity_attempt_id")
5203    } else {
5204        return None;
5205    };
5206    if task_id.is_empty() || task_id.contains('/') {
5207        return None;
5208    }
5209
5210    let request = request_body?.as_object()?;
5211    let lease_owner = request.get("lease_owner")?.as_str()?;
5212    if lease_owner.is_empty() {
5213        return None;
5214    }
5215    let attempt = request.get(attempt_field)?;
5216    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5217        || (attempt_field == "activity_attempt_id"
5218            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5219    {
5220        return None;
5221    }
5222
5223    let body = worker_backend_unavailable_body(error)?;
5224    let delay = body.get("retry_after_seconds")?.as_u64()?;
5225    if delay == 0
5226        || body.get("operation")?.as_str()? != operation
5227        || body.get("outcome")?.as_str()? != "unknown"
5228        || body.get("retryable") != Some(&Value::Bool(true))
5229        || body.get("worker_id")?.as_str()? != lease_owner
5230        || body.get("task_queue") != Some(&Value::Null)
5231        || body.get("task_id")?.as_str()? != task_id
5232        || body.get("lease_owner")?.as_str()? != lease_owner
5233        || body.get(attempt_field) != Some(attempt)
5234    {
5235        return None;
5236    }
5237
5238    Some(Duration::from_secs(delay))
5239}
5240
5241fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5242    let Error::Http { status, body } = error else {
5243        return None;
5244    };
5245    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5246        return None;
5247    }
5248    let body: Value = serde_json::from_str(body).ok()?;
5249    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5250}
5251
5252fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5253    let Error::Http { body, .. } = error else {
5254        return false;
5255    };
5256
5257    serde_json::from_str::<Value>(body)
5258        .ok()
5259        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5260        == Some(false)
5261}
5262
5263fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5264    let Error::Http { status, body } = error else {
5265        return None;
5266    };
5267    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5268        return None;
5269    }
5270
5271    let body = serde_json::from_str::<Value>(body).ok()?;
5272    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5273        == Some("long_poll_capacity_exhausted")
5274        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5275    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5276        return None;
5277    }
5278
5279    Some(Duration::from_secs(
5280        body.get("retry_after_seconds")
5281            .and_then(Value::as_u64)
5282            .unwrap_or_default(),
5283    ))
5284}
5285
5286fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5287    let exponent = retry.saturating_sub(1).min(31) as u32;
5288    policy
5289        .initial_backoff
5290        .saturating_mul(1_u32 << exponent)
5291        .min(policy.max_backoff)
5292}
5293
5294#[derive(Debug)]
5295pub struct ClientBuilder {
5296    base_url: String,
5297    token: Option<String>,
5298    control_token: Option<String>,
5299    worker_token: Option<String>,
5300    namespace: String,
5301    timeout: Duration,
5302    max_external_payload_bytes: usize,
5303    worker_protocol_version: WorkerProtocolVersion,
5304}
5305
5306impl ClientBuilder {
5307    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5308    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5309        self.worker_protocol_version = version;
5310        self
5311    }
5312
5313    pub fn token(mut self, token: Option<String>) -> Self {
5314        self.token = token;
5315        self
5316    }
5317
5318    pub fn control_token(mut self, token: Option<String>) -> Self {
5319        self.control_token = token;
5320        self
5321    }
5322
5323    pub fn worker_token(mut self, token: Option<String>) -> Self {
5324        self.worker_token = token;
5325        self
5326    }
5327
5328    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5329        self.namespace = namespace.into();
5330        self
5331    }
5332
5333    pub fn timeout(mut self, timeout: Duration) -> Self {
5334        self.timeout = timeout;
5335        self
5336    }
5337
5338    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5339    /// References are fetched only from this client's authenticated runtime.
5340    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5341        self.max_external_payload_bytes = bytes;
5342        self
5343    }
5344
5345    pub fn build(self) -> Result<Client> {
5346        let base_url = self.base_url.trim_end_matches('/').to_string();
5347        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5348            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5349            .unwrap_or_else(|_| base_url.ends_with("/api"));
5350
5351        if has_sdk_api_suffix {
5352            return Err(Error::InvalidBaseUrl);
5353        }
5354
5355        Ok(Client {
5356            http: reqwest::Client::builder()
5357                .timeout(self.timeout)
5358                .redirect(reqwest::redirect::Policy::none())
5359                .build()?,
5360            hydration_timeout: self.timeout,
5361            base_url,
5362            token: self.token,
5363            control_token: self.control_token,
5364            worker_token: self.worker_token,
5365            namespace: self.namespace,
5366            max_external_payload_bytes: self.max_external_payload_bytes,
5367            worker_storage_admission: None,
5368            cooperative_worker_protocol: false,
5369            worker_protocol_version: self.worker_protocol_version,
5370            local_activities_enabled: false,
5371            worker_sessions_enabled: false,
5372            max_concurrent_worker_sessions: 10,
5373            worker_build_id: None,
5374            sticky_cache: None,
5375            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5376        })
5377    }
5378}
5379
5380#[derive(Clone, Debug)]
5381pub struct WorkflowHandle {
5382    client: Client,
5383    pub workflow_id: String,
5384    pub run_id: Option<String>,
5385    pub workflow_type: String,
5386}
5387
5388impl WorkflowHandle {
5389    /// Describe whichever run is current for this stable workflow instance.
5390    pub async fn describe(&self) -> Result<WorkflowDescription> {
5391        self.client.describe_workflow(&self.workflow_id).await
5392    }
5393
5394    /// Describe the run identity originally selected by this handle.
5395    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5396        let run_id = self.run_id.as_deref().ok_or_else(|| {
5397            Error::Codec("run_id is required for selected-run description".to_string())
5398        })?;
5399        self.client
5400            .describe_workflow_run(&self.workflow_id, run_id)
5401            .await
5402    }
5403
5404    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5405        self.client
5406            .signal_workflow(&self.workflow_id, signal_name, input)
5407            .await
5408    }
5409
5410    pub async fn append_message<T: Serialize>(
5411        &self,
5412        stream_name: &str,
5413        message_id: &str,
5414        input: T,
5415    ) -> Result<Value> {
5416        self.client
5417            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5418            .await
5419    }
5420
5421    /// Signal only if this handle's selected run is still current.
5422    pub async fn signal_selected_run<T: Serialize>(
5423        &self,
5424        signal_name: &str,
5425        input: T,
5426    ) -> Result<Value> {
5427        let run_id = self.run_id.as_deref().ok_or_else(|| {
5428            Error::Codec("run_id is required for selected-run signaling".to_string())
5429        })?;
5430        self.client
5431            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5432            .await
5433    }
5434
5435    /// Close whichever run is current as cancelled, without workflow cleanup.
5436    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
5437        self.client
5438            .cancel_workflow(&self.workflow_id, options)
5439            .await
5440    }
5441
5442    /// Request cancellation only if this handle's selected run is still current.
5443    pub async fn cancel_selected_run(
5444        &self,
5445        options: WorkflowCommandOptions,
5446    ) -> Result<WorkflowCommandResult> {
5447        let run_id = self.run_id.as_deref().ok_or_else(|| {
5448            Error::Codec("run_id is required for selected-run cancellation".to_string())
5449        })?;
5450        self.client
5451            .cancel_workflow_run(&self.workflow_id, run_id, options)
5452            .await
5453    }
5454
5455    /// Forcefully terminate whichever run is current.
5456    pub async fn terminate(
5457        &self,
5458        options: WorkflowCommandOptions,
5459    ) -> Result<WorkflowCommandResult> {
5460        self.client
5461            .terminate_workflow(&self.workflow_id, options)
5462            .await
5463    }
5464
5465    /// Terminate only if this handle's selected run is still current.
5466    pub async fn terminate_selected_run(
5467        &self,
5468        options: WorkflowCommandOptions,
5469    ) -> Result<WorkflowCommandResult> {
5470        let run_id = self.run_id.as_deref().ok_or_else(|| {
5471            Error::Codec("run_id is required for selected-run termination".to_string())
5472        })?;
5473        self.client
5474            .terminate_workflow_run(&self.workflow_id, run_id, options)
5475            .await
5476    }
5477
5478    /// Continue this handle's failed run without repeating completed activities.
5479    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
5480        let run_id = self
5481            .run_id
5482            .as_deref()
5483            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
5484        self.client
5485            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
5486            .await
5487    }
5488
5489    /// Execute a named, read-only query against this workflow.
5490    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
5491        self.client
5492            .query_workflow(&self.workflow_id, query_name, input)
5493            .await
5494    }
5495
5496    pub async fn query_avro_value<T: Serialize>(
5497        &self,
5498        query_name: &str,
5499        input: T,
5500    ) -> Result<AvroValue> {
5501        self.client
5502            .query_workflow_avro_value(&self.workflow_id, query_name, input)
5503            .await
5504    }
5505
5506    pub async fn update<T: Serialize>(
5507        &self,
5508        update_name: &str,
5509        input: T,
5510        request_id: Option<&str>,
5511    ) -> Result<Value> {
5512        self.client
5513            .update_workflow(&self.workflow_id, update_name, input, request_id)
5514            .await
5515    }
5516
5517    pub async fn update_avro_value<T: Serialize>(
5518        &self,
5519        update_name: &str,
5520        input: T,
5521        request_id: Option<&str>,
5522    ) -> Result<AvroValue> {
5523        self.client
5524            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
5525            .await
5526    }
5527
5528    /// Query only if this handle's selected run is still current.
5529    pub async fn query_selected_run<T: Serialize>(
5530        &self,
5531        query_name: &str,
5532        input: T,
5533    ) -> Result<Value> {
5534        let run_id = self
5535            .run_id
5536            .as_deref()
5537            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
5538        self.client
5539            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
5540            .await
5541    }
5542
5543    /// Await the final terminal outcome of the current continue-as-new chain.
5544    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
5545        self.result_target(options, None).await
5546    }
5547
5548    /// Await the final result without projecting Avro bytes through JSON.
5549    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
5550        self.result_avro_value_target(options, None).await
5551    }
5552
5553    /// Await the final result and decode it into a Serde application type.
5554    pub async fn result_typed<T: DeserializeOwned>(
5555        &self,
5556        options: WorkflowResultOptions,
5557    ) -> Result<T> {
5558        let result = self.result_avro_value(options).await?;
5559        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5560    }
5561
5562    /// Await only the run identity originally selected by this handle.
5563    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
5564        let run_id = self.run_id.as_deref().ok_or_else(|| {
5565            Error::Codec("run_id is required for selected-run result".to_string())
5566        })?;
5567        self.result_target(options, Some(run_id)).await
5568    }
5569
5570    /// Await the selected run's result on the lossless Avro Value surface.
5571    pub async fn result_selected_run_avro_value(
5572        &self,
5573        options: WorkflowResultOptions,
5574    ) -> Result<AvroValue> {
5575        let run_id = self.run_id.as_deref().ok_or_else(|| {
5576            Error::Codec("run_id is required for selected-run result".to_string())
5577        })?;
5578        self.result_avro_value_target(options, Some(run_id)).await
5579    }
5580
5581    /// Await the selected run and decode its result into a Serde type.
5582    pub async fn result_selected_run_typed<T: DeserializeOwned>(
5583        &self,
5584        options: WorkflowResultOptions,
5585    ) -> Result<T> {
5586        let result = self.result_selected_run_avro_value(options).await?;
5587        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
5588    }
5589
5590    async fn result_avro_value_target(
5591        &self,
5592        options: WorkflowResultOptions,
5593        selected_run_id: Option<&str>,
5594    ) -> Result<AvroValue> {
5595        let started = Instant::now();
5596
5597        loop {
5598            let description = match selected_run_id {
5599                Some(run_id) => {
5600                    self.client
5601                        .describe_workflow_run(&self.workflow_id, run_id)
5602                        .await?
5603                }
5604                None => self.describe().await?,
5605            };
5606            if description.is_completed() {
5607                return description.output_avro_value.ok_or_else(|| {
5608                    Error::Codec(
5609                        "missing_payload_envelope: typed workflow result requires output_envelope"
5610                            .to_string(),
5611                    )
5612                });
5613            }
5614            if description.is_terminal() {
5615                let outcome =
5616                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5617                return Err(match outcome.kind {
5618                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5619                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5620                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5621                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5622                });
5623            }
5624            if started.elapsed() >= options.timeout {
5625                return Err(Error::Timeout);
5626            }
5627            tokio::time::sleep(options.poll_interval).await;
5628        }
5629    }
5630
5631    async fn result_target(
5632        &self,
5633        options: WorkflowResultOptions,
5634        selected_run_id: Option<&str>,
5635    ) -> Result<Value> {
5636        let started = Instant::now();
5637
5638        loop {
5639            let description = match selected_run_id {
5640                Some(run_id) => {
5641                    self.client
5642                        .describe_workflow_run(&self.workflow_id, run_id)
5643                        .await?
5644                }
5645                None => self.describe().await?,
5646            };
5647            if description.is_completed() {
5648                return Ok(description.output.unwrap_or(Value::Null));
5649            }
5650
5651            if description.is_terminal() {
5652                let outcome =
5653                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
5654                return Err(match outcome.kind {
5655                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
5656                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
5657                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
5658                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
5659                });
5660            }
5661
5662            if started.elapsed() >= options.timeout {
5663                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
5664                    kind: WorkflowTerminalKind::TimedOut,
5665                    workflow_id: description
5666                        .workflow_id
5667                        .clone()
5668                        .unwrap_or_else(|| self.workflow_id.clone()),
5669                    run_id: description
5670                        .run_id
5671                        .clone()
5672                        .or_else(|| selected_run_id.map(str::to_string)),
5673                    reason: "result_wait_timeout".to_string(),
5674                    failure_category: Some("client_timeout".to_string()),
5675                    failure_id: None,
5676                    exception_type: None,
5677                    exception_class: None,
5678                    non_retryable: None,
5679                    message: Some(format!(
5680                        "workflow result was not terminal within {:?}",
5681                        options.timeout
5682                    )),
5683                    exception: None,
5684                    raw: description.raw_value(),
5685                }));
5686            }
5687
5688            tokio::time::sleep(options.poll_interval).await;
5689        }
5690    }
5691}
5692
5693#[derive(Clone, Copy, Debug)]
5694pub struct WorkflowResultOptions {
5695    pub poll_interval: Duration,
5696    pub timeout: Duration,
5697}
5698
5699impl Default for WorkflowResultOptions {
5700    fn default() -> Self {
5701        Self {
5702            poll_interval: Duration::from_millis(500),
5703            timeout: Duration::from_secs(30),
5704        }
5705    }
5706}
5707
5708#[derive(Clone, Debug, Deserialize)]
5709pub struct WorkflowDescription {
5710    pub workflow_id: Option<String>,
5711    pub run_id: Option<String>,
5712    pub workflow_type: Option<String>,
5713    pub status: Option<String>,
5714    #[serde(default)]
5715    pub closed_reason: Option<String>,
5716    #[serde(default)]
5717    pub error: Option<String>,
5718    #[serde(default)]
5719    pub failure: Option<Value>,
5720    #[serde(default)]
5721    pub exception: Option<Value>,
5722    #[serde(default)]
5723    pub failures: Vec<Value>,
5724    #[serde(default)]
5725    pub output: Option<Value>,
5726    #[serde(default)]
5727    pub output_envelope: Option<Value>,
5728    #[serde(skip)]
5729    pub output_avro_value: Option<AvroValue>,
5730    #[serde(flatten)]
5731    pub raw: HashMap<String, Value>,
5732}
5733
5734/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
5735#[derive(Clone, Debug, Deserialize)]
5736pub struct WorkflowStreamDescription {
5737    pub stream_name: String,
5738    pub status: String,
5739    pub last_offset: i64,
5740    pub total_items: u64,
5741    pub pending_items: u64,
5742    #[serde(default)]
5743    pub opened_at: Option<String>,
5744    #[serde(default)]
5745    pub last_appended_at: Option<String>,
5746    #[serde(default)]
5747    pub closed_at: Option<String>,
5748    #[serde(default)]
5749    pub error_reason: Option<String>,
5750    #[serde(default)]
5751    pub retention_seconds: Option<u64>,
5752    #[serde(flatten)]
5753    pub raw: HashMap<String, Value>,
5754}
5755
5756impl WorkflowStreamDescription {
5757    pub fn is_terminal(&self) -> bool {
5758        matches!(self.status.as_str(), "closed" | "errored")
5759    }
5760}
5761
5762/// One item for direct or replay-safe append.
5763#[derive(Clone, Debug, Default)]
5764pub struct WorkflowStreamAppendItem {
5765    pub payload_envelope: Option<Value>,
5766    pub payload_reference: Option<String>,
5767    pub item_type: Option<String>,
5768    pub content_type: Option<String>,
5769    pub idempotency_key: Option<String>,
5770}
5771
5772impl WorkflowStreamAppendItem {
5773    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
5774    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
5775        let value = AvroValue::from_serialize(&payload)?;
5776        Ok(Self {
5777            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
5778            ..Self::default()
5779        })
5780    }
5781
5782    /// Preserve an external payload URI as an opaque service-contract reference.
5783    pub fn from_reference(reference: impl Into<String>) -> Self {
5784        Self {
5785            payload_reference: Some(reference.into()),
5786            ..Self::default()
5787        }
5788    }
5789
5790    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
5791        self.item_type = Some(item_type.into());
5792        self
5793    }
5794
5795    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
5796        self.content_type = Some(content_type.into());
5797        self
5798    }
5799
5800    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
5801        self.idempotency_key = Some(idempotency_key.into());
5802        self
5803    }
5804
5805    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
5806        let mut item = serde_json::Map::new();
5807        if let Some(payload) = &self.payload_envelope {
5808            item.insert("payload".to_string(), payload.clone());
5809            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
5810        }
5811        if let Some(reference) = &self.payload_reference {
5812            item.insert("payload_reference".to_string(), json!(reference));
5813        }
5814        if let Some(item_type) = &self.item_type {
5815            item.insert("item_type".to_string(), json!(item_type));
5816        }
5817        if let Some(content_type) = &self.content_type {
5818            item.insert("content_type".to_string(), json!(content_type));
5819        }
5820        if let Some(key) = derived_idempotency_key
5821            .as_ref()
5822            .or(self.idempotency_key.as_ref())
5823        {
5824            item.insert("idempotency_key".to_string(), json!(key));
5825        }
5826        Value::Object(item)
5827    }
5828}
5829
5830/// One durable item at its stable zero-based offset.
5831#[derive(Clone, Debug)]
5832pub struct WorkflowStreamItem {
5833    pub offset: u64,
5834    pub payload: Option<Value>,
5835    pub payload_envelope: Option<Value>,
5836    pub payload_reference: Option<String>,
5837    pub payload_codec: Option<String>,
5838    pub idempotency_key: Option<String>,
5839    pub item_type: Option<String>,
5840    pub content_type: Option<String>,
5841    pub origin: Option<String>,
5842    pub origin_reference: Option<String>,
5843    pub emitted_at: Option<String>,
5844    pub raw: Value,
5845}
5846
5847/// One bounded at-least-once subscription page.
5848#[derive(Clone, Debug)]
5849pub struct WorkflowStreamPage {
5850    pub stream: WorkflowStreamDescription,
5851    pub items: Vec<WorkflowStreamItem>,
5852    pub next_offset: u64,
5853    pub terminal: bool,
5854}
5855
5856/// Durable acceptance and deduplication outcome for an append request.
5857#[derive(Clone, Debug)]
5858pub struct WorkflowStreamAppendResult {
5859    pub stream: WorkflowStreamDescription,
5860    pub accepted_offsets: Vec<u64>,
5861    pub accepted: u64,
5862    pub deduped: u64,
5863}
5864
5865#[derive(Deserialize)]
5866struct WorkflowStreamListResponse {
5867    #[serde(default)]
5868    streams: Vec<WorkflowStreamDescription>,
5869}
5870
5871#[derive(Deserialize)]
5872struct WorkflowStreamDescriptionResponse {
5873    stream: WorkflowStreamDescription,
5874}
5875
5876#[derive(Deserialize)]
5877struct WorkflowStreamPageResponse {
5878    stream: WorkflowStreamDescription,
5879    #[serde(default)]
5880    items: Vec<Value>,
5881    next_offset: u64,
5882    terminal: bool,
5883}
5884
5885#[derive(Deserialize)]
5886struct WorkflowStreamAppendResponse {
5887    stream: WorkflowStreamDescription,
5888    #[serde(default)]
5889    accepted_offsets: Vec<u64>,
5890    accepted: u64,
5891    deduped: u64,
5892}
5893
5894impl WorkflowDescription {
5895    pub fn is_completed(&self) -> bool {
5896        matches!(self.status.as_deref(), Some("completed" | "Completed"))
5897    }
5898
5899    pub fn is_terminal(&self) -> bool {
5900        matches!(
5901            self.status.as_deref(),
5902            Some(
5903                "completed"
5904                    | "Completed"
5905                    | "failed"
5906                    | "Failed"
5907                    | "cancelled"
5908                    | "Cancelled"
5909                    | "terminated"
5910                    | "Terminated"
5911                    | "timed_out"
5912                    | "TimedOut",
5913            )
5914        )
5915    }
5916
5917    fn decode_payloads(&mut self) -> Result<()> {
5918        if let Some(envelope) = &self.output_envelope {
5919            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
5920            self.output = Some(value.clone().into_json()?);
5921            self.output_avro_value = Some(value);
5922        }
5923
5924        Ok(())
5925    }
5926
5927    fn raw_value(&self) -> Value {
5928        let mut data = self.raw.clone();
5929        data.insert(
5930            "workflow_id".to_string(),
5931            self.workflow_id
5932                .clone()
5933                .map(Value::String)
5934                .unwrap_or(Value::Null),
5935        );
5936        data.insert(
5937            "run_id".to_string(),
5938            self.run_id
5939                .clone()
5940                .map(Value::String)
5941                .unwrap_or(Value::Null),
5942        );
5943        data.insert(
5944            "workflow_type".to_string(),
5945            self.workflow_type
5946                .clone()
5947                .map(Value::String)
5948                .unwrap_or(Value::Null),
5949        );
5950        data.insert(
5951            "status".to_string(),
5952            self.status
5953                .clone()
5954                .map(Value::String)
5955                .unwrap_or(Value::Null),
5956        );
5957        data.insert(
5958            "closed_reason".to_string(),
5959            self.closed_reason
5960                .clone()
5961                .map(Value::String)
5962                .unwrap_or(Value::Null),
5963        );
5964        if let Some(failure) = &self.failure {
5965            data.insert("failure".to_string(), failure.clone());
5966        }
5967        if let Some(exception) = &self.exception {
5968            data.insert("exception".to_string(), exception.clone());
5969        }
5970        Value::Object(data.into_iter().collect())
5971    }
5972}
5973
5974fn workflow_terminal_outcome(
5975    description: &WorkflowDescription,
5976    workflow_id: &str,
5977    run_id: Option<&str>,
5978) -> WorkflowTerminalOutcome {
5979    let terminal_kind = description
5980        .closed_reason
5981        .as_deref()
5982        .or(description.status.as_deref())
5983        .unwrap_or("failed")
5984        .to_ascii_lowercase();
5985    let kind = match terminal_kind.as_str() {
5986        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
5987        "terminated" => WorkflowTerminalKind::Terminated,
5988        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
5989        _ => WorkflowTerminalKind::Failed,
5990    };
5991    let default_reason = match kind {
5992        WorkflowTerminalKind::Failed => "workflow_failed",
5993        WorkflowTerminalKind::Cancelled => "cancelled",
5994        WorkflowTerminalKind::Terminated => "terminated",
5995        WorkflowTerminalKind::TimedOut => "timed_out",
5996    };
5997    let failure = description
5998        .failure
5999        .as_ref()
6000        .filter(|value| value.is_object());
6001    let nested_failure = failure
6002        .and_then(|value| value.get("failures"))
6003        .and_then(Value::as_array)
6004        .and_then(|failures| failures.last())
6005        .or_else(|| description.failures.last());
6006    let exception = description
6007        .exception
6008        .clone()
6009        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6010        .or_else(|| {
6011            nested_failure
6012                .and_then(|value| value.get("exception_payload"))
6013                .cloned()
6014        });
6015    let string_field = |name: &str| {
6016        failure
6017            .and_then(|value| value.get(name))
6018            .and_then(Value::as_str)
6019            .or_else(|| {
6020                nested_failure
6021                    .and_then(|value| value.get(name))
6022                    .and_then(Value::as_str)
6023            })
6024            .map(str::to_string)
6025    };
6026    let exception_field = |name: &str| {
6027        exception
6028            .as_ref()
6029            .and_then(|value| value.get(name))
6030            .and_then(Value::as_str)
6031            .map(str::to_string)
6032    };
6033    let message = description
6034        .error
6035        .clone()
6036        .or_else(|| string_field("message"))
6037        .or_else(|| exception_field("message"));
6038    let reason = description
6039        .raw
6040        .get("reason")
6041        .and_then(Value::as_str)
6042        .map(str::to_string)
6043        .or_else(|| {
6044            failure
6045                .and_then(|value| value.get("reason"))
6046                .and_then(Value::as_str)
6047                .map(str::to_string)
6048        })
6049        .or_else(|| description.closed_reason.clone())
6050        .unwrap_or_else(|| default_reason.to_string());
6051    let failure_id = string_field("failure_id").or_else(|| {
6052        nested_failure
6053            .and_then(|value| value.get("id"))
6054            .and_then(Value::as_str)
6055            .map(str::to_string)
6056    });
6057
6058    WorkflowTerminalOutcome {
6059        kind,
6060        workflow_id: description
6061            .workflow_id
6062            .clone()
6063            .unwrap_or_else(|| workflow_id.to_string()),
6064        run_id: description
6065            .run_id
6066            .clone()
6067            .or_else(|| run_id.map(str::to_string)),
6068        reason,
6069        failure_category: string_field("failure_category")
6070            .or_else(|| Some(default_reason.to_string())),
6071        failure_id,
6072        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6073        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6074        non_retryable: failure
6075            .and_then(|value| value.get("non_retryable"))
6076            .and_then(Value::as_bool)
6077            .or_else(|| {
6078                nested_failure
6079                    .and_then(|value| value.get("non_retryable"))
6080                    .and_then(Value::as_bool)
6081            }),
6082        message,
6083        exception,
6084        raw: description.raw_value(),
6085    }
6086}
6087
6088#[derive(Clone, Debug, Deserialize)]
6089pub struct RegisterWorkerResponse {
6090    pub worker_id: String,
6091    pub registered: bool,
6092    #[serde(default)]
6093    pub heartbeat_interval_seconds: Option<u64>,
6094    #[serde(default)]
6095    pub protocol_version: Option<String>,
6096    #[serde(default)]
6097    pub server_capabilities: Option<Value>,
6098}
6099
6100/// Result of gracefully removing a worker-plane registration.
6101#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6102pub struct WorkerDeregistrationEnvelope {
6103    pub worker_id: String,
6104    pub outcome: String,
6105    pub recovered_workflow_task_count: u64,
6106}
6107
6108#[derive(Clone, Debug, Deserialize)]
6109pub struct PollWorkflowTaskResponse {
6110    #[serde(default)]
6111    pub task: Option<WorkflowTask>,
6112    #[serde(default)]
6113    pub poll_status: Option<String>,
6114    #[serde(default)]
6115    pub reason: Option<String>,
6116    #[serde(default)]
6117    pub protocol_version: Option<String>,
6118    #[serde(default)]
6119    pub server_capabilities: Option<Value>,
6120}
6121
6122impl PollWorkflowTaskResponse {
6123    /// Classify this response without parsing server display text.
6124    pub fn outcome(&self) -> WorkerPollOutcome {
6125        worker_poll_outcome(
6126            self.task.is_some(),
6127            self.poll_status.as_deref(),
6128            self.reason.as_deref(),
6129        )
6130    }
6131}
6132
6133fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6134    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6135        return false;
6136    };
6137    let supported = capabilities
6138        .get("workflow_memo_updates")
6139        .and_then(Value::as_object)
6140        .and_then(|memo| memo.get("supported"))
6141        .and_then(Value::as_bool)
6142        == Some(true);
6143    let command_advertised = capabilities
6144        .get("supported_workflow_task_commands")
6145        .and_then(Value::as_array)
6146        .is_some_and(|commands| {
6147            commands
6148                .iter()
6149                .any(|command| command.as_str() == Some("upsert_memo"))
6150        });
6151    supported && command_advertised
6152}
6153
6154fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6155    commands
6156        .iter()
6157        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6158}
6159
6160#[derive(Clone, Debug, Deserialize)]
6161pub struct PollActivityTaskResponse {
6162    #[serde(default)]
6163    pub task: Option<ActivityTask>,
6164    #[serde(default)]
6165    pub poll_status: Option<String>,
6166    #[serde(default)]
6167    pub reason: Option<String>,
6168}
6169
6170impl PollActivityTaskResponse {
6171    /// Classify this response without parsing server display text.
6172    pub fn outcome(&self) -> WorkerPollOutcome {
6173        worker_poll_outcome(
6174            self.task.is_some(),
6175            self.poll_status.as_deref(),
6176            self.reason.as_deref(),
6177        )
6178    }
6179}
6180
6181#[derive(Clone, Debug, Deserialize)]
6182pub struct PollQueryTaskResponse {
6183    #[serde(default)]
6184    pub task: Option<QueryTask>,
6185    #[serde(default)]
6186    pub poll_status: Option<String>,
6187    #[serde(default)]
6188    pub reason: Option<String>,
6189}
6190
6191impl PollQueryTaskResponse {
6192    /// Classify this response without parsing server display text.
6193    pub fn outcome(&self) -> WorkerPollOutcome {
6194        worker_poll_outcome(
6195            self.task.is_some(),
6196            self.poll_status.as_deref(),
6197            self.reason.as_deref(),
6198        )
6199    }
6200}
6201
6202/// Stable classification for worker poll responses.
6203#[derive(Clone, Debug, PartialEq, Eq)]
6204pub enum WorkerPollOutcome {
6205    /// A task was leased and is available on the response.
6206    Task,
6207    /// No task was leased, but the worker should continue polling.
6208    Idle {
6209        poll_status: Option<String>,
6210        reason: Option<String>,
6211    },
6212    /// The server asked this worker to stop claiming new work.
6213    Stop {
6214        poll_status: Option<String>,
6215        reason: Option<String>,
6216    },
6217}
6218
6219impl WorkerPollOutcome {
6220    pub fn should_stop(&self) -> bool {
6221        matches!(self, Self::Stop { .. })
6222    }
6223}
6224
6225fn worker_poll_outcome(
6226    has_task: bool,
6227    poll_status: Option<&str>,
6228    reason: Option<&str>,
6229) -> WorkerPollOutcome {
6230    if worker_poll_is_stop(poll_status, reason) {
6231        return WorkerPollOutcome::Stop {
6232            poll_status: poll_status.map(str::to_string),
6233            reason: reason.map(str::to_string),
6234        };
6235    }
6236
6237    if has_task {
6238        WorkerPollOutcome::Task
6239    } else {
6240        WorkerPollOutcome::Idle {
6241            poll_status: poll_status.map(str::to_string),
6242            reason: reason.map(str::to_string),
6243        }
6244    }
6245}
6246
6247/// An ephemeral server-routed query task.
6248#[derive(Clone, Debug, Deserialize)]
6249pub struct QueryTask {
6250    pub query_task_id: String,
6251    #[serde(default = "default_workflow_task_attempt")]
6252    pub query_task_attempt: u64,
6253    #[serde(default)]
6254    pub lease_owner: Option<String>,
6255    #[serde(default)]
6256    pub workflow_id: Option<String>,
6257    #[serde(default)]
6258    pub run_id: Option<String>,
6259    pub workflow_type: String,
6260    pub query_name: String,
6261    #[serde(
6262        default = "missing_task_payload_codec",
6263        deserialize_with = "deserialize_task_payload_codec"
6264    )]
6265    pub payload_codec: String,
6266    #[serde(default)]
6267    pub workflow_arguments: Option<Value>,
6268    #[serde(default)]
6269    pub query_arguments: Option<Value>,
6270    #[serde(default)]
6271    pub history_events: Vec<HistoryEvent>,
6272    #[serde(default)]
6273    pub history_export: Option<Value>,
6274    #[serde(default)]
6275    pub run_status: Option<String>,
6276}
6277
6278#[derive(Clone, Debug, Deserialize)]
6279pub struct WorkflowTask {
6280    pub task_id: String,
6281    #[serde(default)]
6282    pub workflow_command_id: Option<String>,
6283    #[serde(default)]
6284    pub workflow_id: Option<String>,
6285    #[serde(default)]
6286    pub run_id: Option<String>,
6287    pub workflow_type: String,
6288    #[serde(default)]
6289    pub cancel_requested: bool,
6290    #[serde(
6291        default = "missing_task_payload_codec",
6292        deserialize_with = "deserialize_task_payload_codec"
6293    )]
6294    pub payload_codec: String,
6295    #[serde(default)]
6296    pub arguments: Option<Value>,
6297    #[serde(default)]
6298    pub history_events: Vec<HistoryEvent>,
6299    #[serde(default)]
6300    pub total_history_events: Option<u64>,
6301    #[serde(default)]
6302    pub history_size_bytes: Option<u64>,
6303    #[serde(default)]
6304    pub continue_as_new_recommended: Option<bool>,
6305    #[serde(default)]
6306    pub history_budget_pressure: Option<String>,
6307    #[serde(default)]
6308    pub next_history_page_token: Option<String>,
6309    #[serde(default = "default_workflow_task_attempt")]
6310    pub workflow_task_attempt: u64,
6311    #[serde(default)]
6312    pub workflow_signal_id: Option<String>,
6313    #[serde(default)]
6314    pub signal_name: Option<String>,
6315    #[serde(default)]
6316    pub signal_arguments: Option<Value>,
6317    #[serde(default)]
6318    pub workflow_update_id: Option<String>,
6319    #[serde(default)]
6320    pub update_name: Option<String>,
6321    #[serde(default)]
6322    pub lease_owner: Option<String>,
6323}
6324
6325impl WorkflowTask {
6326    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6327        self.history_events.extend(page.history_events);
6328
6329        if page.total_history_events.is_some() {
6330            self.total_history_events = page.total_history_events;
6331        }
6332
6333        self.next_history_page_token = page
6334            .next_history_page_token
6335            .filter(|token| !token.is_empty());
6336    }
6337}
6338
6339#[derive(Clone, Debug, Deserialize)]
6340struct WorkflowTaskHistoryPage {
6341    #[serde(default)]
6342    history_events: Vec<HistoryEvent>,
6343    #[serde(default)]
6344    total_history_events: Option<u64>,
6345    #[serde(default)]
6346    next_history_page_token: Option<String>,
6347}
6348
6349#[derive(Clone, Debug, Deserialize)]
6350pub struct ActivityTask {
6351    pub task_id: String,
6352    #[serde(default)]
6353    pub activity_attempt_id: Option<String>,
6354    #[serde(default)]
6355    pub attempt_id: Option<String>,
6356    pub activity_type: String,
6357    #[serde(
6358        default = "missing_task_payload_codec",
6359        deserialize_with = "deserialize_task_payload_codec"
6360    )]
6361    pub payload_codec: String,
6362    #[serde(default)]
6363    pub arguments: Option<Value>,
6364    #[serde(default = "default_attempt_number")]
6365    pub attempt_number: u64,
6366    #[serde(default)]
6367    pub lease_owner: Option<String>,
6368}
6369
6370#[derive(Clone, Debug, Serialize, Deserialize)]
6371pub struct HistoryEvent {
6372    #[serde(alias = "type")]
6373    pub event_type: String,
6374    #[serde(default)]
6375    pub payload: Value,
6376    #[serde(flatten)]
6377    pub raw: HashMap<String, Value>,
6378}
6379
6380/// One decoded signal in the committed workflow-history snapshot.
6381#[derive(Clone, Debug, PartialEq)]
6382pub struct QuerySignal {
6383    pub id: Option<String>,
6384    pub name: String,
6385    pub arguments: Vec<Value>,
6386    avro_arguments: Vec<AvroValue>,
6387    pub workflow_sequence: Option<u64>,
6388}
6389
6390impl QuerySignal {
6391    /// Lossless fixed Avro Value arguments for this committed signal.
6392    pub fn arguments_avro_value(&self) -> &[AvroValue] {
6393        &self.avro_arguments
6394    }
6395}
6396
6397/// Immutable state supplied to a registered query handler.
6398///
6399/// This context intentionally exposes no activity, signal-wait, or command
6400/// APIs. Query handlers inspect committed history and return a value; query
6401/// completion does not append an event or advance deterministic execution.
6402#[derive(Clone, Debug)]
6403pub struct QueryContext {
6404    pub workflow_id: Option<String>,
6405    pub run_id: Option<String>,
6406    pub workflow_type: String,
6407    pub run_status: Option<String>,
6408    workflow_input: Value,
6409    workflow_input_avro_value: AvroValue,
6410    history_events: Arc<Vec<HistoryEvent>>,
6411    signal_events: Arc<Vec<QuerySignal>>,
6412}
6413
6414impl QueryContext {
6415    /// The normalized argument list used to start the workflow.
6416    pub fn workflow_input(&self) -> &Value {
6417        &self.workflow_input
6418    }
6419
6420    /// The lossless fixed Avro Value argument list used to start the workflow.
6421    pub fn workflow_input_avro_value(&self) -> &AvroValue {
6422        &self.workflow_input_avro_value
6423    }
6424
6425    /// The immutable committed history used for this query snapshot.
6426    pub fn history_events(&self) -> &[HistoryEvent] {
6427        self.history_events.as_slice()
6428    }
6429
6430    /// All decoded signals in committed workflow order.
6431    pub fn signal_events(&self) -> &[QuerySignal] {
6432        self.signal_events.as_slice()
6433    }
6434
6435    /// Decoded argument lists for each committed signal with `signal_name`.
6436    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
6437        self.signal_events
6438            .iter()
6439            .filter(|signal| signal.name == signal_name)
6440            .map(|signal| signal.arguments.clone())
6441            .collect()
6442    }
6443
6444    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
6445    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
6446        self.signal_events
6447            .iter()
6448            .filter(|signal| signal.name == signal_name)
6449            .map(|signal| signal.avro_arguments.clone())
6450            .collect()
6451    }
6452}
6453
6454#[derive(Clone, Debug, Deserialize)]
6455pub struct ActivityHeartbeatResponse {
6456    #[serde(default)]
6457    pub cancel_requested: bool,
6458    #[serde(default)]
6459    pub heartbeat_recorded: bool,
6460    #[serde(default)]
6461    pub can_continue: Option<bool>,
6462    #[serde(default)]
6463    pub reason: Option<String>,
6464    #[serde(default)]
6465    pub run_closed_reason: Option<String>,
6466    #[serde(default)]
6467    pub run_closed_at: Option<String>,
6468    #[serde(default)]
6469    pub lease_expires_at: Option<String>,
6470    #[serde(default)]
6471    pub last_heartbeat_at: Option<String>,
6472}
6473
6474impl ActivityHeartbeatResponse {
6475    /// Whether the activity should stop instead of attempting completion.
6476    pub fn should_stop(&self) -> bool {
6477        self.cancel_requested || self.can_continue == Some(false)
6478    }
6479}
6480
6481fn missing_task_payload_codec() -> String {
6482    MISSING_TASK_PAYLOAD_CODEC.to_string()
6483}
6484
6485fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
6486where
6487    D: Deserializer<'de>,
6488{
6489    Ok(match Value::deserialize(deserializer)? {
6490        Value::String(codec) => codec,
6491        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
6492        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
6493    })
6494}
6495
6496fn default_workflow_task_attempt() -> u64 {
6497    1
6498}
6499
6500fn default_attempt_number() -> u64 {
6501    1
6502}
6503
6504type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6505type WorkflowHandler = Arc<dyn Fn(WorkflowContext, AvroValue) -> WorkflowFuture + Send + Sync>;
6506type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
6507type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
6508type ReplayedWorkflowHandler =
6509    Arc<dyn Fn(WorkflowContext, AvroValue) -> ReplayedWorkflowInvocation + Send + Sync>;
6510type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6511type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
6512type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
6513type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6514type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
6515type ReplayedQueryHandler = Arc<
6516    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
6517        + Send
6518        + Sync,
6519>;
6520type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
6521
6522struct ReplayedWorkflowInvocation {
6523    future: WorkflowFuture,
6524    snapshot: WorkflowStateSnapshot,
6525}
6526
6527#[derive(Clone)]
6528struct RegisteredWorkflow {
6529    execute: WorkflowHandler,
6530    replay: Option<ReplayedWorkflowHandler>,
6531    state_type: Option<TypeId>,
6532    definition_fingerprint: Option<String>,
6533}
6534
6535fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
6536    names
6537        .iter()
6538        .map(|name| {
6539            json!({
6540                "name": name,
6541                "parameters": [{
6542                    "name": "args",
6543                    "position": 0,
6544                    "required": false,
6545                    "variadic": true,
6546                    "type": null,
6547                    "allows_null": true,
6548                    "default_available": false,
6549                    "default": null,
6550                }],
6551            })
6552        })
6553        .collect()
6554}
6555
6556#[derive(Debug)]
6557struct WorkflowTaskDecision {
6558    commands: Vec<Value>,
6559    message_stream_cursors: Vec<Value>,
6560    message_stream_waits: Vec<Value>,
6561    cancellation_delivery: Option<CancellationDelivery>,
6562    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
6563    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
6564}
6565
6566enum PreparedWorkflowTask {
6567    Decision(WorkflowTaskDecision),
6568    Execution {
6569        task: WorkflowTask,
6570        context: WorkflowContext,
6571        future: WorkflowFuture,
6572    },
6573}
6574
6575impl WorkflowTaskDecision {
6576    fn without_message_streams(commands: Vec<Value>) -> Self {
6577        Self {
6578            commands,
6579            message_stream_cursors: Vec::new(),
6580            message_stream_waits: Vec::new(),
6581            cancellation_delivery: None,
6582            cancellation_scope_opening: None,
6583            cancellation_scope_delivery: None,
6584        }
6585    }
6586}
6587
6588#[derive(Clone)]
6589enum RegisteredQuery {
6590    Snapshot(QueryHandler),
6591    Replayed {
6592        state_type: TypeId,
6593        handler: ReplayedQueryHandler,
6594    },
6595}
6596
6597#[derive(Clone, Debug)]
6598pub struct WorkerHeartbeatObservation {
6599    pub worker_id: String,
6600    pub task_queue: String,
6601    pub acknowledged_at_unix_millis: u64,
6602    pub acknowledgement: Value,
6603}
6604
6605/// Bounded retry policy for worker poll acquisition and worker heartbeats.
6606///
6607/// Expected empty long polls and explicit Server capacity backpressure are
6608/// normal worker states. Capacity backpressure honors the advertised retry
6609/// delay without consuming this retry budget. Other transport failures,
6610/// retryable HTTP 408/429 responses, and server errors are retried with capped
6611/// exponential backoff. Authentication, protocol, codec, and handler failures
6612/// are never retried by the worker.
6613/// Explicit storage admission pauses also preserve the already-serialized worker
6614/// request without consuming this budget or rerunning its handler. The delay is
6615/// capped by `max_backoff`, and shutdown interrupts storage waits.
6616/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
6617/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
6618/// and `max_retries = 0` disables ordinary retries in either mode.
6619#[derive(Clone, Copy, Debug)]
6620pub struct WorkerRetryPolicy {
6621    /// Number of retries after the initial request fails.
6622    pub max_retries: usize,
6623    /// Delay before the first retry.
6624    pub initial_backoff: Duration,
6625    /// Maximum delay between retries.
6626    pub max_backoff: Duration,
6627}
6628
6629impl Default for WorkerRetryPolicy {
6630    fn default() -> Self {
6631        Self {
6632            max_retries: 5,
6633            initial_backoff: Duration::from_millis(100),
6634            max_backoff: Duration::from_secs(5),
6635        }
6636    }
6637}
6638
6639#[derive(Clone, Debug)]
6640struct WorkerStorageAdmission {
6641    policy: WorkerRetryPolicy,
6642    stop: Arc<AtomicBool>,
6643}
6644
6645struct StopWorkerOnDrop(Arc<AtomicBool>);
6646
6647impl Drop for StopWorkerOnDrop {
6648    fn drop(&mut self) {
6649        self.0.store(true, Ordering::SeqCst);
6650    }
6651}
6652
6653async fn wait_for_worker_stop(stop: &AtomicBool) {
6654    while !stop.load(Ordering::SeqCst) {
6655        tokio::time::sleep(Duration::from_millis(100)).await;
6656    }
6657}
6658
6659#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6660enum ManagedPollOutcome {
6661    Idle,
6662    Handled,
6663    Stop,
6664}
6665
6666#[derive(Clone)]
6667pub struct Worker {
6668    client: Client,
6669    worker_id: String,
6670    task_queue: String,
6671    workflows: HashMap<String, RegisteredWorkflow>,
6672    activities: HashMap<String, ActivityHandler>,
6673    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
6674    signals: HashMap<String, Vec<String>>,
6675    updates: HashMap<String, HashMap<String, UpdateHandler>>,
6676    registration_definitions:
6677        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
6678    registration_error: Option<DuplicateRegistrationError>,
6679    max_concurrent_workflow_tasks: usize,
6680    max_concurrent_activity_tasks: usize,
6681    poll_timeout: Duration,
6682    heartbeat_interval: Duration,
6683    retry_policy: WorkerRetryPolicy,
6684    recover_transient_outages: bool,
6685    run_stop: Option<Arc<AtomicBool>>,
6686    heartbeat_observer: Option<WorkerHeartbeatObserver>,
6687    cooperative_cancellation_enabled: bool,
6688    allow_cancellation_scope_authoring: bool,
6689    allow_cancellation_scope_delivery: bool,
6690    cooperative_registration_confirmed: Arc<AtomicBool>,
6691    local_registration_confirmed: Arc<AtomicBool>,
6692    session_registration_confirmed: Arc<AtomicBool>,
6693    sticky_registration_confirmed: Arc<AtomicBool>,
6694    resource_capabilities: Vec<String>,
6695    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
6696}
6697
6698impl Worker {
6699    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
6700        Self {
6701            client,
6702            worker_id: default_worker_id(),
6703            task_queue: task_queue.into(),
6704            workflows: HashMap::new(),
6705            activities: HashMap::new(),
6706            queries: HashMap::new(),
6707            signals: HashMap::new(),
6708            updates: HashMap::new(),
6709            registration_definitions: HashMap::new(),
6710            registration_error: None,
6711            max_concurrent_workflow_tasks: 10,
6712            max_concurrent_activity_tasks: 10,
6713            poll_timeout: Duration::from_secs(30),
6714            heartbeat_interval: Duration::from_secs(60),
6715            retry_policy: WorkerRetryPolicy::default(),
6716            recover_transient_outages: false,
6717            run_stop: None,
6718            heartbeat_observer: None,
6719            cooperative_cancellation_enabled: false,
6720            allow_cancellation_scope_authoring: false,
6721            allow_cancellation_scope_delivery: false,
6722            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
6723            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
6724            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
6725            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
6726            resource_capabilities: Vec::new(),
6727            sessions: Arc::new(Mutex::new(HashMap::new())),
6728        }
6729    }
6730
6731    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
6732        self.worker_id = worker_id.into();
6733        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6734        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6735        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
6736        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
6737        self.client.reset_sticky_cache();
6738        self.sessions = Arc::new(Mutex::new(HashMap::new()));
6739        self
6740    }
6741
6742    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
6743        self.poll_timeout = timeout;
6744        self
6745    }
6746
6747    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
6748        self.heartbeat_interval = interval;
6749        self
6750    }
6751
6752    /// Explicitly enable inline local activities in this workflow worker.
6753    ///
6754    /// The worker advertises the capability to Server only when enabled.
6755    /// These callbacks must yield to Tokio and have idempotent side effects.
6756    /// Cooperative prepared local supervision is a separate capability.
6757    pub fn local_activities(mut self, enabled: bool) -> Self {
6758        self.client.local_activities_enabled = enabled;
6759        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
6760        self
6761    }
6762
6763    /// Opt in to separate cooperative workflow cancellation requests.
6764    ///
6765    /// Registration requires the Server to acknowledge this exact worker,
6766    /// namespace, queue and capabilities with compatible protocol 1.20. Task
6767    /// processing uses canonical delivery and activity ownership fences.
6768    /// Existing terminal cancel and terminate operations remain terminal.
6769    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
6770    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
6771    /// and [`Worker::run_until`] register automatically.
6772    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
6773        self.cooperative_cancellation_enabled = enabled;
6774        self.client.cooperative_worker_protocol = enabled;
6775        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
6776        self
6777    }
6778
6779    /// Enable candidate scope authoring without advertising scoped execution.
6780    #[doc(hidden)]
6781    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
6782        self.allow_cancellation_scope_authoring = enabled;
6783        self
6784    }
6785
6786    /// Enable the candidate scoped call consumer with canonical authoring.
6787    #[doc(hidden)]
6788    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
6789        self.allow_cancellation_scope_delivery = enabled;
6790        self
6791    }
6792
6793    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
6794    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
6795        self.retry_policy = policy;
6796        self
6797    }
6798
6799    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
6800    ///
6801    /// Retries preserve the poll request identity and use capped exponential
6802    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
6803    /// An in-flight poll is allowed to finish so leased work is not discarded.
6804    /// Authentication, protocol, codec, handler and task settlement failures
6805    /// remain errors. Registration and deregistration are not retried here.
6806    ///
6807    /// The default is disabled, preserving the bounded retry contract.
6808    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
6809    /// even when this option is enabled.
6810    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
6811        self.recover_transient_outages = enabled;
6812        self
6813    }
6814
6815    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
6816    where
6817        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
6818    {
6819        self.heartbeat_observer = Some(Arc::new(observer));
6820        self
6821    }
6822
6823    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
6824        self.max_concurrent_workflow_tasks = count.max(1);
6825        self
6826    }
6827
6828    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
6829        self.max_concurrent_activity_tasks = count.max(1);
6830        self
6831    }
6832
6833    /// Validate local handler admission without making a Server request.
6834    ///
6835    /// Registration methods retain their existing signatures. A duplicate keeps
6836    /// the original handler and makes this Worker invalid, including its clones.
6837    /// `register`, `run`, `run_until` and `run_once` enforce this check before
6838    /// any network request. Build a new Worker to correct an invalid configuration.
6839    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
6840        match &self.registration_error {
6841            Some(error) => Err(error.clone()),
6842            None => Ok(()),
6843        }
6844    }
6845
6846    #[track_caller]
6847    fn admit_registration<F>(
6848        &mut self,
6849        handler_kind: RegistrationKind,
6850        workflow_type: Option<&str>,
6851        handler_name: &str,
6852        method: &'static str,
6853    ) -> bool {
6854        let location = std::panic::Location::caller();
6855        let definition = HandlerRegistration {
6856            method,
6857            handler_type: type_name::<F>(),
6858            file: location.file(),
6859            line: location.line(),
6860            column: location.column(),
6861        };
6862        let key = (
6863            handler_kind,
6864            workflow_type.map(str::to_owned),
6865            handler_name.to_owned(),
6866        );
6867        if let Some(first_definition) = self.registration_definitions.get(&key) {
6868            if self.registration_error.is_none() {
6869                self.registration_error = Some(DuplicateRegistrationError {
6870                    handler_kind,
6871                    workflow_type: key.1.clone(),
6872                    handler_name: key.2.clone(),
6873                    first_definition: first_definition.clone(),
6874                    second_definition: definition,
6875                });
6876            }
6877            return false;
6878        }
6879        self.registration_definitions.insert(key, definition);
6880        true
6881    }
6882
6883    /// Register a workflow handler.
6884    ///
6885    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
6886    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
6887    /// while acquiring or decoding a worker task remain worker-operation
6888    /// failures and do not get converted into workflow outcomes.
6889    #[track_caller]
6890    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
6891    where
6892        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
6893        Fut: Future<Output = Result<Value>> + Send + 'static,
6894    {
6895        let workflow_type = workflow_type.into();
6896        if !self.admit_registration::<F>(
6897            RegistrationKind::Workflow,
6898            None,
6899            &workflow_type,
6900            "register_workflow",
6901        ) {
6902            return;
6903        }
6904        let handler = Arc::new(handler);
6905        self.workflows.insert(
6906            workflow_type,
6907            RegisteredWorkflow {
6908                execute: Arc::new(move |ctx, input| {
6909                    let handler = Arc::clone(&handler);
6910                    Box::pin(async move {
6911                        let result = handler(ctx, input.into_json()?).await?;
6912                        AvroValue::from_serialize(&result)
6913                    })
6914                }),
6915                replay: None,
6916                state_type: None,
6917                definition_fingerprint: None,
6918            },
6919        );
6920    }
6921
6922    /// Register a workflow with one Serde request value and a Serde result.
6923    ///
6924    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
6925    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
6926    /// workflow-specific schema. A task must contain zero arguments for a unit
6927    /// request or exactly one argument for every other request type.
6928    ///
6929    /// See the runnable
6930    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
6931    /// for typed workflow and activity contracts with retry and timeout policy.
6932    #[track_caller]
6933    pub fn register_typed_workflow<I, O, F, Fut>(
6934        &mut self,
6935        workflow_type: impl Into<String>,
6936        handler: F,
6937    ) where
6938        I: DeserializeOwned + Send + 'static,
6939        O: Serialize + Send + 'static,
6940        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
6941        Fut: Future<Output = Result<O>> + Send + 'static,
6942    {
6943        let workflow_type = workflow_type.into();
6944        if !self.admit_registration::<F>(
6945            RegistrationKind::Workflow,
6946            None,
6947            &workflow_type,
6948            "register_typed_workflow",
6949        ) {
6950            return;
6951        }
6952        let handler_name = workflow_type.clone();
6953        let handler = Arc::new(handler);
6954        self.workflows.insert(
6955            workflow_type,
6956            RegisteredWorkflow {
6957                execute: Arc::new(move |ctx, input| {
6958                    let handler = Arc::clone(&handler);
6959                    let handler_name = handler_name.clone();
6960                    Box::pin(async move {
6961                        let input =
6962                            decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
6963                        let result = handler(ctx, input).await?;
6964                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
6965                    })
6966                }),
6967                replay: None,
6968                state_type: None,
6969                definition_fingerprint: None,
6970            },
6971        );
6972    }
6973
6974    /// Register a workflow on the lossless fixed Avro Value surface.
6975    #[track_caller]
6976    pub fn register_workflow_avro_value<F, Fut>(
6977        &mut self,
6978        workflow_type: impl Into<String>,
6979        handler: F,
6980    ) where
6981        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
6982        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
6983    {
6984        let workflow_type = workflow_type.into();
6985        if !self.admit_registration::<F>(
6986            RegistrationKind::Workflow,
6987            None,
6988            &workflow_type,
6989            "register_workflow_avro_value",
6990        ) {
6991            return;
6992        }
6993        self.workflows.insert(
6994            workflow_type,
6995            RegisteredWorkflow {
6996                execute: Arc::new(move |ctx, input| Box::pin(handler(ctx, input))),
6997                replay: None,
6998                state_type: None,
6999                definition_fingerprint: None,
7000            },
7001        );
7002    }
7003
7004    /// Register a workflow whose typed instance state can be reconstructed for queries.
7005    ///
7006    /// `state_factory` creates a fresh instance for every normal workflow task and
7007    /// query replay. The workflow handler is the single source of truth for state
7008    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7009    /// resolve. Query replay runs this same handler over committed history and
7010    /// discards any commands it would emit.
7011    #[track_caller]
7012    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7013        &mut self,
7014        workflow_type: impl Into<String>,
7015        state_factory: Factory,
7016        handler: F,
7017    ) where
7018        S: Clone + Send + Sync + 'static,
7019        Factory: Fn() -> S + Send + Sync + 'static,
7020        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7021        Fut: Future<Output = Result<Value>> + Send + 'static,
7022    {
7023        let workflow_type = workflow_type.into();
7024        if !self.admit_registration::<F>(
7025            RegistrationKind::Workflow,
7026            None,
7027            &workflow_type,
7028            "register_replayed_workflow",
7029        ) {
7030            return;
7031        }
7032        let state_factory = Arc::new(state_factory);
7033        let handler = Arc::new(handler);
7034
7035        let execute_factory = Arc::clone(&state_factory);
7036        let execute_handler = Arc::clone(&handler);
7037        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7038            let state = WorkflowInstance::new(execute_factory());
7039            let handler = Arc::clone(&execute_handler);
7040            Box::pin(async move {
7041                let result = handler(ctx, input.into_json()?, state).await?;
7042                AvroValue::from_serialize(&result)
7043            }) as WorkflowFuture
7044        });
7045
7046        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7047            let state = WorkflowInstance::new(state_factory());
7048            let snapshot_state = state.clone();
7049            let snapshot: WorkflowStateSnapshot =
7050                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7051            let replay_handler = Arc::clone(&handler);
7052            let future = async move {
7053                let result = replay_handler(ctx, input.into_json()?, state).await?;
7054                AvroValue::from_serialize(&result)
7055            };
7056            ReplayedWorkflowInvocation {
7057                future: Box::pin(future),
7058                snapshot,
7059            }
7060        });
7061
7062        self.workflows.insert(
7063            workflow_type,
7064            RegisteredWorkflow {
7065                execute,
7066                replay: Some(replay),
7067                state_type: Some(TypeId::of::<S>()),
7068                definition_fingerprint: None,
7069            },
7070        );
7071    }
7072
7073    /// Register a replayable workflow with one Serde request value and result.
7074    ///
7075    /// Normal task execution and instance-state query replay both decode and
7076    /// encode through the fixed Avro Value codec. The state factory and handler
7077    /// otherwise follow [`Worker::register_replayed_workflow`].
7078    #[track_caller]
7079    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7080        &mut self,
7081        workflow_type: impl Into<String>,
7082        state_factory: Factory,
7083        handler: F,
7084    ) where
7085        I: DeserializeOwned + Send + 'static,
7086        O: Serialize + Send + 'static,
7087        S: Clone + Send + Sync + 'static,
7088        Factory: Fn() -> S + Send + Sync + 'static,
7089        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7090        Fut: Future<Output = Result<O>> + Send + 'static,
7091    {
7092        let workflow_type = workflow_type.into();
7093        if !self.admit_registration::<F>(
7094            RegistrationKind::Workflow,
7095            None,
7096            &workflow_type,
7097            "register_typed_replayed_workflow",
7098        ) {
7099            return;
7100        }
7101        let state_factory = Arc::new(state_factory);
7102        let handler = Arc::new(handler);
7103
7104        let execute_name = workflow_type.clone();
7105        let execute_factory = Arc::clone(&state_factory);
7106        let execute_handler = Arc::clone(&handler);
7107        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7108            let state = WorkflowInstance::new(execute_factory());
7109            let handler = Arc::clone(&execute_handler);
7110            let handler_name = execute_name.clone();
7111            Box::pin(async move {
7112                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7113                let result = handler(ctx, input, state).await?;
7114                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7115            }) as WorkflowFuture
7116        });
7117
7118        let replay_name = workflow_type.clone();
7119        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7120            let state = WorkflowInstance::new(state_factory());
7121            let snapshot_state = state.clone();
7122            let snapshot: WorkflowStateSnapshot =
7123                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7124            let handler = Arc::clone(&handler);
7125            let handler_name = replay_name.clone();
7126            let future = async move {
7127                let input = decode_handler_input::<I>(input, HandlerKind::Workflow, &handler_name)?;
7128                let result = handler(ctx, input, state).await?;
7129                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7130            };
7131            ReplayedWorkflowInvocation {
7132                future: Box::pin(future),
7133                snapshot,
7134            }
7135        });
7136
7137        self.workflows.insert(
7138            workflow_type,
7139            RegisteredWorkflow {
7140                execute,
7141                replay: Some(replay),
7142                state_type: Some(TypeId::of::<S>()),
7143                definition_fingerprint: None,
7144            },
7145        );
7146    }
7147
7148    /// Declare the signal names consumed by a registered workflow.
7149    ///
7150    /// Call this after registering the workflow and before starting the worker.
7151    /// Names read through `wait_signal` or `signals` need a declaration for
7152    /// Server command admission. Arguments remain arbitrary positional values,
7153    /// including lossless Avro values. This replaces the previous declaration;
7154    /// an empty slice declares no signals. Names are sorted and deduplicated.
7155    /// Existing runs retain the declarations captured when they started.
7156    pub fn declare_workflow_signals(
7157        &mut self,
7158        workflow_type: &str,
7159        signal_names: &[&str],
7160    ) -> Result<()> {
7161        if !self.workflows.contains_key(workflow_type) {
7162            return Err(Error::Codec(format!(
7163                "workflow type {workflow_type:?} is not registered"
7164            )));
7165        }
7166        if signal_names
7167            .iter()
7168            .any(|name| name.is_empty() || *name != name.trim())
7169        {
7170            return Err(Error::Codec(
7171                "signal names must be non-empty and have no surrounding whitespace".into(),
7172            ));
7173        }
7174        let mut names = signal_names
7175            .iter()
7176            .map(|name| (*name).to_string())
7177            .collect::<Vec<_>>();
7178        names.sort();
7179        names.dedup();
7180        self.signals.insert(workflow_type.to_string(), names);
7181        Ok(())
7182    }
7183
7184    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7185    ///
7186    /// Supply `include_str!` values for the workflow body and every helper whose
7187    /// behavior can affect replay. Register the workflow once, then set its
7188    /// identity before starting the worker. Duplicate registrations are invalid. The server
7189    /// rejects reusing a worker ID when its prior fingerprint disappears.
7190    /// Workflows without source identity remain runnable but cannot be safely redriven.
7191    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7192    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7193    pub fn set_workflow_definition_sources(
7194        &mut self,
7195        workflow_type: &str,
7196        sources: &[&str],
7197    ) -> Result<()> {
7198        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7199            return Err(Error::Codec(
7200                "workflow definition sources must be non-empty".to_string(),
7201            ));
7202        }
7203        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7204            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7205        })?;
7206        let mut hasher = Sha256::new();
7207        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7208        hasher.update((workflow_type.len() as u64).to_be_bytes());
7209        hasher.update(workflow_type.as_bytes());
7210        for source in sources {
7211            hasher.update((source.len() as u64).to_be_bytes());
7212            hasher.update(source.as_bytes());
7213        }
7214        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7215        Ok(())
7216    }
7217
7218    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7219    #[track_caller]
7220    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7221        &mut self,
7222        workflow_type: impl Into<String>,
7223        state_factory: Factory,
7224        handler: F,
7225    ) where
7226        S: Clone + Send + Sync + 'static,
7227        Factory: Fn() -> S + Send + Sync + 'static,
7228        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7229        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7230    {
7231        let workflow_type = workflow_type.into();
7232        if !self.admit_registration::<F>(
7233            RegistrationKind::Workflow,
7234            None,
7235            &workflow_type,
7236            "register_replayed_workflow_avro_value",
7237        ) {
7238            return;
7239        }
7240        let state_factory = Arc::new(state_factory);
7241        let handler = Arc::new(handler);
7242
7243        let execute_factory = Arc::clone(&state_factory);
7244        let execute_handler = Arc::clone(&handler);
7245        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7246            let state = WorkflowInstance::new(execute_factory());
7247            Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture
7248        });
7249
7250        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7251            let state = WorkflowInstance::new(state_factory());
7252            let snapshot_state = state.clone();
7253            let snapshot: WorkflowStateSnapshot =
7254                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7255            ReplayedWorkflowInvocation {
7256                future: Box::pin(handler(ctx, input, state)),
7257                snapshot,
7258            }
7259        });
7260
7261        self.workflows.insert(
7262            workflow_type,
7263            RegisteredWorkflow {
7264                execute,
7265                replay: Some(replay),
7266                state_type: Some(TypeId::of::<S>()),
7267                definition_fingerprint: None,
7268            },
7269        );
7270    }
7271
7272    #[track_caller]
7273    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7274    where
7275        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7276        Fut: Future<Output = Result<Value>> + Send + 'static,
7277    {
7278        let activity_type = activity_type.into();
7279        if !self.admit_registration::<F>(
7280            RegistrationKind::Activity,
7281            None,
7282            &activity_type,
7283            "register_activity",
7284        ) {
7285            return;
7286        }
7287        let handler = Arc::new(handler);
7288        self.activities.insert(
7289            activity_type,
7290            Arc::new(move |ctx, args| {
7291                let handler = Arc::clone(&handler);
7292                Box::pin(async move {
7293                    let result = handler(ctx, args.into_json()?).await?;
7294                    AvroValue::from_serialize(&result)
7295                })
7296            }),
7297        );
7298    }
7299
7300    /// Register an activity with one Serde request value and a Serde result.
7301    ///
7302    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7303    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7304    /// with the activity name and Rust type.
7305    #[track_caller]
7306    pub fn register_typed_activity<I, O, F, Fut>(
7307        &mut self,
7308        activity_type: impl Into<String>,
7309        handler: F,
7310    ) where
7311        I: DeserializeOwned + Send + 'static,
7312        O: Serialize + Send + 'static,
7313        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
7314        Fut: Future<Output = Result<O>> + Send + 'static,
7315    {
7316        let activity_type = activity_type.into();
7317        if !self.admit_registration::<F>(
7318            RegistrationKind::Activity,
7319            None,
7320            &activity_type,
7321            "register_typed_activity",
7322        ) {
7323            return;
7324        }
7325        let handler_name = activity_type.clone();
7326        let handler = Arc::new(handler);
7327        self.activities.insert(
7328            activity_type,
7329            Arc::new(move |ctx, input| {
7330                let handler = Arc::clone(&handler);
7331                let handler_name = handler_name.clone();
7332                Box::pin(async move {
7333                    let input =
7334                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
7335                    let result = handler(ctx, input).await?;
7336                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
7337                })
7338            }),
7339        );
7340    }
7341
7342    /// Register an activity on the lossless fixed Avro Value surface.
7343    #[track_caller]
7344    pub fn register_activity_avro_value<F, Fut>(
7345        &mut self,
7346        activity_type: impl Into<String>,
7347        handler: F,
7348    ) where
7349        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
7350        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7351    {
7352        let activity_type = activity_type.into();
7353        if !self.admit_registration::<F>(
7354            RegistrationKind::Activity,
7355            None,
7356            &activity_type,
7357            "register_activity_avro_value",
7358        ) {
7359            return;
7360        }
7361        self.activities.insert(
7362            activity_type,
7363            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7364        );
7365    }
7366
7367    /// Register a named, read-only query handler for a workflow type.
7368    ///
7369    /// The workflow type must also be registered with [`Worker::register_workflow`]
7370    /// before the worker runs. The handler receives only an immutable committed
7371    /// state snapshot and normalized query arguments.
7372    #[track_caller]
7373    pub fn register_query<F, Fut>(
7374        &mut self,
7375        workflow_type: impl Into<String>,
7376        query_name: impl Into<String>,
7377        handler: F,
7378    ) where
7379        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7380        Fut: Future<Output = Result<Value>> + Send + 'static,
7381    {
7382        let workflow_type = workflow_type.into();
7383        let query_name = query_name.into();
7384        if !self.admit_registration::<F>(
7385            RegistrationKind::Query,
7386            Some(&workflow_type),
7387            &query_name,
7388            "register_query",
7389        ) {
7390            return;
7391        }
7392        let handler = Arc::new(handler);
7393        self.queries.entry(workflow_type).or_default().insert(
7394            query_name,
7395            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
7396                let handler = Arc::clone(&handler);
7397                Box::pin(async move {
7398                    let result = handler(ctx, args.into_json()?).await?;
7399                    AvroValue::from_serialize(&result)
7400                })
7401            })),
7402        );
7403    }
7404
7405    /// Register a query handler on the lossless fixed Avro Value surface.
7406    #[track_caller]
7407    pub fn register_query_avro_value<F, Fut>(
7408        &mut self,
7409        workflow_type: impl Into<String>,
7410        query_name: impl Into<String>,
7411        handler: F,
7412    ) where
7413        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7414        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7415    {
7416        let workflow_type = workflow_type.into();
7417        let query_name = query_name.into();
7418        if !self.admit_registration::<F>(
7419            RegistrationKind::Query,
7420            Some(&workflow_type),
7421            &query_name,
7422            "register_query_avro_value",
7423        ) {
7424            return;
7425        }
7426        self.queries.entry(workflow_type).or_default().insert(
7427            query_name,
7428            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
7429        );
7430    }
7431
7432    /// Register a named query against deterministically replayed instance state.
7433    ///
7434    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
7435    /// same state type `S`. The handler receives an immutable, detached state
7436    /// clone, so successful and failed queries cannot affect workflow execution
7437    /// or the state reconstructed by a later query.
7438    #[track_caller]
7439    pub fn register_replayed_query<S, F, Fut>(
7440        &mut self,
7441        workflow_type: impl Into<String>,
7442        query_name: impl Into<String>,
7443        handler: F,
7444    ) where
7445        S: Clone + Send + Sync + 'static,
7446        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
7447        Fut: Future<Output = Result<Value>> + Send + 'static,
7448    {
7449        let workflow_type = workflow_type.into();
7450        let query_name = query_name.into();
7451        if !self.admit_registration::<F>(
7452            RegistrationKind::Query,
7453            Some(&workflow_type),
7454            &query_name,
7455            "register_replayed_query",
7456        ) {
7457            return;
7458        }
7459        let handler = Arc::new(handler);
7460        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7461            let state = state.downcast::<S>().map_err(|_| {
7462                "registered query state type does not match the replayed workflow state".to_string()
7463            })?;
7464            let handler = Arc::clone(&handler);
7465            Ok(Box::pin(async move {
7466                let result = handler(ctx, state, args.into_json()?).await?;
7467                AvroValue::from_serialize(&result)
7468            }))
7469        });
7470
7471        self.queries.entry(workflow_type).or_default().insert(
7472            query_name,
7473            RegisteredQuery::Replayed {
7474                state_type: TypeId::of::<S>(),
7475                handler: erased_handler,
7476            },
7477        );
7478    }
7479
7480    /// Register a replayed-state query on the lossless fixed Avro Value surface.
7481    #[track_caller]
7482    pub fn register_replayed_query_avro_value<S, F, Fut>(
7483        &mut self,
7484        workflow_type: impl Into<String>,
7485        query_name: impl Into<String>,
7486        handler: F,
7487    ) where
7488        S: Clone + Send + Sync + 'static,
7489        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
7490        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7491    {
7492        let workflow_type = workflow_type.into();
7493        let query_name = query_name.into();
7494        if !self.admit_registration::<F>(
7495            RegistrationKind::Query,
7496            Some(&workflow_type),
7497            &query_name,
7498            "register_replayed_query_avro_value",
7499        ) {
7500            return;
7501        }
7502        let handler = Arc::new(handler);
7503        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
7504            let state = state.downcast::<S>().map_err(|_| {
7505                "registered query state type does not match the replayed workflow state".to_string()
7506            })?;
7507            Ok(Box::pin(handler(ctx, state, args)))
7508        });
7509
7510        self.queries.entry(workflow_type).or_default().insert(
7511            query_name,
7512            RegisteredQuery::Replayed {
7513                state_type: TypeId::of::<S>(),
7514                handler: erased_handler,
7515            },
7516        );
7517    }
7518
7519    /// Register a synchronous workflow update handler.
7520    #[track_caller]
7521    pub fn register_update<F, Fut>(
7522        &mut self,
7523        workflow_type: impl Into<String>,
7524        update_name: impl Into<String>,
7525        handler: F,
7526    ) where
7527        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
7528        Fut: Future<Output = Result<Value>> + Send + 'static,
7529    {
7530        let workflow_type = workflow_type.into();
7531        let update_name = update_name.into();
7532        if !self.admit_registration::<F>(
7533            RegistrationKind::Update,
7534            Some(&workflow_type),
7535            &update_name,
7536            "register_update",
7537        ) {
7538            return;
7539        }
7540        let handler = Arc::new(handler);
7541        self.updates.entry(workflow_type).or_default().insert(
7542            update_name,
7543            Arc::new(move |ctx, args| {
7544                let handler = Arc::clone(&handler);
7545                Box::pin(async move {
7546                    let result = handler(ctx, args.into_json()?).await?;
7547                    AvroValue::from_serialize(&result)
7548                })
7549            }),
7550        );
7551    }
7552
7553    /// Register an update handler on the lossless fixed Avro Value surface.
7554    #[track_caller]
7555    pub fn register_update_avro_value<F, Fut>(
7556        &mut self,
7557        workflow_type: impl Into<String>,
7558        update_name: impl Into<String>,
7559        handler: F,
7560    ) where
7561        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
7562        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7563    {
7564        let workflow_type = workflow_type.into();
7565        let update_name = update_name.into();
7566        if !self.admit_registration::<F>(
7567            RegistrationKind::Update,
7568            Some(&workflow_type),
7569            &update_name,
7570            "register_update_avro_value",
7571        ) {
7572            return;
7573        }
7574        self.updates.entry(workflow_type).or_default().insert(
7575            update_name,
7576            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
7577        );
7578    }
7579
7580    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
7581        self.validate_registration()?;
7582        self.sticky_registration_confirmed
7583            .store(false, Ordering::SeqCst);
7584        self.session_registration_confirmed
7585            .store(false, Ordering::SeqCst);
7586        for capability in &self.resource_capabilities {
7587            worker_session::validate_resource_capability(capability)?;
7588        }
7589        self.local_registration_confirmed
7590            .store(false, Ordering::SeqCst);
7591        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
7592            return Err(Error::CooperativeCancellationUnavailable(
7593                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
7594            ));
7595        }
7596        let mut command_contracts = serde_json::Map::new();
7597        for workflow_type in self.workflows.keys() {
7598            let mut queries = self
7599                .queries
7600                .get(workflow_type)
7601                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7602                .unwrap_or_default();
7603            queries.sort();
7604            let mut updates = self
7605                .updates
7606                .get(workflow_type)
7607                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
7608                .unwrap_or_default();
7609            updates.sort();
7610            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
7611            command_contracts.insert(
7612                workflow_type.clone(),
7613                json!({
7614                    "queries": queries,
7615                    "query_contracts": argument_vector_contracts(&queries),
7616                    "signals": signals,
7617                    "signal_contracts": argument_vector_contracts(&signals),
7618                    "updates": updates,
7619                    "update_contracts": argument_vector_contracts(&updates),
7620                    "update_validators": [],
7621                }),
7622            );
7623        }
7624
7625        self.cooperative_registration_confirmed
7626            .store(false, Ordering::SeqCst);
7627        let response = self
7628            .client
7629            .register_worker_with_definition_fingerprints(
7630                &self.worker_id,
7631                &self.task_queue,
7632                self.workflows.keys().cloned().collect(),
7633                self.activities.keys().cloned().collect(),
7634                self.max_concurrent_workflow_tasks,
7635                self.max_concurrent_activity_tasks,
7636                [
7637                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
7638                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
7639                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
7640                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
7641                    self.client
7642                        .local_activities_enabled
7643                        .then(|| "local_activities".to_string()),
7644                    self.client
7645                        .worker_sessions_enabled
7646                        .then(|| "worker_sessions".to_string()),
7647                    self.client
7648                        .sticky_cache
7649                        .is_some()
7650                        .then(|| "sticky_execution".to_string()),
7651                    self.cooperative_cancellation_enabled
7652                        .then(|| "cooperative_cancellation".to_string()),
7653                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
7654                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
7655                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
7656                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
7657                ]
7658                .into_iter()
7659                .flatten()
7660                .chain(self.resource_capabilities.iter().cloned())
7661                .collect(),
7662                Value::Object(command_contracts),
7663                Some(
7664                    self.workflows
7665                        .iter()
7666                        .filter_map(|(workflow_type, workflow)| {
7667                            workflow
7668                                .definition_fingerprint
7669                                .as_ref()
7670                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
7671                        })
7672                        .collect(),
7673                ),
7674            )
7675            .await?;
7676        if self.cooperative_cancellation_enabled && response.registered {
7677            self.cooperative_registration_confirmed
7678                .store(true, Ordering::SeqCst);
7679        }
7680        if self.client.local_activities_enabled && response.registered {
7681            self.local_registration_confirmed
7682                .store(true, Ordering::SeqCst);
7683        }
7684        if self.client.worker_sessions_enabled && response.registered {
7685            self.session_registration_confirmed
7686                .store(true, Ordering::SeqCst);
7687        }
7688        if self.client.sticky_cache.is_some() && response.registered {
7689            self.sticky_registration_confirmed
7690                .store(true, Ordering::SeqCst);
7691        }
7692        Ok(response)
7693    }
7694
7695    /// Run until shutdown or a terminal worker error occurs.
7696    ///
7697    /// Empty long-poll expirations do not stop the worker. Retryable poll and
7698    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
7699    /// authentication, protocol, and other non-retryable failures are returned.
7700    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
7701    /// poll and heartbeat outages beyond the ordinary retry budget.
7702    pub async fn run(&self) -> Result<()> {
7703        self.run_until(std::future::pending::<()>()).await
7704    }
7705
7706    /// Run until `shutdown` resolves or a terminal worker error occurs.
7707    ///
7708    /// This has the same liveness and terminal-error contract as [`Worker::run`].
7709    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
7710    where
7711        F: Future<Output = ()>,
7712    {
7713        let _clear_cache_on_drop =
7714            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
7715        let stop = Arc::new(AtomicBool::new(false));
7716        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
7717        let mut worker = self.with_storage_admission(Arc::clone(&stop));
7718        worker.run_stop = Some(Arc::clone(&stop));
7719        let run = worker.run_with_storage_admission(Arc::clone(&stop));
7720        tokio::pin!(run);
7721        tokio::pin!(shutdown);
7722        tokio::select! {
7723            result = &mut run => result,
7724            _ = &mut shutdown => {
7725                stop.store(true, Ordering::SeqCst);
7726                run.await
7727            }
7728        }
7729    }
7730
7731    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
7732        let mut worker = self.clone();
7733        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
7734            policy: self.retry_policy,
7735            stop,
7736        });
7737        worker
7738    }
7739
7740    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
7741        let registration = self.register().await?;
7742        if !registration.registered {
7743            return Err(Error::WorkerLoop(format!(
7744                "worker registration for {:?} was not accepted",
7745                self.worker_id
7746            )));
7747        }
7748        let registered_worker_id = registration.worker_id.clone();
7749        let primary = self.run_registered_until(stop, registration).await;
7750        let primary = match (primary, self.close_worker_sessions().await) {
7751            (Ok(()), result) => result,
7752            (Err(error), Ok(())) => Err(error),
7753            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
7754                primary: Box::new(primary),
7755                deregistration: Box::new(close),
7756            }),
7757        };
7758        self.session_registration_confirmed
7759            .store(false, Ordering::SeqCst);
7760        self.cooperative_registration_confirmed
7761            .store(false, Ordering::SeqCst);
7762        self.local_registration_confirmed
7763            .store(false, Ordering::SeqCst);
7764        let deregistration = self
7765            .client
7766            .deregister_worker_registration(&registered_worker_id)
7767            .await;
7768        self.sticky_registration_confirmed
7769            .store(false, Ordering::SeqCst);
7770        self.client.clear_sticky_cache()?;
7771
7772        match (primary, deregistration) {
7773            (Ok(()), Ok(_)) => Ok(()),
7774            (Ok(()), Err(deregistration)) => Err(deregistration),
7775            (Err(primary), Ok(_)) => Err(primary),
7776            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
7777                primary: Box::new(primary),
7778                deregistration: Box::new(deregistration),
7779            }),
7780        }
7781    }
7782
7783    async fn run_registered_until(
7784        &self,
7785        stop: Arc<AtomicBool>,
7786        registration: RegisterWorkerResponse,
7787    ) -> Result<()> {
7788        let heartbeat_interval = Duration::from_secs(
7789            registration
7790                .heartbeat_interval_seconds
7791                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
7792        );
7793        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
7794        // from the completion of the preceding attempt, including its bounded
7795        // retries. A fixed-epoch interval can leave an already-due tick queued
7796        // while an acknowledgement is slow, producing a catch-up heartbeat as
7797        // soon as that request completes.
7798        let heartbeat = tokio::time::sleep(Duration::ZERO);
7799        tokio::pin!(heartbeat);
7800        // Poll responses may already have leased server-side work by the time
7801        // they become ready, so each poller owns its responses through
7802        // completion or failure instead of racing raw polls in this select.
7803        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
7804            let worker = self.clone();
7805            let stop = Arc::clone(&stop);
7806            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
7807        });
7808        let mut activity_poller = (!self.activities.is_empty()).then(|| {
7809            let worker = self.clone();
7810            let stop = Arc::clone(&stop);
7811            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
7812        });
7813        let mut query_poller = (!self.queries.is_empty()).then(|| {
7814            let worker = self.clone();
7815            let stop = Arc::clone(&stop);
7816            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
7817        });
7818
7819        loop {
7820            tokio::select! {
7821                _ = wait_for_worker_stop(&stop) => {
7822                    stop.store(true, Ordering::SeqCst);
7823                    break;
7824                }
7825                _ = &mut heartbeat => {
7826                    let result = self.retry_worker_operation(|| {
7827                        self.client.heartbeat_worker_with_sessions(
7828                            &self.worker_id,
7829                            self.max_concurrent_workflow_tasks,
7830                            self.max_concurrent_activity_tasks,
7831                            self.client.worker_sessions_enabled.then(|| self.session_available()),
7832                        )
7833                    }).await;
7834                    heartbeat
7835                        .as_mut()
7836                        .reset(tokio::time::Instant::now() + heartbeat_interval);
7837                    match result {
7838                        Ok(Some(acknowledgement)) => {
7839                            if let Some(observer) = &self.heartbeat_observer {
7840                                observer(&WorkerHeartbeatObservation {
7841                                    worker_id: self.worker_id.clone(),
7842                                    task_queue: self.task_queue.clone(),
7843                                    acknowledged_at_unix_millis: SystemTime::now()
7844                                        .duration_since(UNIX_EPOCH)
7845                                        .unwrap_or_default()
7846                                        .as_millis()
7847                                        .min(u64::MAX as u128)
7848                                        as u64,
7849                                    acknowledgement,
7850                                });
7851                            }
7852                        }
7853                        Ok(None) => break,
7854                        Err(error) => {
7855                            stop.store(true, Ordering::SeqCst);
7856                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
7857                            return Err(error);
7858                        }
7859                    }
7860                }
7861                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
7862                    workflow_poller = None;
7863                    let stopped_by_server = stop.load(Ordering::SeqCst);
7864                    stop.store(true, Ordering::SeqCst);
7865                    let poller_result = optional_poller_result("workflow", 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                        "workflow poller stopped unexpectedly".to_string(),
7875                    ));
7876                }
7877                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
7878                    activity_poller = None;
7879                    let stopped_by_server = stop.load(Ordering::SeqCst);
7880                    stop.store(true, Ordering::SeqCst);
7881                    let poller_result = optional_poller_result("activity", 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                        "activity poller stopped unexpectedly".to_string(),
7891                    ));
7892                }
7893                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
7894                    query_poller = None;
7895                    let stopped_by_server = stop.load(Ordering::SeqCst);
7896                    stop.store(true, Ordering::SeqCst);
7897                    let poller_result = optional_poller_result("query", result);
7898                    let join_result =
7899                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
7900                    poller_result?;
7901                    join_result?;
7902                    if stopped_by_server {
7903                        return Ok(());
7904                    }
7905                    return Err(Error::WorkerLoop(
7906                        "query poller stopped unexpectedly".to_string(),
7907                    ));
7908                }
7909            }
7910        }
7911
7912        join_pollers(
7913            workflow_poller.take(),
7914            activity_poller.take(),
7915            query_poller.take(),
7916        )
7917        .await
7918    }
7919
7920    /// Poll and settle at most one task from each enabled task family.
7921    ///
7922    /// A workflow may reach its server-enforced run deadline while this worker
7923    /// holds a task. When the completion endpoint authoritatively rejects that
7924    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
7925    /// terminal `run_status=failed`, the workflow tick is considered settled:
7926    /// the late command was not recorded and cannot replace the terminal run.
7927    /// Every other completion rejection remains an error. This worker-level
7928    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
7929    /// only bounds how long a client waits for a result.
7930    ///
7931    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
7932    /// the original [`Error::Http`] status and response body.
7933    pub async fn run_once(&self) -> Result<usize> {
7934        self.validate_registration()?;
7935        if self.client.worker_sessions_enabled {
7936            self.require_session_registration()?;
7937        }
7938        if self.cooperative_cancellation_enabled
7939            && !self
7940                .cooperative_registration_confirmed
7941                .load(Ordering::SeqCst)
7942        {
7943            return Err(Error::CooperativeCancellationUnavailable(
7944                "register this cooperative worker before polling tasks".into(),
7945            ));
7946        }
7947        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
7948        let mut handled = 0;
7949        match worker.poll_workflow_once().await? {
7950            ManagedPollOutcome::Handled => handled += 1,
7951            ManagedPollOutcome::Stop => return Ok(handled),
7952            ManagedPollOutcome::Idle => {}
7953        }
7954        match worker.poll_activity_once().await? {
7955            ManagedPollOutcome::Handled => handled += 1,
7956            ManagedPollOutcome::Stop => return Ok(handled),
7957            ManagedPollOutcome::Idle => {}
7958        }
7959        if !self.queries.is_empty() {
7960            match worker.poll_query_once().await? {
7961                ManagedPollOutcome::Handled => handled += 1,
7962                ManagedPollOutcome::Stop => return Ok(handled),
7963                ManagedPollOutcome::Idle => {}
7964            }
7965        }
7966        Ok(handled)
7967    }
7968
7969    async fn poll_workflow_once(&self) -> Result<ManagedPollOutcome> {
7970        if self.client.sticky_cache.is_some()
7971            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
7972        {
7973            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
7974        }
7975        if self.client.local_activities_enabled
7976            && !self.local_registration_confirmed.load(Ordering::SeqCst)
7977        {
7978            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
7979        }
7980        if self.cooperative_cancellation_enabled {
7981            return self.poll_cooperative_workflow_once().await;
7982        }
7983        let poll_request_id = unique_request_id("rust-workflow-poll");
7984        let response = self
7985            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
7986            .await;
7987        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
7988            return Ok(ManagedPollOutcome::Idle);
7989        };
7990        if response.outcome().should_stop() {
7991            return Ok(ManagedPollOutcome::Stop);
7992        }
7993        let memo_updates_supported =
7994            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
7995        let Some(task) = response.task else {
7996            return Ok(ManagedPollOutcome::Idle);
7997        };
7998
7999        let task_id = task.task_id.clone();
8000        let attempt = task.workflow_task_attempt;
8001        let run_id = task.run_id.clone();
8002        let lease_owner = task
8003            .lease_owner
8004            .clone()
8005            .unwrap_or_else(|| self.worker_id.clone());
8006
8007        let decision = match self.execute_workflow_with_local_activities(task).await {
8008            Ok(Some(decision)) => Ok(decision),
8009            Ok(None) => return Ok(ManagedPollOutcome::Handled),
8010            Err(error) => Err(error),
8011        };
8012        self.settle_workflow_task_decision(
8013            &task_id,
8014            &lease_owner,
8015            attempt,
8016            run_id.as_deref(),
8017            decision,
8018            memo_updates_supported,
8019            snapshot,
8020        )
8021        .await
8022    }
8023
8024    #[allow(clippy::too_many_arguments)]
8025    async fn settle_workflow_task_decision(
8026        &self,
8027        task_id: &str,
8028        lease_owner: &str,
8029        attempt: u64,
8030        run_id: Option<&str>,
8031        decision: Result<WorkflowTaskDecision>,
8032        memo_updates_supported: bool,
8033        snapshot: Option<sticky_worker::StickySnapshot>,
8034    ) -> Result<ManagedPollOutcome> {
8035        match decision {
8036            Ok(decision)
8037                if decision.cancellation_delivery.is_some()
8038                    || decision.cancellation_scope_delivery.is_some()
8039                    || decision.cancellation_scope_opening.is_some() =>
8040            {
8041                return Err(Error::CooperativeCancellationUnavailable(
8042                    "worker cancellation delivery has not been negotiated".into(),
8043                ));
8044            }
8045            Ok(decision)
8046                if commands_use_workflow_memo_updates(&decision.commands)
8047                    && !memo_updates_supported =>
8048            {
8049                self.client
8050                    .fail_workflow_task(
8051                        task_id,
8052                        lease_owner,
8053                        attempt,
8054                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8055                    )
8056                    .await?;
8057            }
8058            Ok(decision) if decision.commands.is_empty() => {
8059                // A replay can consume a recorded pending durable command
8060                // without producing a new command. The standalone protocol
8061                // acknowledges that state through the typed waiting outcome;
8062                // an empty completion is rejected by servers that require at
8063                // least one executable command.
8064                self.client
8065                    .fail_workflow_task_with_type(
8066                        task_id,
8067                        lease_owner,
8068                        attempt,
8069                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8070                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8071                    )
8072                    .await?;
8073            }
8074            Ok(decision) => {
8075                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8076                let completion = self
8077                    .client
8078                    .complete_workflow_task_with_message_streams(
8079                        task_id,
8080                        lease_owner,
8081                        attempt,
8082                        decision.commands,
8083                        decision.message_stream_cursors,
8084                        decision.message_stream_waits,
8085                        sticky_claim,
8086                    )
8087                    .await;
8088                if let Err(error) = completion {
8089                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8090                    if !workflow_task_completion_is_terminal_timeout(
8091                        &error, task_id, attempt, run_id,
8092                    ) {
8093                        return Err(error);
8094                    }
8095                }
8096            }
8097            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8098            Err(error) => {
8099                self.discard_sticky_snapshot(snapshot.as_ref())?;
8100                self.client
8101                    .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8102                    .await?;
8103            }
8104        }
8105
8106        Ok(ManagedPollOutcome::Handled)
8107    }
8108
8109    async fn poll_workflows_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8110        while !stop.load(Ordering::SeqCst) {
8111            match self.poll_workflow_once().await {
8112                Ok(ManagedPollOutcome::Stop) => {
8113                    stop.store(true, Ordering::SeqCst);
8114                    break;
8115                }
8116                Err(error) => {
8117                    stop.store(true, Ordering::SeqCst);
8118                    return Err(error);
8119                }
8120                _ => {}
8121            }
8122        }
8123
8124        Ok(())
8125    }
8126
8127    async fn poll_activity_once(&self) -> Result<ManagedPollOutcome> {
8128        if self.client.worker_sessions_enabled {
8129            self.require_session_registration()?;
8130        }
8131        if self.cooperative_cancellation_enabled {
8132            return self.poll_cooperative_activity_once().await;
8133        }
8134        let poll_request_id = unique_request_id("rust-activity-poll");
8135        let response = self
8136            .retry_worker_operation(|| {
8137                self.client.poll_activity_task_response_with_request_id(
8138                    &self.worker_id,
8139                    &self.task_queue,
8140                    self.poll_timeout,
8141                    &poll_request_id,
8142                    0,
8143                )
8144            })
8145            .await;
8146        let response = match response {
8147            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8148            response => response,
8149        };
8150        let Some(response) = self.settle_worker_poll_response(response).await? else {
8151            return Ok(ManagedPollOutcome::Idle);
8152        };
8153        if response.outcome().should_stop() {
8154            return Ok(ManagedPollOutcome::Stop);
8155        }
8156        let Some(task) = response.task else {
8157            return Ok(ManagedPollOutcome::Idle);
8158        };
8159
8160        let session = self.track_session_task(task.worker_session.as_ref())?;
8161        let hydration_claim = task.hydration_claim;
8162        let task = task.task;
8163
8164        let task_id = task.task_id.clone();
8165        let attempt_id = task
8166            .activity_attempt_id
8167            .clone()
8168            .or(task.attempt_id.clone())
8169            .unwrap_or_default();
8170        let lease_owner = task
8171            .lease_owner
8172            .clone()
8173            .unwrap_or_else(|| self.worker_id.clone());
8174        let codec = task.payload_codec.clone();
8175        let result = self
8176            .execute_session_activity_task(task, session, hydration_claim.as_ref())
8177            .await;
8178        match result {
8179            Err(Error::ActivityExecutionAbandoned(_)) => {}
8180            Err(error) if activity_hydration::stopped(&error) => {}
8181            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
8182            Ok(value) => {
8183                let completion = self
8184                    .client
8185                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
8186                    .await;
8187                if let Err(error) = completion {
8188                    if !activity_task_rejection_is_final(&error) {
8189                        return Err(error);
8190                    }
8191                }
8192            }
8193            Err(error) => {
8194                let failure = self
8195                    .client
8196                    .fail_activity_task(
8197                        &task_id,
8198                        &attempt_id,
8199                        &lease_owner,
8200                        error.to_string(),
8201                        false,
8202                    )
8203                    .await;
8204                if let Err(error) = failure {
8205                    if !activity_task_rejection_is_final(&error) {
8206                        return Err(error);
8207                    }
8208                }
8209            }
8210        }
8211
8212        Ok(ManagedPollOutcome::Handled)
8213    }
8214
8215    async fn poll_activities_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8216        // Each lane retains its leased response through callback settlement.
8217        // A bounded independent activity must not occupy the cleanup lane too.
8218        // Preserve the existing serial loop unless cooperation is enabled.
8219        let lane_count = if self.cooperative_cancellation_enabled {
8220            self.max_concurrent_activity_tasks
8221        } else {
8222            1
8223        };
8224        let mut lanes = FuturesUnordered::new();
8225        for _ in 0..lane_count {
8226            let worker = self.clone();
8227            let stop = Arc::clone(&stop);
8228            lanes.push(async move {
8229                while !stop.load(Ordering::SeqCst) {
8230                    match worker.poll_activity_once().await {
8231                        Ok(ManagedPollOutcome::Stop) => {
8232                            stop.store(true, Ordering::SeqCst);
8233                            break;
8234                        }
8235                        Err(error) => {
8236                            stop.store(true, Ordering::SeqCst);
8237                            return Err(error);
8238                        }
8239                        _ => {}
8240                    }
8241                }
8242                Ok(())
8243            });
8244        }
8245        // Join every lane before deregistration, including after one fails.
8246        let mut first_error = None;
8247        while let Some(result) = lanes.next().await {
8248            if let Err(error) = result {
8249                first_error.get_or_insert(error);
8250            }
8251        }
8252        first_error.map_or(Ok(()), Err)
8253    }
8254
8255    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
8256        let poll_request_id = unique_request_id("rust-query-poll");
8257        let response = self
8258            .retry_worker_operation(|| {
8259                self.client.poll_query_task_response_with_request_id(
8260                    &self.worker_id,
8261                    &self.task_queue,
8262                    self.poll_timeout,
8263                    &poll_request_id,
8264                    0,
8265                )
8266            })
8267            .await;
8268        let Some(response) = self.settle_worker_poll_response(response).await? else {
8269            return Ok(ManagedPollOutcome::Idle);
8270        };
8271        if response.outcome().should_stop() {
8272            return Ok(ManagedPollOutcome::Stop);
8273        }
8274        let Some(task) = response.task else {
8275            return Ok(ManagedPollOutcome::Idle);
8276        };
8277
8278        let query_task_id = task.query_task_id.clone();
8279        let attempt = task.query_task_attempt;
8280        let lease_owner = task
8281            .lease_owner
8282            .clone()
8283            .unwrap_or_else(|| self.worker_id.clone());
8284        let codec = task.payload_codec.clone();
8285
8286        match self.execute_query_task(task).await {
8287            Ok(value) => {
8288                let result_envelope = match encode_typed_envelope(&value, &codec) {
8289                    Ok(result_envelope) => result_envelope,
8290                    Err(error) => {
8291                        let failure = self
8292                            .client
8293                            .fail_query_task(
8294                                &query_task_id,
8295                                &lease_owner,
8296                                attempt,
8297                                error.to_string(),
8298                                "query_result_encode_failed",
8299                                "QueryResultEncodeFailed",
8300                            )
8301                            .await;
8302                        if let Err(error) = failure {
8303                            if !query_task_rejection_is_final(&error) {
8304                                return Err(error);
8305                            }
8306                        }
8307                        return Ok(ManagedPollOutcome::Handled);
8308                    }
8309                };
8310
8311                if let Err(error) = self
8312                    .client
8313                    .complete_query_task_with_envelope(
8314                        &query_task_id,
8315                        &lease_owner,
8316                        attempt,
8317                        value.clone().into_json()?,
8318                        result_envelope,
8319                    )
8320                    .await
8321                {
8322                    if !query_task_rejection_is_final(&error) {
8323                        return Err(error);
8324                    }
8325                }
8326            }
8327            Err(failure) => {
8328                let result = self
8329                    .client
8330                    .fail_query_task(
8331                        &query_task_id,
8332                        &lease_owner,
8333                        attempt,
8334                        failure.message,
8335                        failure.reason,
8336                        failure.failure_type,
8337                    )
8338                    .await;
8339                if let Err(error) = result {
8340                    if !query_task_rejection_is_final(&error) {
8341                        return Err(error);
8342                    }
8343                }
8344            }
8345        }
8346
8347        Ok(ManagedPollOutcome::Handled)
8348    }
8349
8350    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
8351        while !stop.load(Ordering::SeqCst) {
8352            match self.poll_query_once().await {
8353                Ok(ManagedPollOutcome::Stop) => {
8354                    stop.store(true, Ordering::SeqCst);
8355                    break;
8356                }
8357                Err(error) => {
8358                    stop.store(true, Ordering::SeqCst);
8359                    return Err(error);
8360                }
8361                _ => {}
8362            }
8363        }
8364
8365        Ok(())
8366    }
8367
8368    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
8369    where
8370        F: FnMut() -> Fut,
8371        Fut: Future<Output = Result<T>>,
8372    {
8373        let mut retries = 0;
8374
8375        loop {
8376            if self
8377                .run_stop
8378                .as_ref()
8379                .is_some_and(|stop| stop.load(Ordering::SeqCst))
8380            {
8381                return Ok(None);
8382            }
8383            match operation().await {
8384                Err(error)
8385                    if (workflow_hydration::stopped(&error)
8386                        || activity_hydration::stopped(&error))
8387                        && self
8388                            .run_stop
8389                            .as_ref()
8390                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
8391                {
8392                    return Ok(None);
8393                }
8394                Err(error)
8395                    if worker_operation_is_retryable(&error)
8396                        && (retries < self.retry_policy.max_retries
8397                            || (self.recover_transient_outages
8398                                && self.run_stop.is_some()
8399                                && self.retry_policy.max_retries > 0)) =>
8400                {
8401                    retries = retries.saturating_add(1);
8402                    let delay = worker_retry_delay(self.retry_policy, retries)
8403                        .max(Duration::from_millis(1));
8404                    if let Some(stop) = &self.run_stop {
8405                        tokio::select! {
8406                            _ = tokio::time::sleep(delay) => {}
8407                            _ = wait_for_worker_stop(stop) => return Ok(None),
8408                        }
8409                    } else {
8410                        tokio::time::sleep(delay).await;
8411                    }
8412                }
8413                result => return result.map(Some),
8414            }
8415        }
8416    }
8417
8418    async fn settle_worker_poll_response<T>(
8419        &self,
8420        response: Result<Option<T>>,
8421    ) -> Result<Option<T>> {
8422        match response {
8423            Ok(response) => Ok(response),
8424            Err(error) => {
8425                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
8426                    return Err(error);
8427                };
8428                let minimum_delay = self
8429                    .retry_policy
8430                    .initial_backoff
8431                    .max(Duration::from_millis(1));
8432                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
8433                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
8434                Ok(None)
8435            }
8436        }
8437    }
8438
8439    async fn execute_query_task(
8440        &self,
8441        mut task: QueryTask,
8442    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
8443        validate_query_task_payloads(&task).map_err(|error| {
8444            QueryTaskExecutionFailure::new(
8445                "query_payload_decode_failed",
8446                error.to_string(),
8447                "QueryPayloadDecodeFailed",
8448            )
8449        })?;
8450
8451        if !self.workflows.contains_key(&task.workflow_type) {
8452            return Err(QueryTaskExecutionFailure::new(
8453                "query_workflow_type_not_registered",
8454                format!("no workflow registered for type {:?}", task.workflow_type),
8455                "WorkflowTypeNotRegistered",
8456            ));
8457        }
8458
8459        let Some(handlers) = self.queries.get(&task.workflow_type) else {
8460            return Err(QueryTaskExecutionFailure::new(
8461                "query_handler_unavailable",
8462                format!(
8463                    "query handlers are unavailable for workflow type {:?}",
8464                    task.workflow_type
8465                ),
8466                "QueryHandlerUnavailable",
8467            ));
8468        };
8469        let Some(query) = handlers.get(&task.query_name) else {
8470            return Err(QueryTaskExecutionFailure::new(
8471                "rejected_unknown_query",
8472                format!("unknown query {:?}", task.query_name),
8473                "QueryFailed",
8474            ));
8475        };
8476
8477        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
8478            .map_err(|error| {
8479            QueryTaskExecutionFailure::new(
8480                "query_payload_decode_failed",
8481                format!("cannot decode query arguments: {error}"),
8482                "QueryPayloadDecodeFailed",
8483            )
8484        })?;
8485        let workflow_input_typed =
8486            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
8487                .map_err(|error| {
8488                    QueryTaskExecutionFailure::new(
8489                        "query_workflow_state_unavailable",
8490                        format!("cannot decode workflow start input: {error}"),
8491                        "QueryWorkflowStateUnavailable",
8492                    )
8493                })?;
8494        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
8495            QueryTaskExecutionFailure::new(
8496                "query_workflow_state_unavailable",
8497                format!("cannot project workflow start input: {error}"),
8498                "QueryWorkflowStateUnavailable",
8499            )
8500        })?;
8501        hydrate_query_history_from_export(&mut task).map_err(|error| {
8502            QueryTaskExecutionFailure::new(
8503                "query_workflow_state_unavailable",
8504                format!("cannot restore query history snapshot: {error}"),
8505                "QueryWorkflowStateUnavailable",
8506            )
8507        })?;
8508        enrich_query_history_from_export(&mut task).map_err(|error| {
8509            QueryTaskExecutionFailure::new(
8510                "query_workflow_state_unavailable",
8511                format!("cannot restore compact query history payloads: {error}"),
8512                "QueryWorkflowStateUnavailable",
8513            )
8514        })?;
8515        let signal_events = query_signal_events(&task).map_err(|error| {
8516            QueryTaskExecutionFailure::new(
8517                "query_workflow_state_unavailable",
8518                format!("cannot decode committed workflow signals: {error}"),
8519                "QueryWorkflowStateUnavailable",
8520            )
8521        })?;
8522        let history_events = Arc::new(std::mem::take(&mut task.history_events));
8523        let context = QueryContext {
8524            workflow_id: task.workflow_id,
8525            run_id: task.run_id,
8526            workflow_type: task.workflow_type.clone(),
8527            run_status: task.run_status,
8528            workflow_input,
8529            workflow_input_avro_value: workflow_input_typed.clone(),
8530            history_events: Arc::clone(&history_events),
8531            signal_events: Arc::new(signal_events),
8532        };
8533
8534        let future = match query {
8535            RegisteredQuery::Snapshot(handler) => handler(context, args),
8536            RegisteredQuery::Replayed {
8537                state_type,
8538                handler,
8539            } => {
8540                let workflow = self
8541                    .workflows
8542                    .get(&task.workflow_type)
8543                    .expect("workflow registration was checked above");
8544                if workflow.state_type != Some(*state_type) {
8545                    return Err(QueryTaskExecutionFailure::new(
8546                        "query_workflow_state_unavailable",
8547                        "replayed query state type does not match its workflow registration",
8548                        "QueryWorkflowStateUnavailable",
8549                    ));
8550                }
8551                let replay = workflow.replay.as_ref().ok_or_else(|| {
8552                    QueryTaskExecutionFailure::new(
8553                        "query_workflow_state_unavailable",
8554                        format!(
8555                            "workflow type {:?} is not registered for instance-state replay",
8556                            task.workflow_type
8557                        ),
8558                        "QueryWorkflowStateUnavailable",
8559                    )
8560                })?;
8561                let workflow_state = Arc::new(Mutex::new(
8562                    WorkflowState::new_with_identity(
8563                        history_events.as_ref().clone(),
8564                        context.workflow_id.clone(),
8565                        context.run_id.clone(),
8566                        self.task_queue.clone(),
8567                        task.payload_codec,
8568                        None,
8569                    )
8570                    .map_err(|error| {
8571                        QueryTaskExecutionFailure::new(
8572                            "query_workflow_state_unavailable",
8573                            format!("workflow replay failed before query: {error}"),
8574                            "QueryWorkflowStateUnavailable",
8575                        )
8576                    })?,
8577                ));
8578                let workflow_context = WorkflowContext {
8579                    state: workflow_state,
8580                    cancellation_scope_id: "root".into(),
8581                };
8582                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone());
8583                let mut cx = TaskContext::from_waker(noop_waker_ref());
8584                let outcome = {
8585                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
8586                        .map_err(|error| {
8587                            QueryTaskExecutionFailure::new(
8588                                "query_workflow_state_unavailable",
8589                                error.to_string(),
8590                                "QueryWorkflowStateUnavailable",
8591                            )
8592                        })?;
8593                    invocation.future.as_mut().poll(&mut cx)
8594                };
8595                match outcome {
8596                    Poll::Ready(Ok(_)) => {
8597                        workflow_context
8598                            .ensure_history_consumed()
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                    Poll::Ready(Err(error)) => {
8608                        return Err(QueryTaskExecutionFailure::new(
8609                            "query_workflow_state_unavailable",
8610                            format!("workflow replay failed before query: {error}"),
8611                            "QueryWorkflowStateUnavailable",
8612                        ));
8613                    }
8614                    Poll::Pending => {
8615                        let commands = workflow_context.take_commands().map_err(|error| {
8616                            QueryTaskExecutionFailure::new(
8617                                "query_workflow_state_unavailable",
8618                                format!("workflow replay failed before query: {error}"),
8619                                "QueryWorkflowStateUnavailable",
8620                            )
8621                        })?;
8622                        if commands.is_empty()
8623                            && !workflow_context
8624                                .matched_recorded_pending()
8625                                .map_err(|error| {
8626                                    QueryTaskExecutionFailure::new(
8627                                        "query_workflow_state_unavailable",
8628                                        format!("workflow replay failed before query: {error}"),
8629                                        "QueryWorkflowStateUnavailable",
8630                                    )
8631                                })?
8632                        {
8633                            return Err(QueryTaskExecutionFailure::new(
8634                                "query_workflow_state_unavailable",
8635                                "workflow replay yielded without a durable command",
8636                                "QueryWorkflowStateUnavailable",
8637                            ));
8638                        }
8639                    }
8640                }
8641                let state = (invocation.snapshot)().map_err(|error| {
8642                    QueryTaskExecutionFailure::new(
8643                        "query_workflow_state_unavailable",
8644                        format!("cannot snapshot replayed workflow state: {error}"),
8645                        "QueryWorkflowStateUnavailable",
8646                    )
8647                })?;
8648                handler(context, state, args).map_err(|message| {
8649                    QueryTaskExecutionFailure::new(
8650                        "query_workflow_state_unavailable",
8651                        message,
8652                        "QueryWorkflowStateUnavailable",
8653                    )
8654                })?
8655            }
8656        };
8657
8658        future.await.map_err(|error| {
8659            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
8660        })
8661    }
8662
8663    #[cfg(test)]
8664    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
8665        Ok(self.execute_workflow_task_decision(task)?.commands)
8666    }
8667
8668    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
8669        self.execute_workflow_task_decision_with_cancellation(task, None)
8670    }
8671
8672    fn execute_workflow_task_decision_with_cancellation(
8673        &self,
8674        task: WorkflowTask,
8675        observation: Option<&CancellationRequest>,
8676    ) -> Result<WorkflowTaskDecision> {
8677        match self.prepare_workflow_task_execution(task, observation)? {
8678            PreparedWorkflowTask::Decision(decision) => Ok(decision),
8679            PreparedWorkflowTask::Execution {
8680                task,
8681                context,
8682                mut future,
8683            } => {
8684                let outcome = Self::poll_workflow_future(&context, &mut future)?;
8685                self.finish_workflow_task_execution(&task, &context, outcome)
8686            }
8687        }
8688    }
8689
8690    fn prepare_workflow_task_execution(
8691        &self,
8692        task: WorkflowTask,
8693        observation: Option<&CancellationRequest>,
8694    ) -> Result<PreparedWorkflowTask> {
8695        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
8696            && !self.cooperative_cancellation_enabled
8697        {
8698            return Err(Error::CancellationScopeExecutionUnavailable);
8699        }
8700        validate_workflow_task_payloads(&task)?;
8701        cooperative_cancellation::assert_cancellation_scope_replay_supported(
8702            &task.history_events,
8703            self.allow_cancellation_scope_authoring,
8704            self.allow_cancellation_scope_delivery,
8705        )?;
8706        let cancellation_history = if let Some(observation) = observation {
8707            observation.validate_observation()?;
8708            cooperative_cancellation::cancellation_claim(&task)?;
8709            let canonical = CancellationHistory::from_events(
8710                &task.history_events,
8711                task.run_id.as_deref().unwrap_or_default(),
8712                Some(observation),
8713            )?;
8714            if canonical.request_index >= task.history_events.len() {
8715                return Err(Error::InvalidCooperativeCancellation(
8716                    "workflow replay requires the observed canonical request".into(),
8717                ));
8718            }
8719            Some(canonical)
8720        } else {
8721            None
8722        };
8723        if let Some(update_id) = task
8724            .workflow_update_id
8725            .as_deref()
8726            .filter(|update_id| !update_id.is_empty())
8727        {
8728            if self.allow_cancellation_scope_delivery {
8729                return Err(Error::CancellationScopeExecutionUnavailable);
8730            }
8731            CancellationHistory::from_events(
8732                &task.history_events,
8733                task.run_id.as_deref().unwrap_or_default(),
8734                None,
8735            )?;
8736            return self
8737                .execute_update_task(&task, update_id)
8738                .map(WorkflowTaskDecision::without_message_streams)
8739                .map(PreparedWorkflowTask::Decision);
8740        }
8741
8742        let workflow = self
8743            .workflows
8744            .get(&task.workflow_type)
8745            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
8746        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
8747        let resume_signal = decode_resume_signal(&task)?;
8748        let history_budget = WorkflowHistoryBudget {
8749            event_count: task
8750                .total_history_events
8751                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
8752            size_bytes: task.history_size_bytes,
8753            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
8754            pressure: task.history_budget_pressure.clone(),
8755        };
8756        let workflow_command_identity = task
8757            .workflow_command_id
8758            .clone()
8759            .filter(|identity| !identity.is_empty())
8760            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
8761            .unwrap_or_default();
8762        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
8763            task.history_events.clone(),
8764            task.workflow_id.clone(),
8765            task.run_id.clone(),
8766            self.task_queue.clone(),
8767            task.payload_codec.clone(),
8768            resume_signal,
8769            self.allow_cancellation_scope_authoring,
8770            self.allow_cancellation_scope_delivery,
8771        )?;
8772        workflow_state.history_budget = history_budget;
8773        workflow_state.workflow_command_identity = workflow_command_identity;
8774        if let Some(canonical) = cancellation_history {
8775            workflow_state.cancellation_history = canonical;
8776            workflow_state.cancellation_delivery_enabled = true;
8777        }
8778        if workflow_state.cancellation_history.request.is_none() {
8779            workflow_state.cancel_requested = task.cancel_requested;
8780        }
8781        let state = Arc::new(Mutex::new(workflow_state));
8782        let ctx = WorkflowContext {
8783            state,
8784            cancellation_scope_id: "root".into(),
8785        };
8786        let future = (workflow.execute)(ctx.clone(), input);
8787        Ok(PreparedWorkflowTask::Execution {
8788            task,
8789            context: ctx,
8790            future,
8791        })
8792    }
8793
8794    fn poll_workflow_future(
8795        ctx: &WorkflowContext,
8796        future: &mut WorkflowFuture,
8797    ) -> Result<Poll<Result<AvroValue>>> {
8798        let mut cx = TaskContext::from_waker(noop_waker_ref());
8799        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
8800        Ok(future.as_mut().poll(&mut cx))
8801    }
8802
8803    fn finish_workflow_task_execution(
8804        &self,
8805        task: &WorkflowTask,
8806        ctx: &WorkflowContext,
8807        outcome: Poll<Result<AvroValue>>,
8808    ) -> Result<WorkflowTaskDecision> {
8809        if !ctx
8810            .state
8811            .lock()
8812            .map_err(|_| Error::WorkflowStatePoisoned)?
8813            .local_activity_requests
8814            .is_empty()
8815        {
8816            return Err(Error::CooperativeCancellationUnavailable(
8817                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
8818            ));
8819        }
8820        let awaiting_canonical_boundary = {
8821            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8822            state.cancellation_delivery_intent.is_some()
8823                || state.cancellation_scope_opening.is_some()
8824                || state
8825                    .scope_delivery
8826                    .as_ref()
8827                    .is_some_and(|replay| replay.intent.is_some())
8828        };
8829        if awaiting_canonical_boundary {
8830            // A private delivery intent never becomes an application error.
8831            // Even a custom future which ignores a pending durable call cannot
8832            // publish terminal commands before canonical delivery and replay.
8833            if let Poll::Ready(Err(error)) = outcome {
8834                if workflow_task_integrity_error(&error) {
8835                    return Err(error);
8836                }
8837            }
8838            return self.message_stream_decision(&ctx, ctx.take_commands()?);
8839        }
8840
8841        match outcome {
8842            Poll::Ready(Ok(result)) => {
8843                ctx.ensure_history_consumed()?;
8844                let result = encode_typed_envelope(&result, &task.payload_codec)?;
8845                let mut commands = ctx.take_commands()?;
8846                commands.push(json!({
8847                    "type": "complete_workflow",
8848                    "result": result
8849                }));
8850                self.message_stream_decision(&ctx, commands)
8851            }
8852            Poll::Ready(Err(error)) => {
8853                if let Error::ContinueAsNew(request) = error {
8854                    let mut commands = ctx.take_commands()?;
8855                    if let Some(command) = ctx.continue_as_new_command(request)? {
8856                        commands.push(command);
8857                    }
8858                    ctx.ensure_history_consumed()?;
8859                    return self.message_stream_decision(&ctx, commands);
8860                }
8861                if workflow_task_integrity_error(&error) {
8862                    // Replay and protocol failures describe the workflow-task
8863                    // decision itself. Preserve their specific failure reason
8864                    // instead of replacing it with the derivative fact that
8865                    // recorded commands remain unconsumed.
8866                    return Err(error);
8867                }
8868                // A handler error must not hide a committed durable command that
8869                // upgraded workflow code no longer consumes.
8870                ctx.ensure_history_consumed()?;
8871                let mut commands = ctx.take_commands()?;
8872                commands.push(workflow_failure_command(
8873                    &error,
8874                    recorded_activity_failure_boundary(&ctx, &error),
8875                ));
8876                self.message_stream_decision(&ctx, commands)
8877            }
8878            Poll::Pending => {
8879                let commands = ctx.take_commands()?;
8880                if commands.is_empty() && !ctx.matched_recorded_pending()? {
8881                    Err(Error::WorkflowYieldedWithoutCommand)
8882                } else {
8883                    self.message_stream_decision(&ctx, commands)
8884                }
8885            }
8886        }
8887    }
8888
8889    fn message_stream_decision(
8890        &self,
8891        ctx: &WorkflowContext,
8892        commands: Vec<Value>,
8893    ) -> Result<WorkflowTaskDecision> {
8894        if !self.cooperative_cancellation_enabled
8895            && commands.iter().any(|command| {
8896                command["type"] == "schedule_activity"
8897                    && command.get("cancellation_policy").is_some()
8898            })
8899        {
8900            return Err(Error::CooperativeCancellationUnavailable(format!(
8901                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8902                self.worker_id,
8903            )));
8904        }
8905        if !self.cooperative_cancellation_enabled
8906            && commands.iter().any(|command| {
8907                command["type"] == "start_child_workflow"
8908                    && (command["parent_close_policy"] == "request_cancellation"
8909                        || matches!(
8910                            command["cancellation_policy"].as_str(),
8911                            Some("try_cancel" | "wait_cancellation_completed")
8912                        ))
8913            })
8914        {
8915            return Err(Error::CooperativeCancellationUnavailable(format!(
8916                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
8917                self.worker_id,
8918            )));
8919        }
8920        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
8921        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
8922        let scope_delivery = state
8923            .scope_delivery
8924            .as_ref()
8925            .and_then(|replay| replay.intent.clone());
8926        if scope_delivery
8927            .as_ref()
8928            .is_some_and(|intent| commands.len() != intent.command_count)
8929        {
8930            return Err(invalid_recorded_history(
8931                "cancellation_scope_pending_call_escaped",
8932                scope_delivery.as_ref().unwrap().boundary.sequence,
8933                "commands preceding the pending scoped call",
8934                "commands after suspension",
8935                "workflow cannot publish beyond an uncommitted scope delivery",
8936            ));
8937        }
8938        if let Some(opening) = &state.cancellation_scope_opening {
8939            if commands.len() != opening.command_count {
8940                return Err(invalid_recorded_history(
8941                    "cancellation_scope_pending_call_escaped",
8942                    opening.sequence,
8943                    "commands before original scope opening",
8944                    "commands after suspended opening",
8945                    "workflow cannot publish beyond an uncommitted scope opening",
8946                ));
8947            }
8948        }
8949        if state.cancellation_delivery_intent.is_some()
8950            && commands.len() != state.cancellation_delivery_command_count
8951        {
8952            return Err(invalid_recorded_history(
8953                "cooperative_cancellation_pending_call_escaped",
8954                state
8955                    .cancellation_delivery_intent
8956                    .as_ref()
8957                    .expect("pending delivery")
8958                    .sequence,
8959                "only commands preceding the pending cancellation call",
8960                "commands authored after a suspended call",
8961                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
8962            ));
8963        }
8964        Ok(WorkflowTaskDecision {
8965            commands,
8966            message_stream_cursors,
8967            message_stream_waits,
8968            cancellation_delivery: state.cancellation_delivery_intent.clone(),
8969            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
8970            cancellation_scope_delivery: scope_delivery,
8971        })
8972    }
8973
8974    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
8975        if !self.workflows.contains_key(&task.workflow_type) {
8976            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
8977        }
8978
8979        let accepted = task.history_events.iter().rev().find_map(|event| {
8980            (event.event_type == "UpdateAccepted"
8981                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
8982            .then_some(&event.payload)
8983        });
8984        let update_name = accepted
8985            .and_then(|payload| payload.get("update_name"))
8986            .and_then(Value::as_str)
8987            .or(task.update_name.as_deref())
8988            .unwrap_or_default();
8989        let Some(handler) = self
8990            .updates
8991            .get(&task.workflow_type)
8992            .and_then(|handlers| handlers.get(update_name))
8993        else {
8994            return Ok(vec![json!({
8995                "type": "fail_update",
8996                "update_id": update_id,
8997                "message": format!(
8998                    "no update handler is registered for {}.{update_name}",
8999                    task.workflow_type
9000                ),
9001                "exception_type": "UnknownUpdate",
9002                "non_retryable": true,
9003            })]);
9004        };
9005        let arguments = accepted
9006            .and_then(|payload| payload.get("arguments"))
9007            .or(task.arguments.as_ref());
9008        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9009        let workflow_input_avro_value =
9010            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9011        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9012        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9013        let context = QueryContext {
9014            workflow_id: task.workflow_id.clone(),
9015            run_id: task.run_id.clone(),
9016            workflow_type: task.workflow_type.clone(),
9017            run_status: Some("running".to_string()),
9018            workflow_input,
9019            workflow_input_avro_value,
9020            history_events: Arc::new(task.history_events.clone()),
9021            signal_events: Arc::new(signal_events),
9022        };
9023        let mut future = handler(context, arguments);
9024        let mut cx = TaskContext::from_waker(noop_waker_ref());
9025
9026        match future.as_mut().poll(&mut cx) {
9027            Poll::Ready(Ok(result)) => Ok(vec![json!({
9028                "type": "complete_update",
9029                "update_id": update_id,
9030                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9031            })]),
9032            Poll::Ready(Err(error)) => Ok(vec![json!({
9033                "type": "fail_update",
9034                "update_id": update_id,
9035                "message": error.to_string(),
9036                "exception_type": "UpdateFailed",
9037                "non_retryable": true,
9038            })]),
9039            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9040        }
9041    }
9042
9043    #[cfg(test)]
9044    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9045        self.execute_session_activity_task(task, None, None).await
9046    }
9047
9048    async fn execute_session_activity_task(
9049        &self,
9050        task: ActivityTask,
9051        worker_session: Option<WorkerSession>,
9052        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9053    ) -> Result<AvroValue> {
9054        validate_activity_task_payloads(&task)?;
9055        if worker_session.is_some() {
9056            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
9057                || task
9058                    .activity_attempt_id
9059                    .as_deref()
9060                    .or(task.attempt_id.as_deref())
9061                    .is_none_or(str::is_empty)
9062                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
9063            {
9064                return Err(Error::ActivityExecutionAbandoned(
9065                    "session activity requires this worker's exact immutable claim".into(),
9066                ));
9067            }
9068        }
9069
9070        let handler = self
9071            .activities
9072            .get(&task.activity_type)
9073            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
9074        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9075        let attempt_id = task
9076            .activity_attempt_id
9077            .clone()
9078            .or(task.attempt_id.clone())
9079            .unwrap_or_default();
9080        let lease_owner = task
9081            .lease_owner
9082            .clone()
9083            .unwrap_or_else(|| self.worker_id.clone());
9084        let session = worker_session.clone();
9085        let ctx = ActivityContext {
9086            client: self.client.clone(),
9087            task_id: task.task_id,
9088            activity_attempt_id: attempt_id,
9089            lease_owner,
9090            activity_type: task.activity_type,
9091            attempt_number: task.attempt_number,
9092            task_queue: self.task_queue.clone(),
9093            worker_id: self.worker_id.clone(),
9094            claim_guard: None,
9095            local_heartbeats: None,
9096            worker_session,
9097        };
9098
9099        if let Some(claim) = hydration_claim {
9100            claim.confirm(&self.client).await?;
9101        }
9102        let callback = handler(ctx, args);
9103        if let Some(session) = session {
9104            tokio::select! {
9105                biased;
9106                _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
9107                result = callback => if session.active() { result } else {
9108                    Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
9109                },
9110            }
9111        } else {
9112            callback.await
9113        }
9114    }
9115}
9116
9117fn poller_result(
9118    kind: &str,
9119    result: std::result::Result<Result<()>, tokio::task::JoinError>,
9120) -> Result<()> {
9121    match result {
9122        Ok(result) => result,
9123        Err(error) => Err(Error::WorkerLoop(format!(
9124            "{kind} poller join error: {error}"
9125        ))),
9126    }
9127}
9128
9129fn optional_poller_result(
9130    kind: &str,
9131    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
9132) -> Result<()> {
9133    match result {
9134        Some(result) => poller_result(kind, result),
9135        None => Ok(()),
9136    }
9137}
9138
9139async fn join_pollers(
9140    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9141    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9142    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
9143) -> Result<()> {
9144    let mut first_error = None;
9145
9146    if let Some(handle) = workflow_poller {
9147        if let Err(error) = poller_result("workflow", handle.await) {
9148            first_error.get_or_insert(error);
9149        }
9150    }
9151
9152    if let Some(handle) = activity_poller {
9153        if let Err(error) = poller_result("activity", handle.await) {
9154            first_error.get_or_insert(error);
9155        }
9156    }
9157
9158    if let Some(handle) = query_poller {
9159        if let Err(error) = poller_result("query", handle.await) {
9160            first_error.get_or_insert(error);
9161        }
9162    }
9163
9164    if let Some(error) = first_error {
9165        Err(error)
9166    } else {
9167        Ok(())
9168    }
9169}
9170
9171fn default_worker_id() -> String {
9172    let millis = SystemTime::now()
9173        .duration_since(UNIX_EPOCH)
9174        .unwrap_or_default()
9175        .as_millis();
9176    format!("rust-worker-{}-{millis}", std::process::id())
9177}
9178
9179fn percent_encode_path_segment(segment: &str) -> String {
9180    const HEX: &[u8; 16] = b"0123456789ABCDEF";
9181    let mut encoded = String::with_capacity(segment.len());
9182
9183    for byte in segment.bytes() {
9184        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
9185            encoded.push(char::from(byte));
9186        } else {
9187            encoded.push('%');
9188            encoded.push(char::from(HEX[(byte >> 4) as usize]));
9189            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
9190        }
9191    }
9192
9193    encoded
9194}
9195
9196fn unique_request_id(prefix: &str) -> String {
9197    let nanos = SystemTime::now()
9198        .duration_since(UNIX_EPOCH)
9199        .unwrap_or_default()
9200        .as_nanos();
9201    format!("{prefix}-{}-{nanos}", std::process::id())
9202}
9203
9204#[derive(Debug)]
9205struct QueryTaskExecutionFailure {
9206    reason: String,
9207    message: String,
9208    failure_type: String,
9209}
9210
9211impl QueryTaskExecutionFailure {
9212    fn new(
9213        reason: impl Into<String>,
9214        message: impl Into<String>,
9215        failure_type: impl Into<String>,
9216    ) -> Self {
9217        Self {
9218            reason: reason.into(),
9219            message: message.into(),
9220            failure_type: failure_type.into(),
9221        }
9222    }
9223}
9224
9225/// Typed local state owned by one deterministic workflow invocation.
9226///
9227/// Use [`WorkflowInstance::update`] for the same state transitions during
9228/// ordinary execution and replay. A replayed query receives a detached
9229/// immutable `Arc<S>` rather than this mutation-capable handle.
9230#[derive(Clone, Debug)]
9231pub struct WorkflowInstance<S> {
9232    state: Arc<Mutex<S>>,
9233}
9234
9235impl<S> WorkflowInstance<S> {
9236    fn new(state: S) -> Self {
9237        Self {
9238            state: Arc::new(Mutex::new(state)),
9239        }
9240    }
9241
9242    /// Read the current workflow-instance state without changing it.
9243    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
9244        let state = self
9245            .state
9246            .lock()
9247            .map_err(|_| Error::WorkflowStatePoisoned)?;
9248        Ok(reader(&state))
9249    }
9250
9251    /// Apply one deterministic workflow-instance state transition.
9252    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
9253        let mut state = self
9254            .state
9255            .lock()
9256            .map_err(|_| Error::WorkflowStatePoisoned)?;
9257        Ok(transition(&mut state))
9258    }
9259}
9260
9261impl<S: Clone> WorkflowInstance<S> {
9262    fn snapshot(&self) -> Result<S> {
9263        self.read(Clone::clone)
9264    }
9265}
9266
9267#[derive(Clone, Debug, PartialEq)]
9268pub struct MessageStreamMessage {
9269    pub stream_name: String,
9270    pub message_id: String,
9271    pub position: u64,
9272    pub arguments: Vec<AvroValue>,
9273}
9274
9275#[derive(Clone, Debug)]
9276pub struct MessageStream {
9277    ctx: WorkflowContext,
9278    name: String,
9279}
9280
9281impl MessageStream {
9282    /// Wait for one message, then return a bounded currently-available batch.
9283    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
9284        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
9285            return Err(Error::Codec(format!(
9286                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
9287            )));
9288        }
9289        loop {
9290            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
9291                return Ok(batch);
9292            }
9293
9294            self.ctx.record_message_stream_wait(&self.name)?;
9295            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
9296            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
9297            self.ctx.buffer_message_stream_delivery(arguments)?;
9298            if let Some(sequence) = replay_wait_sequence {
9299                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
9300            }
9301        }
9302    }
9303
9304    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
9305        self.receive(1)
9306            .await?
9307            .into_iter()
9308            .next()
9309            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
9310    }
9311}
9312
9313#[derive(Clone, Debug)]
9314pub struct WorkflowContext {
9315    state: Arc<Mutex<WorkflowState>>,
9316    cancellation_scope_id: String,
9317}
9318
9319fn valid_memo_key(key: &str) -> bool {
9320    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
9321
9322    !key.is_empty()
9323        && key.len() <= 64
9324        && (numeric_candidate.is_empty()
9325            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
9326        && key
9327            .bytes()
9328            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
9329}
9330
9331fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
9332    BASE64
9333        .decode(encode_avro_value(value)?.blob)
9334        .map(|bytes| bytes.len())
9335        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
9336}
9337
9338fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
9339    let AvroValue::Map(entries) = value else {
9340        return Err(Error::InvalidMemoUpdate(
9341            "entries must serialize to an Avro string-keyed map".to_string(),
9342        ));
9343    };
9344    if require_entries && entries.is_empty() {
9345        return Err(Error::InvalidMemoUpdate(
9346            "at least one entry is required".to_string(),
9347        ));
9348    }
9349    if entries.len() > MAX_MEMO_ENTRIES {
9350        return Err(Error::InvalidMemoUpdate(format!(
9351            "at most {MAX_MEMO_ENTRIES} entries are allowed"
9352        )));
9353    }
9354
9355    for (key, value) in &entries {
9356        if !valid_memo_key(&key) {
9357            return Err(Error::InvalidMemoUpdate(
9358                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
9359            ));
9360        }
9361        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
9362            return Err(Error::InvalidMemoUpdate(format!(
9363                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
9364            )));
9365        }
9366    }
9367
9368    let value = AvroValue::Map(entries);
9369    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
9370        return Err(Error::InvalidMemoUpdate(format!(
9371            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
9372        )));
9373    }
9374    Ok(value)
9375}
9376
9377fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
9378    let object = envelope.as_object().ok_or_else(|| {
9379        Error::InvalidMemoUpdate(
9380            "history field must use the public {codec, blob} payload envelope".to_string(),
9381        )
9382    })?;
9383    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
9384        return Err(Error::InvalidMemoUpdate(
9385            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
9386        ));
9387    }
9388
9389    canonical_memo_entries(
9390        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
9391        require_entries,
9392    )
9393}
9394
9395impl WorkflowContext {
9396    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
9397        let name = name.into();
9398        if name.is_empty()
9399            || name.len() > 128
9400            || !name.bytes().all(|byte| {
9401                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
9402            })
9403        {
9404            return Err(Error::Codec(
9405                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
9406                    .to_string(),
9407            ));
9408        }
9409        Ok(MessageStream {
9410            ctx: self.clone(),
9411            name,
9412        })
9413    }
9414
9415    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
9416        let mut state = self
9417            .state
9418            .lock()
9419            .map_err(|_| Error::WorkflowStatePoisoned)?;
9420        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9421        state
9422            .message_stream_waits
9423            .insert(name.to_string(), position);
9424        Ok(())
9425    }
9426
9427    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
9428        let mut state = self
9429            .state
9430            .lock()
9431            .map_err(|_| Error::WorkflowStatePoisoned)?;
9432        let cursor = state
9433            .message_stream_cursors
9434            .get(&message.stream_name)
9435            .copied()
9436            .unwrap_or(0);
9437        if message.position <= cursor {
9438            return Ok(());
9439        }
9440        let pending = state
9441            .message_stream_messages
9442            .entry(message.stream_name.clone())
9443            .or_default();
9444        if pending.iter().any(|candidate| {
9445            candidate.position == message.position || candidate.message_id == message.message_id
9446        }) {
9447            return Ok(());
9448        }
9449        pending.push(message);
9450        pending.sort_by_key(|candidate| candidate.position);
9451        Ok(())
9452    }
9453
9454    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
9455        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
9456            match delivery {
9457                MessageStreamDelivery::Message(message) => {
9458                    let stream_name = message.stream_name.clone();
9459                    self.buffer_message_stream(message)?;
9460                    return Ok(Some(stream_name));
9461                }
9462                MessageStreamDelivery::Cursor {
9463                    stream_name,
9464                    through_position,
9465                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
9466            }
9467        }
9468        Ok(None)
9469    }
9470
9471    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
9472        let state = self
9473            .state
9474            .lock()
9475            .map_err(|_| Error::WorkflowStatePoisoned)?;
9476        Ok(match state.recorded_commands.get(state.command_cursor) {
9477            Some(RecordedCommand::SignalWait {
9478                sequence,
9479                signal_name,
9480                ..
9481            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
9482            _ => None,
9483        })
9484    }
9485
9486    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
9487        let (history, payload_codec) = {
9488            let state = self
9489                .state
9490                .lock()
9491                .map_err(|_| Error::WorkflowStatePoisoned)?;
9492            (
9493                Arc::clone(&state.history_events),
9494                state.payload_codec.clone(),
9495            )
9496        };
9497
9498        let Some(opened_index) = history.iter().position(|event| {
9499            event.event_type == "SignalWaitOpened"
9500                && durable_event_sequence(event) == Some(wait_sequence)
9501                && event.payload.get("signal_name").and_then(Value::as_str)
9502                    == Some(MESSAGE_STREAM_SIGNAL)
9503        }) else {
9504            return Ok(());
9505        };
9506        let boundary_index = history
9507            .iter()
9508            .enumerate()
9509            .skip(opened_index + 1)
9510            .find_map(|(index, event)| {
9511                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
9512                    && is_authored_command_open_event(event))
9513                .then_some(index)
9514            })
9515            .unwrap_or(history.len());
9516
9517        for event in history[opened_index + 1..boundary_index]
9518            .iter()
9519            .filter(|event| {
9520                event.event_type == "SignalReceived"
9521                    && event.payload.get("signal_name").and_then(Value::as_str)
9522                        == Some(MESSAGE_STREAM_SIGNAL)
9523            })
9524        {
9525            let arguments = decode_signal_event_arguments(event, &payload_codec)?
9526                .into_iter()
9527                .map(AvroValue::into_json)
9528                .collect::<Result<Vec<_>>>()?;
9529            self.buffer_message_stream_delivery(arguments)?;
9530        }
9531        Ok(())
9532    }
9533
9534    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
9535        let mut state = self
9536            .state
9537            .lock()
9538            .map_err(|_| Error::WorkflowStatePoisoned)?;
9539        let cursor = state
9540            .message_stream_cursors
9541            .entry(name.to_string())
9542            .or_default();
9543        *cursor = (*cursor).max(through_position);
9544        if let Some(pending) = state.message_stream_messages.get_mut(name) {
9545            pending.retain(|message| message.position > through_position);
9546        }
9547        Ok(())
9548    }
9549
9550    fn take_message_stream_batch(
9551        &self,
9552        name: &str,
9553        max_items: usize,
9554    ) -> Result<Option<Vec<MessageStreamMessage>>> {
9555        let mut state = self
9556            .state
9557            .lock()
9558            .map_err(|_| Error::WorkflowStatePoisoned)?;
9559        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
9560        let pending = state
9561            .message_stream_messages
9562            .entry(name.to_string())
9563            .or_default();
9564        let count = contiguous_message_stream_count(pending, cursor, max_items);
9565        if count == 0 {
9566            return Ok(None);
9567        }
9568        let batch = pending.drain(..count).collect::<Vec<_>>();
9569        let position = batch.last().map(|message| message.position).unwrap_or(0);
9570        state
9571            .message_stream_cursors
9572            .insert(name.to_string(), position);
9573        state.message_stream_waits.remove(name);
9574        Ok(Some(batch))
9575    }
9576
9577    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
9578        let state = self
9579            .state
9580            .lock()
9581            .map_err(|_| Error::WorkflowStatePoisoned)?;
9582        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
9583        cursors.sort_by_key(|(name, _)| *name);
9584        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
9585        waits.sort_by_key(|(name, _)| *name);
9586        Ok((
9587            cursors
9588                .into_iter()
9589                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
9590                .collect(),
9591            waits
9592                .into_iter()
9593                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
9594                .collect(),
9595        ))
9596    }
9597    /// Identity of the parent workflow currently being replayed.
9598    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
9599        let state = self
9600            .state
9601            .lock()
9602            .map_err(|_| Error::WorkflowStatePoisoned)?;
9603        Ok(WorkflowIdentity {
9604            workflow_id: state.workflow_id.clone(),
9605            run_id: state.run_id.clone(),
9606        })
9607    }
9608
9609    /// Return the server-published history budget for this workflow task.
9610    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
9611        let state = self
9612            .state
9613            .lock()
9614            .map_err(|_| Error::WorkflowStatePoisoned)?;
9615        Ok(state.history_budget.clone())
9616    }
9617
9618    /// Continue this workflow instance as a fresh run with replacement arguments.
9619    ///
9620    /// Return this value directly from the workflow handler. The worker converts
9621    /// it to the terminal protocol command only after replay has consumed every
9622    /// recorded durable command.
9623    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
9624        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
9625    }
9626
9627    /// Continue as new with optional workflow-type and task-queue overrides.
9628    pub fn continue_as_new_with_options<T: Serialize>(
9629        &self,
9630        options: ContinueAsNewOptions,
9631        args: T,
9632    ) -> Result<Value> {
9633        options.validate()?;
9634        Err(Error::ContinueAsNew(ContinueAsNewRequest {
9635            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
9636            options,
9637        }))
9638    }
9639
9640    pub fn activity<T: Serialize>(
9641        &self,
9642        activity_type: impl Into<String>,
9643        args: T,
9644    ) -> ActivityCall {
9645        self.activity_with_options(activity_type, ActivityOptions::new(), args)
9646    }
9647
9648    pub fn activity_on_queue<T, Q>(
9649        &self,
9650        activity_type: impl Into<String>,
9651        task_queue: Option<Q>,
9652        args: T,
9653    ) -> ActivityCall
9654    where
9655        T: Serialize,
9656        Q: Into<String>,
9657    {
9658        let mut options = ActivityOptions::new();
9659        options.task_queue = task_queue.map(Into::into);
9660        self.activity_with_options(activity_type, options, args)
9661    }
9662
9663    /// Schedule one durable activity with retry, routing, and timeout options.
9664    ///
9665    /// Options are validated before the command is emitted. Once the command is
9666    /// recorded, replay consumes the same activity lifecycle at this command
9667    /// position and never emits a duplicate schedule.
9668    ///
9669    /// ```no_run
9670    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
9671    /// # use std::time::Duration;
9672    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
9673    /// let result = ctx
9674    ///     .activity_with_options(
9675    ///         "charge-card",
9676    ///         ActivityOptions::new()
9677    ///             .task_queue("payments")
9678    ///             .retry_policy(
9679    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
9680    ///                     Duration::from_secs(1),
9681    ///                     2,
9682    ///                     Some(Duration::from_secs(30)),
9683    ///                 ),
9684    ///             )
9685    ///             .start_to_close_timeout(Duration::from_secs(60))
9686    ///             .schedule_to_close_timeout(Duration::from_secs(180))
9687    ///             .heartbeat_timeout(Duration::from_secs(15)),
9688    ///         json!([{"order_id": "order-42"}]),
9689    ///     )
9690    ///     .await;
9691    /// match result {
9692    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
9693    ///         "reason": failure.reason,
9694    ///         "timeout_kind": failure.timeout_kind,
9695    ///     })),
9696    ///     other => other,
9697    /// }
9698    /// # }
9699    /// ```
9700    pub fn activity_with_options<T: Serialize>(
9701        &self,
9702        activity_type: impl Into<String>,
9703        options: ActivityOptions,
9704        args: T,
9705    ) -> ActivityCall {
9706        ActivityCall {
9707            ctx: self.clone(),
9708            activity_type: activity_type.into(),
9709            options,
9710            worker_session: None,
9711            args: Some(AvroValue::from_serialize(&args)),
9712            scheduled: false,
9713            local: false,
9714            local_result: None,
9715            parallel_group_path: Vec::new(),
9716        }
9717    }
9718
9719    pub async fn activity_avro_value<T: Serialize>(
9720        &self,
9721        activity_type: impl Into<String>,
9722        args: T,
9723    ) -> Result<AvroValue> {
9724        let mut call = self.activity(activity_type, args);
9725        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9726    }
9727
9728    pub async fn activity_avro_value_with_options<T: Serialize>(
9729        &self,
9730        activity_type: impl Into<String>,
9731        options: ActivityOptions,
9732        args: T,
9733    ) -> Result<AvroValue> {
9734        let mut call = self.activity_with_options(activity_type, options, args);
9735        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9736    }
9737
9738    /// Schedule an activity with a Serde request and decode its Serde result.
9739    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
9740    where
9741        I: Serialize,
9742        O: DeserializeOwned,
9743    {
9744        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
9745            .await
9746    }
9747
9748    /// Schedule an activity with options and decode its result into `O`.
9749    ///
9750    /// Both directions use the fixed Avro Value codec. In particular, this
9751    /// method does not deserialize the JSON-safe inspection projection returned
9752    /// by the dynamic [`ActivityCall`] future.
9753    pub async fn activity_typed_with_options<I, O>(
9754        &self,
9755        activity_type: impl Into<String>,
9756        options: ActivityOptions,
9757        args: I,
9758    ) -> Result<O>
9759    where
9760        I: Serialize,
9761        O: DeserializeOwned,
9762    {
9763        let activity_type = activity_type.into();
9764        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
9765            handler_type_error::<I>(
9766                HandlerKind::Activity,
9767                &activity_type,
9768                HandlerValueKind::Input,
9769                error.to_string(),
9770            )
9771        });
9772        let mut call = ActivityCall {
9773            ctx: self.clone(),
9774            activity_type: activity_type.clone(),
9775            options,
9776            worker_session: None,
9777            args: Some(encoded),
9778            scheduled: false,
9779            local: false,
9780            local_result: None,
9781            parallel_group_path: Vec::new(),
9782        };
9783        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
9784        decode_handler_result(result, HandlerKind::Activity, &activity_type)
9785    }
9786
9787    /// Schedule and join a deterministic activity/child/timer group.
9788    ///
9789    /// Nested groups retain their input shape. Every durable leaf is scheduled
9790    /// before this future yields, results are assembled by declaration order,
9791    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
9792    /// declaration path, stable group metadata, and completed siblings.
9793    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9794        ParallelCall::new(self.clone(), operations)
9795    }
9796
9797    /// Alias for [`WorkflowContext::parallel`].
9798    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
9799        self.parallel(operations)
9800    }
9801
9802    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
9803    pub async fn parallel_avro_value(
9804        &self,
9805        operations: Vec<ParallelOperation>,
9806    ) -> Result<Vec<ParallelAvroResult>> {
9807        let mut call = self.parallel(operations);
9808        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9809    }
9810
9811    /// Start every durable operation and resume from the one winner persisted
9812    /// by Server. Non-winning operations continue and remain addressable.
9813    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
9814        let operations = operations
9815            .into_iter()
9816            .enumerate()
9817            .map(|(index, operation)| (SelectionKey::Index(index), operation))
9818            .collect();
9819        SelectCall::new(self.clone(), operations)
9820    }
9821
9822    /// Named-key variant of [`WorkflowContext::select`].
9823    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
9824    where
9825        K: Into<SelectionKey>,
9826    {
9827        SelectCall::new(
9828            self.clone(),
9829            operations
9830                .into_iter()
9831                .map(|(key, operation)| (key.into(), operation))
9832                .collect(),
9833        )
9834    }
9835
9836    /// Create a workflow-local deterministic compensation registry.
9837    pub fn saga(&self) -> Saga {
9838        Saga::new(self.clone())
9839    }
9840
9841    /// Whether cancellation has reached this replay's authored boundary.
9842    ///
9843    /// Server's current `/cancel` route is terminal and does not set this flag.
9844    /// A canonical service request remains pending until its committed delivery
9845    /// is consumed. Request observation alone does not authorize an exception.
9846    pub fn is_cancellation_requested(&self) -> Result<bool> {
9847        let state = self
9848            .state
9849            .lock()
9850            .map_err(|_| Error::WorkflowStatePoisoned)?;
9851        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9852            return Ok(state
9853                .scope_delivery
9854                .as_ref()
9855                .unwrap()
9856                .contexts
9857                .contains_key(&self.cancellation_scope_id));
9858        }
9859        Ok(state.cancel_requested
9860            || state
9861                .scope_delivery
9862                .as_ref()
9863                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
9864    }
9865
9866    /// Raise a typed cooperative cancellation at an author-controlled point.
9867    ///
9868    /// Passing this result to [`Saga::finish`] compensates already registered
9869    /// forward steps before the cancellation remains the initiating outcome.
9870    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
9871        let mut state = self
9872            .state
9873            .lock()
9874            .map_err(|_| Error::WorkflowStatePoisoned)?;
9875        if state.cancellation_shield_depth == 0 {
9876            if let Some(replay) = &state.scope_delivery {
9877                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
9878                    let delivered = replay
9879                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
9880                        .ok_or_else(|| {
9881                            Error::InvalidCooperativeCancellation(
9882                                "scoped request lacks its consumed original delivery".into(),
9883                            )
9884                        })?;
9885                    return Err(Error::CancellationScopeRequested(
9886                        CancellationScopeRequested {
9887                            context: context
9888                                .clone()
9889                                .with_replay(Some(Arc::downgrade(&self.state))),
9890                            delivery: delivered.boundary.clone(),
9891                        },
9892                    ));
9893                }
9894            }
9895        }
9896        if state.cancel_requested && state.cancellation_shield_depth == 0 {
9897            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
9898                return Ok(());
9899            }
9900            return Err(state.cancellation_error());
9901        }
9902        Ok(())
9903    }
9904
9905    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9906        SignalCall {
9907            ctx: self.clone(),
9908            signal_name: signal_name.into(),
9909            runtime_reserved_allowed: false,
9910            opened_wait: false,
9911            matched_pending: false,
9912            parallel_group_path: Vec::new(),
9913        }
9914    }
9915
9916    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
9917        SignalCall {
9918            ctx: self.clone(),
9919            signal_name: signal_name.into(),
9920            runtime_reserved_allowed: true,
9921            opened_wait: false,
9922            matched_pending: false,
9923            parallel_group_path: Vec::new(),
9924        }
9925    }
9926
9927    pub async fn wait_signal_avro_value(
9928        &self,
9929        signal_name: impl Into<String>,
9930    ) -> Result<Vec<AvroValue>> {
9931        let mut call = self.wait_signal(signal_name);
9932        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
9933    }
9934
9935    /// Return every committed signal argument list with the given name.
9936    ///
9937    /// This history-backed view is deterministic and is intended for
9938    /// condition predicates that must be re-evaluated after a signal while the
9939    /// workflow is blocked on [`WorkflowContext::wait_condition`].
9940    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
9941        self.signals_avro_value(signal_name)?
9942            .into_iter()
9943            .map(|arguments| {
9944                arguments
9945                    .into_iter()
9946                    .map(AvroValue::into_json)
9947                    .collect::<Result<Vec<_>>>()
9948            })
9949            .collect()
9950    }
9951
9952    /// Lossless fixed Avro Value view of committed signals with the given name.
9953    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9954        let state = self
9955            .state
9956            .lock()
9957            .map_err(|_| Error::WorkflowStatePoisoned)?;
9958        state
9959            .history_events
9960            .iter()
9961            .filter(|event| {
9962                event.event_type == "SignalReceived"
9963                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
9964            })
9965            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
9966            .collect()
9967    }
9968
9969    /// Return every committed update argument list with the given name.
9970    ///
9971    /// Accepted and applied records for the same update ID are de-duplicated.
9972    /// A Server task created after an update therefore replays the workflow and
9973    /// re-evaluates an open condition without application polling.
9974    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
9975        self.updates_avro_value(update_name)?
9976            .into_iter()
9977            .map(|arguments| {
9978                arguments
9979                    .into_iter()
9980                    .map(AvroValue::into_json)
9981                    .collect::<Result<Vec<_>>>()
9982            })
9983            .collect()
9984    }
9985
9986    /// Lossless fixed Avro Value view of committed updates with the given name.
9987    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
9988        let state = self
9989            .state
9990            .lock()
9991            .map_err(|_| Error::WorkflowStatePoisoned)?;
9992        let mut seen = Vec::new();
9993        let mut updates = Vec::new();
9994        for event in state.history_events.iter() {
9995            if !matches!(
9996                event.event_type.as_str(),
9997                "UpdateAccepted" | "UpdateApplied"
9998            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
9999                || event.payload.get("arguments").is_none()
10000            {
10001                continue;
10002            }
10003            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
10004                if seen.iter().any(|recorded| recorded == update_id) {
10005                    continue;
10006                }
10007                seen.push(update_id.to_string());
10008            }
10009            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
10010        }
10011        Ok(updates)
10012    }
10013
10014    /// Wait for a deterministic predicate to become true or for its durable
10015    /// timeout to elapse.
10016    ///
10017    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
10018    /// predicate tokens automatically change the recorded definition
10019    /// fingerprint. Direct callers must provide an equally stable identity in
10020    /// [`ConditionWaitOptions`].
10021    pub fn wait_condition<F>(
10022        &self,
10023        options: ConditionWaitOptions,
10024        predicate: F,
10025    ) -> ConditionWaitCall
10026    where
10027        F: Fn() -> Result<bool> + Send + 'static,
10028    {
10029        ConditionWaitCall {
10030            ctx: self.clone(),
10031            options,
10032            predicate: Box::new(predicate),
10033            occurrence_id: None,
10034            opened_wait: false,
10035            parallel_group_path: Vec::new(),
10036        }
10037    }
10038
10039    /// Wait for server-backed durable time without blocking the worker executor.
10040    ///
10041    /// Polling this future emits one `start_timer` command and yields. The
10042    /// server records the deadline, so neither worker nor server restarts reset
10043    /// the wait. Replay resolves the future only from a `TimerScheduled` and
10044    /// `TimerFired` pair at the same position in the shared durable-command
10045    /// stream, with matching sequence, timer identity, and delay. Sub-second
10046    /// durations round up because protocol deadlines use whole seconds.
10047    ///
10048    /// ```no_run
10049    /// # use durable_workflow::{json, Client, Worker};
10050    /// # use std::time::Duration;
10051    /// # fn configure(client: Client) {
10052    /// let mut worker = Worker::new(client, "rust-workers");
10053    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
10054    ///     ctx.sleep(Duration::from_secs(5)).await?;
10055    ///     Ok(json!({"status": "timer fired"}))
10056    /// });
10057    /// # }
10058    /// ```
10059    pub fn sleep(&self, duration: Duration) -> TimerCall {
10060        let delay_seconds = duration
10061            .as_secs()
10062            .checked_add(u64::from(duration.subsec_nanos() > 0));
10063        TimerCall {
10064            ctx: self.clone(),
10065            delay_seconds,
10066            scheduled: false,
10067            matched_pending: false,
10068            parallel_group_path: Vec::new(),
10069        }
10070    }
10071
10072    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
10073    pub fn start_timer(&self, duration: Duration) -> TimerCall {
10074        self.sleep(duration)
10075    }
10076
10077    /// Evaluate a non-deterministic callback once and durably record its typed value.
10078    ///
10079    /// On replay the callback is not invoked: the value is decoded from the
10080    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
10081    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
10082    /// small values that must remain fixed for the lifetime of a workflow run.
10083    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
10084    where
10085        T: Serialize + DeserializeOwned,
10086        F: FnOnce() -> T,
10087    {
10088        {
10089            let mut state = self
10090                .state
10091                .lock()
10092                .map_err(|_| Error::WorkflowStatePoisoned)?;
10093            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10094                return match recorded {
10095                    RecordedCommand::SideEffect { sequence, value } => {
10096                        state.command_cursor += 1;
10097                        value.deserialize().map_err(|error| {
10098                            Error::NonDeterministicReplay(ReplayFailure::new(
10099                                "side_effect_type_mismatch",
10100                                Some(sequence),
10101                                Some(std::any::type_name::<T>().to_string()),
10102                                Some(error.to_string()),
10103                                "recorded side-effect value is incompatible with the requested Rust type",
10104                            ))
10105                        })
10106                    }
10107                    other => Err(command_mismatch(&other, "side effect")),
10108                };
10109            }
10110        }
10111
10112        let value = callback();
10113        let avro_value = AvroValue::from_serialize(&value)?;
10114        let mut state = self
10115            .state
10116            .lock()
10117            .map_err(|_| Error::WorkflowStatePoisoned)?;
10118        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
10119        state.commands.push(json!({
10120            "type": "record_side_effect",
10121            "result": result,
10122        }));
10123        Ok(value)
10124    }
10125
10126    /// Record or replay a lossless fixed Avro Value side effect.
10127    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
10128    where
10129        F: FnOnce() -> AvroValue,
10130    {
10131        {
10132            let mut state = self
10133                .state
10134                .lock()
10135                .map_err(|_| Error::WorkflowStatePoisoned)?;
10136            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10137                return match recorded {
10138                    RecordedCommand::SideEffect { value, .. } => {
10139                        state.command_cursor += 1;
10140                        Ok(value)
10141                    }
10142                    other => Err(command_mismatch(&other, "side effect")),
10143                };
10144            }
10145        }
10146
10147        let value = callback();
10148        let mut state = self
10149            .state
10150            .lock()
10151            .map_err(|_| Error::WorkflowStatePoisoned)?;
10152        let result = encode_typed_envelope(&value, &state.payload_codec)?;
10153        state.commands.push(json!({
10154            "type": "record_side_effect",
10155            "result": result,
10156        }));
10157        Ok(value)
10158    }
10159
10160    /// Append output items at a deterministic workflow command boundary.
10161    ///
10162    /// Stable idempotency keys are derived from the server-provided durable
10163    /// workflow command identity, command ordinal, and item index. Replay
10164    /// consumes the recorded side effect and never emits another append.
10165    pub fn append_workflow_stream(
10166        &self,
10167        stream_name: impl Into<String>,
10168        items: &[WorkflowStreamAppendItem],
10169        max_pending_items: Option<u64>,
10170    ) -> Result<()> {
10171        if items.is_empty() {
10172            return Err(Error::Codec(
10173                "workflow_stream_items_empty: append requires at least one item".to_string(),
10174            ));
10175        }
10176        if max_pending_items == Some(0) {
10177            return Err(Error::Codec(
10178                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
10179                    .to_string(),
10180            ));
10181        }
10182        let stream_name = stream_name.into();
10183        if stream_name.is_empty() {
10184            return Err(Error::Codec(
10185                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10186            ));
10187        }
10188
10189        let mut state = self
10190            .state
10191            .lock()
10192            .map_err(|_| Error::WorkflowStatePoisoned)?;
10193        let command_ordinal = state.workflow_stream_command_counter;
10194        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10195            state.workflow_stream_command_counter += 1;
10196            return match recorded {
10197                RecordedCommand::SideEffect { .. } => {
10198                    state.command_cursor += 1;
10199                    Ok(())
10200                }
10201                other => Err(command_mismatch(&other, "workflow stream append")),
10202            };
10203        }
10204
10205        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10206        state.workflow_stream_command_counter += 1;
10207        let wire_items = items
10208            .iter()
10209            .enumerate()
10210            .map(|(item_index, item)| {
10211                item.wire_value(Some(format!(
10212                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
10213                )))
10214            })
10215            .collect::<Vec<_>>();
10216        let mut directive = json!({
10217            "operation": "append",
10218            "stream_name": stream_name,
10219            "command_identity": identity,
10220            "command_ordinal": command_ordinal,
10221            "items": wire_items,
10222        });
10223        if let Some(max_pending_items) = max_pending_items {
10224            directive["max_pending_items"] = json!(max_pending_items);
10225        }
10226        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10227        state.commands.push(json!({
10228            "type": "record_side_effect",
10229            "result": result,
10230            "workflow_stream": directive,
10231        }));
10232        Ok(())
10233    }
10234
10235    /// Close a run-scoped output stream at a deterministic command boundary.
10236    pub fn close_workflow_stream(
10237        &self,
10238        stream_name: impl Into<String>,
10239        retention_seconds: Option<u64>,
10240    ) -> Result<()> {
10241        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
10242    }
10243
10244    /// Mark a run-scoped output stream errored at a deterministic command boundary.
10245    pub fn error_workflow_stream(
10246        &self,
10247        stream_name: impl Into<String>,
10248        error_reason: impl Into<String>,
10249        retention_seconds: Option<u64>,
10250    ) -> Result<()> {
10251        let error_reason = error_reason.into();
10252        if error_reason.is_empty() {
10253            return Err(Error::Codec(
10254                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
10255            ));
10256        }
10257        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
10258    }
10259
10260    fn finish_workflow_stream(
10261        &self,
10262        stream_name: String,
10263        error_reason: Option<String>,
10264        retention_seconds: Option<u64>,
10265    ) -> Result<()> {
10266        if stream_name.is_empty() {
10267            return Err(Error::Codec(
10268                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
10269            ));
10270        }
10271        if retention_seconds == Some(0) {
10272            return Err(Error::Codec(
10273                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
10274            ));
10275        }
10276        let mut state = self
10277            .state
10278            .lock()
10279            .map_err(|_| Error::WorkflowStatePoisoned)?;
10280        let command_ordinal = state.workflow_stream_command_counter;
10281        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10282            state.workflow_stream_command_counter += 1;
10283            return match recorded {
10284                RecordedCommand::SideEffect { .. } => {
10285                    state.command_cursor += 1;
10286                    Ok(())
10287                }
10288                other => Err(command_mismatch(&other, "workflow stream close")),
10289            };
10290        }
10291        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
10292        state.workflow_stream_command_counter += 1;
10293        let mut directive = json!({
10294            "operation": if error_reason.is_some() { "error" } else { "close" },
10295            "stream_name": stream_name,
10296            "command_identity": identity,
10297            "command_ordinal": command_ordinal,
10298        });
10299        if let Some(error_reason) = error_reason {
10300            directive["error_reason"] = json!(error_reason);
10301        }
10302        if let Some(retention_seconds) = retention_seconds {
10303            directive["retention_seconds"] = json!(retention_seconds);
10304        }
10305        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
10306        state.commands.push(json!({
10307            "type": "record_side_effect",
10308            "result": result,
10309            "workflow_stream": directive,
10310        }));
10311        Ok(())
10312    }
10313
10314    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
10315        let identity = state.workflow_command_identity.as_str();
10316        if identity.is_empty() {
10317            return Err(Error::MissingWorkflowCommandIdentity);
10318        }
10319        Ok(identity)
10320    }
10321
10322    /// Validate, emit, or replay a typed workflow search-attribute update.
10323    ///
10324    /// The command is non-blocking within a workflow decision, but its
10325    /// `SearchAttributesUpserted` event occupies the same deterministic command
10326    /// stream as activities, timers, conditions, and other durable operations.
10327    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
10328        update.validate()?;
10329        let (attributes, attribute_types) = update.into_wire_parts();
10330        let mut state = self
10331            .state
10332            .lock()
10333            .map_err(|_| Error::WorkflowStatePoisoned)?;
10334
10335        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10336            return match recorded {
10337                RecordedCommand::SearchAttributes {
10338                    sequence,
10339                    attributes: recorded_attributes,
10340                    attribute_types: recorded_attribute_types,
10341                } => {
10342                    if recorded_attributes != attributes {
10343                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10344                            "search_attribute_value_mismatch",
10345                            Some(sequence),
10346                            Some(recorded_attributes.to_string()),
10347                            Some(attributes.to_string()),
10348                            "search-attribute values differ from the recorded durable command",
10349                        )));
10350                    }
10351                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
10352                        if recorded_types != attribute_types {
10353                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10354                                "search_attribute_type_mismatch",
10355                                Some(sequence),
10356                                Some(json!(recorded_types).to_string()),
10357                                Some(json!(attribute_types).to_string()),
10358                                "search-attribute declared types differ from the recorded durable command",
10359                            )));
10360                        }
10361                    }
10362                    state.command_cursor += 1;
10363                    Ok(())
10364                }
10365                other => Err(command_mismatch(&other, "search-attribute update")),
10366            };
10367        }
10368
10369        let mut command = serde_json::Map::from_iter([
10370            ("type".to_string(), json!("upsert_search_attributes")),
10371            ("attributes".to_string(), attributes),
10372        ]);
10373        if !attribute_types.is_empty() {
10374            command.insert("attribute_types".to_string(), json!(attribute_types));
10375        }
10376        state.commands.push(Value::Object(command));
10377        Ok(())
10378    }
10379
10380    /// Record a UUIDv4 once and return the same UUID on every replay.
10381    pub fn uuid_v4(&self) -> Result<Uuid> {
10382        self.side_effect(Uuid::new_v4)
10383    }
10384
10385    /// Select the newest supported version for a change, or replay the version
10386    /// already committed for that stable change ID.
10387    ///
10388    /// An unmarked old history that reached its next durable operation, or
10389    /// already completed, selects `-1` when that version is supported. This
10390    /// leaves the original operation available and writes no additional marker.
10391    /// Consistent markers written by older workers retain their original ordered
10392    /// positions. Repeated calls consume a matching marker at the current cursor.
10393    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
10394    pub fn get_version(
10395        &self,
10396        change_id: impl Into<String>,
10397        min_supported: i32,
10398        max_supported: i32,
10399    ) -> Result<i32> {
10400        let change_id = change_id.into();
10401        if change_id.trim().is_empty() {
10402            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10403                "version_change_id_invalid",
10404                None,
10405                Some("non-empty change ID".to_string()),
10406                Some(change_id),
10407                "version markers require a stable non-empty change ID",
10408            )));
10409        }
10410        if min_supported > max_supported {
10411            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10412                "version_range_invalid",
10413                None,
10414                Some("min_supported <= max_supported".to_string()),
10415                Some(format!("{min_supported}..={max_supported}")),
10416                "version marker supported range is invalid",
10417            )));
10418        }
10419
10420        let mut state = self
10421            .state
10422            .lock()
10423            .map_err(|_| Error::WorkflowStatePoisoned)?;
10424        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
10425            if let Some(RecordedCommand::VersionMarker {
10426                sequence: alias_sequence,
10427                change_id: alias_change_id,
10428                version: alias_version,
10429            }) = state.recorded_commands.get(state.command_cursor)
10430            {
10431                if alias_change_id == &change_id {
10432                    if *alias_version != version {
10433                        return Err(invalid_recorded_history(
10434                            "version_marker_conflict",
10435                            *alias_sequence,
10436                            &format!("selected version {version} for change ID {change_id:?}"),
10437                            &format!("recorded version {alias_version}"),
10438                            "recorded marker conflicts with the decision already selected during replay",
10439                        ));
10440                    }
10441                    ensure_version_supported(
10442                        &change_id,
10443                        version,
10444                        min_supported,
10445                        max_supported,
10446                        *alias_sequence,
10447                    )?;
10448                    // Older workers could record the same decision again. Keep
10449                    // each physical boundary without skipping intervening work.
10450                    state.command_cursor += 1;
10451                    return Ok(version);
10452                }
10453            }
10454            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
10455            return Ok(version);
10456        }
10457
10458        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10459            return match recorded {
10460                RecordedCommand::VersionMarker {
10461                    sequence,
10462                    change_id: recorded_change_id,
10463                    version,
10464                    ..
10465                } => {
10466                    if recorded_change_id != change_id {
10467                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10468                            "version_change_id_mismatch",
10469                            Some(sequence),
10470                            Some(recorded_change_id),
10471                            Some(change_id),
10472                            "recorded version marker change ID differs from current workflow code",
10473                        )));
10474                    }
10475                    ensure_version_supported(
10476                        &change_id,
10477                        version,
10478                        min_supported,
10479                        max_supported,
10480                        sequence,
10481                    )?;
10482                    state.command_cursor += 1;
10483                    state.version_markers.insert(change_id, (version, sequence));
10484                    Ok(version)
10485                }
10486                other => {
10487                    let version = -1;
10488                    let sequence = other.sequence();
10489                    ensure_version_supported(
10490                        &change_id,
10491                        version,
10492                        min_supported,
10493                        max_supported,
10494                        sequence,
10495                    )?;
10496                    // The existing operation proves this patch site was reached
10497                    // before its marker existed. Keep its original cursor.
10498                    state.version_markers.insert(change_id, (version, sequence));
10499                    Ok(version)
10500                }
10501            };
10502        }
10503
10504        if state
10505            .history_events
10506            .iter()
10507            .any(|event| event.event_type == "WorkflowCompleted")
10508        {
10509            let version = -1;
10510            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
10511            state.version_markers.insert(change_id, (version, 0));
10512            return Ok(version);
10513        }
10514
10515        let version = max_supported;
10516        state.commands.push(json!({
10517            "type": "record_version_marker",
10518            "change_id": change_id,
10519            "version": version,
10520            "min_supported": min_supported,
10521            "max_supported": max_supported,
10522        }));
10523        // Sequence numbers are assigned by the server. Zero identifies a marker
10524        // selected in this uncommitted decision batch for duplicate-call checks.
10525        state.version_markers.insert(change_id, (version, 0));
10526        Ok(version)
10527    }
10528
10529    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
10530    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
10531        Ok(self.get_version(change_id, -1, 1)? == 1)
10532    }
10533
10534    /// Keep a patch marker in history after the legacy branch has been removed.
10535    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
10536        self.get_version(change_id, -1, 1).map(|_| ())
10537    }
10538
10539    /// Merge non-indexed workflow memo metadata through durable history.
10540    ///
10541    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
10542    /// public Avro payload envelope consumed by Server and Cloud runtimes.
10543    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
10544        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
10545        let mut state = self
10546            .state
10547            .lock()
10548            .map_err(|_| Error::WorkflowStatePoisoned)?;
10549
10550        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10551            return match recorded {
10552                RecordedCommand::Memo {
10553                    sequence,
10554                    entries: recorded_entries,
10555                } => {
10556                    if recorded_entries != entries {
10557                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10558                            "memo_update_mismatch",
10559                            Some(sequence),
10560                            Some(format!("{recorded_entries:?}")),
10561                            Some(format!("{entries:?}")),
10562                            "recorded memo entries differ from the current workflow update",
10563                        )));
10564                    }
10565                    state.command_cursor += 1;
10566                    Ok(())
10567                }
10568                other => Err(command_mismatch(&other, "memo upsert")),
10569            };
10570        }
10571
10572        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
10573        state.commands.push(json!({
10574            "type": "upsert_memo",
10575            "entries": entries_envelope,
10576        }));
10577        Ok(())
10578    }
10579
10580    /// Start a named durable child on an explicit queue and await its result.
10581    ///
10582    /// The command is recorded in the parent's sequence-ordered durable command
10583    /// stream. Replay keeps a scheduled child pending without emitting another
10584    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
10585    /// values preserve the history payload codec and include both sides of the
10586    /// durable relationship; failures are returned as
10587    /// [`Error::ChildWorkflowFailed`].
10588    ///
10589    /// ```no_run
10590    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
10591    /// # fn configure(client: Client) {
10592    /// let mut worker = Worker::new(client, "parent-workers");
10593    /// worker.register_workflow("order-parent", |ctx, _input| async move {
10594    ///     let child = ctx
10595    ///         .start_child_workflow(
10596    ///             "fulfil-order",
10597    ///             ChildWorkflowOptions::new("fulfilment-workers")
10598    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
10599    ///             json!([{"order_id": "order-42"}]),
10600    ///         )
10601    ///         .await?;
10602    ///     Ok(child.result)
10603    /// });
10604    /// # }
10605    /// ```
10606    pub fn start_child_workflow<T: Serialize>(
10607        &self,
10608        workflow_type: impl Into<String>,
10609        options: ChildWorkflowOptions,
10610        args: T,
10611    ) -> ChildWorkflowCall {
10612        ChildWorkflowCall {
10613            ctx: self.clone(),
10614            workflow_type: workflow_type.into(),
10615            options,
10616            args: Some(AvroValue::from_serialize(&args)),
10617            scheduled: false,
10618            matched_pending: false,
10619            parallel_group_path: Vec::new(),
10620        }
10621    }
10622
10623    pub async fn start_child_workflow_avro_value<T: Serialize>(
10624        &self,
10625        workflow_type: impl Into<String>,
10626        options: ChildWorkflowOptions,
10627        args: T,
10628    ) -> Result<ChildWorkflowAvroResult> {
10629        let mut call = self.start_child_workflow(workflow_type, options, args);
10630        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10631    }
10632
10633    fn take_commands(&self) -> Result<Vec<Value>> {
10634        let mut state = self
10635            .state
10636            .lock()
10637            .map_err(|_| Error::WorkflowStatePoisoned)?;
10638        Ok(std::mem::take(&mut state.commands))
10639    }
10640
10641    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
10642        let mut state = self
10643            .state
10644            .lock()
10645            .map_err(|_| Error::WorkflowStatePoisoned)?;
10646
10647        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
10648            return Err(command_mismatch(&recorded, "continue as new"));
10649        }
10650        if state.recorded_continue_as_new_sequence.is_some() {
10651            state.continue_as_new_consumed = true;
10652            return Ok(None);
10653        }
10654
10655        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
10656        let mut command = serde_json::Map::from_iter([
10657            ("type".to_string(), json!("continue_as_new")),
10658            ("arguments".to_string(), arguments),
10659            ("queue".to_string(), json!(state.task_queue.clone())),
10660        ]);
10661        if let Some(workflow_type) = request.options.workflow_type {
10662            command.insert("workflow_type".to_string(), json!(workflow_type));
10663        }
10664        if let Some(task_queue) = request.options.task_queue {
10665            command.insert("queue".to_string(), json!(task_queue));
10666        }
10667        Ok(Some(Value::Object(command)))
10668    }
10669
10670    fn matched_recorded_pending(&self) -> Result<bool> {
10671        let state = self
10672            .state
10673            .lock()
10674            .map_err(|_| Error::WorkflowStatePoisoned)?;
10675        Ok(state.matched_recorded_pending)
10676    }
10677
10678    fn ensure_history_consumed(&self) -> Result<()> {
10679        let state = self
10680            .state
10681            .lock()
10682            .map_err(|_| Error::WorkflowStatePoisoned)?;
10683        if let Some(replay) = &state.scope_delivery {
10684            if let Some((&sequence, _)) = replay
10685                .canonical
10686                .deliveries
10687                .iter()
10688                .find(|(sequence, _)| !replay.consumed.contains(sequence))
10689            {
10690                return Err(invalid_recorded_history(
10691                    "cancellation_scope_delivery_unconsumed",
10692                    sequence,
10693                    "original scoped delivery",
10694                    "workflow completion",
10695                    "workflow completed without consuming its committed scope delivery",
10696                ));
10697            }
10698        }
10699        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
10700            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10701                "recorded_commands_unconsumed",
10702                Some(command.sequence()),
10703                Some(command.shape().to_string()),
10704                Some("workflow completion".to_string()),
10705                "workflow completed before consuming all recorded durable commands",
10706            )));
10707        }
10708        if let Some(delivery) = state
10709            .cancellation_history
10710            .delivery
10711            .as_ref()
10712            .filter(|_| !state.cancellation_consumed)
10713        {
10714            return Err(invalid_recorded_history(
10715                "cooperative_cancellation_unconsumed",
10716                delivery.sequence,
10717                "committed cancellation call",
10718                "workflow completion",
10719                "workflow completed without reaching its committed cancellation boundary",
10720            ));
10721        }
10722        if let Some(sequence) = state
10723            .recorded_continue_as_new_sequence
10724            .filter(|_| !state.continue_as_new_consumed)
10725        {
10726            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
10727                "recorded_continue_as_new_unconsumed",
10728                Some(sequence),
10729                Some("continue as new".to_string()),
10730                Some("workflow completion".to_string()),
10731                "workflow completed without consuming its recorded continue-as-new transition",
10732            )));
10733        }
10734        Ok(())
10735    }
10736}
10737
10738fn contiguous_message_stream_count(
10739    pending: &[MessageStreamMessage],
10740    cursor: u64,
10741    max_items: usize,
10742) -> usize {
10743    pending
10744        .iter()
10745        .take(max_items)
10746        .enumerate()
10747        .take_while(|(offset, message)| {
10748            u64::try_from(*offset)
10749                .ok()
10750                .and_then(|offset| cursor.checked_add(offset + 1))
10751                == Some(message.position)
10752        })
10753        .count()
10754}
10755
10756fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
10757    matches!(
10758        event.event_type.as_str(),
10759        "ActivityScheduled"
10760            | "TimerScheduled"
10761            | "ChildWorkflowScheduled"
10762            | "SignalWaitOpened"
10763            | "ConditionWaitOpened"
10764            | "SearchAttributesUpserted"
10765            | "SideEffectRecorded"
10766            | "VersionMarkerRecorded"
10767            | "MemoUpserted"
10768            | "WorkflowContinuedAsNew"
10769    )
10770}
10771
10772#[derive(Debug)]
10773struct WorkflowState {
10774    workflow_id: Option<String>,
10775    run_id: Option<String>,
10776    task_queue: String,
10777    payload_codec: String,
10778    history_events: Arc<Vec<HistoryEvent>>,
10779    history_budget: WorkflowHistoryBudget,
10780    cancel_requested: bool,
10781    cancellation_history: CancellationHistory,
10782    cancellation_consumed: bool,
10783    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
10784    cancellation_shield_depth: u64,
10785    cancellation_delivery_enabled: bool,
10786    cancellation_delivery_intent: Option<CancellationDelivery>,
10787    cancellation_delivery_command_count: usize,
10788    allow_cancellation_scope_authoring: bool,
10789    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
10790    cancellation_scope_memberships: BTreeMap<u64, String>,
10791    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
10792    resume_signal: Option<ResumeSignal>,
10793    recorded_commands: Vec<RecordedCommand>,
10794    selection_markers: Vec<SelectionMarker>,
10795    selection_marker_cursor: usize,
10796    cancelled_selection_members: Vec<SelectionCancellation>,
10797    recorded_continue_as_new_sequence: Option<u64>,
10798    continue_as_new_consumed: bool,
10799    command_cursor: usize,
10800    condition_wait_occurrence_counter: u64,
10801    matched_recorded_pending: bool,
10802    version_markers: HashMap<String, (i32, u64)>,
10803    workflow_command_identity: String,
10804    workflow_stream_command_counter: u64,
10805    commands: Vec<Value>,
10806    local_activity_requests: Vec<local_activity::Request>,
10807    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
10808    message_stream_cursors: HashMap<String, u64>,
10809    message_stream_waits: HashMap<String, u64>,
10810}
10811
10812impl WorkflowState {
10813    #[cfg(test)]
10814    fn new(
10815        history: Vec<HistoryEvent>,
10816        task_queue: String,
10817        payload_codec: String,
10818        resume_signal: Option<ResumeSignal>,
10819    ) -> Result<Self> {
10820        Self::new_with_identity(
10821            history,
10822            None,
10823            None,
10824            task_queue,
10825            payload_codec,
10826            resume_signal,
10827        )
10828    }
10829
10830    fn new_with_identity(
10831        history: Vec<HistoryEvent>,
10832        workflow_id: Option<String>,
10833        run_id: Option<String>,
10834        task_queue: String,
10835        payload_codec: String,
10836        resume_signal: Option<ResumeSignal>,
10837    ) -> Result<Self> {
10838        Self::new_with_identity_and_scopes(
10839            history,
10840            workflow_id,
10841            run_id,
10842            task_queue,
10843            payload_codec,
10844            resume_signal,
10845            false,
10846        )
10847    }
10848
10849    fn new_with_identity_and_scopes(
10850        history: Vec<HistoryEvent>,
10851        workflow_id: Option<String>,
10852        run_id: Option<String>,
10853        task_queue: String,
10854        payload_codec: String,
10855        resume_signal: Option<ResumeSignal>,
10856        allow_cancellation_scope_authoring: bool,
10857    ) -> Result<Self> {
10858        Self::new_with_identity_and_scope_delivery(
10859            history,
10860            workflow_id,
10861            run_id,
10862            task_queue,
10863            payload_codec,
10864            resume_signal,
10865            allow_cancellation_scope_authoring,
10866            false,
10867        )
10868    }
10869
10870    fn new_with_identity_and_scope_delivery(
10871        history: Vec<HistoryEvent>,
10872        workflow_id: Option<String>,
10873        run_id: Option<String>,
10874        task_queue: String,
10875        payload_codec: String,
10876        resume_signal: Option<ResumeSignal>,
10877        allow_cancellation_scope_authoring: bool,
10878        allow_cancellation_scope_delivery: bool,
10879    ) -> Result<Self> {
10880        cooperative_cancellation::assert_cancellation_scope_replay_supported(
10881            &history,
10882            allow_cancellation_scope_authoring,
10883            allow_cancellation_scope_delivery,
10884        )?;
10885        let scopes = if allow_cancellation_scope_authoring {
10886            cancellation_scope::CancellationScopeHistory::read(
10887                &history,
10888                run_id.as_deref().unwrap_or_default(),
10889            )?
10890        } else {
10891            cancellation_scope::CancellationScopeHistory::default()
10892        };
10893        let cancellation_history = CancellationHistory::from_events(
10894            &history,
10895            run_id.as_deref().unwrap_or_default(),
10896            None,
10897        )?;
10898        if allow_cancellation_scope_authoring
10899            && cancellation_history.request.is_some()
10900            && !allow_cancellation_scope_delivery
10901        {
10902            return Err(Error::CancellationScopeExecutionUnavailable);
10903        }
10904        let scope_delivery = if allow_cancellation_scope_delivery {
10905            Some(cancellation_scope_replay::ScopeReplay::read(
10906                &history,
10907                &scopes,
10908                run_id.as_deref().unwrap_or_default(),
10909                workflow_id.as_deref().unwrap_or_default(),
10910            )?)
10911        } else {
10912            None
10913        };
10914        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
10915            &history,
10916            &payload_codec,
10917            WorkflowIdentity {
10918                workflow_id: workflow_id.clone(),
10919                run_id: run_id.clone(),
10920            },
10921        )?)?;
10922        for (sequence, opening) in &scopes.openings {
10923            if recorded_commands
10924                .iter()
10925                .any(|command| command.sequence() == *sequence)
10926            {
10927                return Err(invalid_recorded_history(
10928                    "invalid_cancellation_scope_history",
10929                    *sequence,
10930                    "distinct authored scope opening",
10931                    "operation collision",
10932                    "scope opening collides with a command",
10933                ));
10934            }
10935            recorded_commands.push(RecordedCommand::CancellationScope {
10936                sequence: *sequence,
10937                scope_id: opening.scope_id.clone(),
10938                parent_scope_id: opening.parent_scope_id.clone(),
10939                shield_parent: opening.shield_parent,
10940            });
10941        }
10942        recorded_commands.sort_by_key(RecordedCommand::sequence);
10943        if let Some(replay) = &scope_delivery {
10944            replay.bind_commands(&mut recorded_commands)?;
10945        }
10946        let selection_markers = recorded_selection_markers(&history)?;
10947        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
10948        let recorded_continue_as_new = history
10949            .iter()
10950            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
10951            .collect::<Vec<_>>();
10952        if recorded_continue_as_new.len() > 1 {
10953            return Err(invalid_recorded_history(
10954                "duplicate_continue_as_new_transition",
10955                recorded_continue_as_new
10956                    .last()
10957                    .and_then(|event| durable_event_sequence(event))
10958                    .unwrap_or(0),
10959                "one WorkflowContinuedAsNew event",
10960                &format!(
10961                    "{} WorkflowContinuedAsNew events",
10962                    recorded_continue_as_new.len()
10963                ),
10964                "workflow history records one continue-as-new transition more than once",
10965            ));
10966        }
10967        let recorded_continue_as_new_sequence = recorded_continue_as_new
10968            .first()
10969            .map(|event| {
10970                durable_event_sequence(event).ok_or_else(|| {
10971                    Error::NonDeterministicReplay(ReplayFailure::new(
10972                        "continue_as_new_sequence_missing",
10973                        None,
10974                        Some("recorded transition sequence".to_string()),
10975                        Some("missing sequence".to_string()),
10976                        "WorkflowContinuedAsNew history is missing its recorded sequence",
10977                    ))
10978                })
10979            })
10980            .transpose()?;
10981        let mut message_stream_cursors = HashMap::new();
10982        for event in &history {
10983            if !matches!(
10984                event.event_type.as_str(),
10985                "SignalReceived" | "SignalApplied"
10986            ) || event.payload.get("signal_name").and_then(Value::as_str)
10987                != Some(MESSAGE_STREAM_SIGNAL)
10988            {
10989                continue;
10990            }
10991            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
10992            if arguments.len() != 1 {
10993                continue;
10994            }
10995            let envelope = arguments[0].clone().into_json()?;
10996            let Some(envelope) = envelope.as_object() else {
10997                continue;
10998            };
10999            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
11000            {
11001                continue;
11002            }
11003            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11004                continue;
11005            };
11006            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11007            else {
11008                continue;
11009            };
11010            let cursor = message_stream_cursors
11011                .entry(stream_name.to_string())
11012                .or_insert(0);
11013            *cursor = (*cursor).max(through_position);
11014        }
11015        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
11016        let cancel_requested = history.iter().any(|event| {
11017            matches!(
11018                event.event_type.as_str(),
11019                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
11020            )
11021        });
11022        let cancellation_clock = cancellation_history
11023            .request
11024            .as_ref()
11025            .and_then(|request| request.context.as_ref())
11026            .map(|_| {
11027                cancellation_replay_clock::ReplayClock::new(
11028                    &history,
11029                    &recorded_commands,
11030                    cancellation_history.delivery_index,
11031                )
11032            })
11033            .or_else(|| {
11034                scope_delivery.as_ref().map(|_| {
11035                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
11036                })
11037            });
11038        Ok(Self {
11039            workflow_command_identity: String::new(),
11040            workflow_stream_command_counter: 0,
11041            workflow_id,
11042            run_id,
11043            task_queue,
11044            payload_codec,
11045            history_events: Arc::new(history),
11046            history_budget: WorkflowHistoryBudget {
11047                event_count,
11048                ..WorkflowHistoryBudget::default()
11049            },
11050            cancel_requested,
11051            cancellation_history,
11052            cancellation_consumed: false,
11053            cancellation_clock,
11054            cancellation_shield_depth: 0,
11055            cancellation_delivery_enabled: false,
11056            cancellation_delivery_intent: None,
11057            cancellation_delivery_command_count: 0,
11058            allow_cancellation_scope_authoring,
11059            cancellation_scope_opening: None,
11060            cancellation_scope_memberships: scopes.memberships,
11061            scope_delivery,
11062            resume_signal,
11063            recorded_commands,
11064            selection_markers,
11065            selection_marker_cursor: 0,
11066            cancelled_selection_members,
11067            recorded_continue_as_new_sequence,
11068            continue_as_new_consumed: false,
11069            command_cursor: 0,
11070            condition_wait_occurrence_counter: 0,
11071            matched_recorded_pending: false,
11072            version_markers: HashMap::new(),
11073            commands: Vec::new(),
11074            local_activity_requests: Vec::new(),
11075            message_stream_messages: HashMap::new(),
11076            message_stream_cursors,
11077            message_stream_waits: HashMap::new(),
11078        })
11079    }
11080}
11081
11082enum MessageStreamDelivery {
11083    Message(MessageStreamMessage),
11084    Cursor {
11085        stream_name: String,
11086        through_position: u64,
11087    },
11088}
11089
11090fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
11091    if arguments.len() != 1 {
11092        return Ok(None);
11093    }
11094    let envelope = arguments
11095        .into_iter()
11096        .next()
11097        .expect("one argument was checked");
11098    let Some(envelope) = envelope.as_object() else {
11099        return Ok(None);
11100    };
11101    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
11102        return Ok(None);
11103    };
11104    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
11105        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
11106        else {
11107            return Ok(None);
11108        };
11109        return Ok(Some(MessageStreamDelivery::Cursor {
11110            stream_name: stream_name.to_string(),
11111            through_position,
11112        }));
11113    }
11114    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
11115        return Ok(None);
11116    }
11117    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
11118        return Ok(None);
11119    };
11120    let Some(position) = envelope
11121        .get("position")
11122        .and_then(Value::as_u64)
11123        .filter(|value| *value > 0)
11124    else {
11125        return Ok(None);
11126    };
11127    let Some(payload_envelope) = envelope.get("payload_envelope") else {
11128        return Ok(None);
11129    };
11130    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
11131    else {
11132        return Ok(None);
11133    };
11134    let decoded = decode_avro_value(&payload_envelope)?;
11135    let AvroValue::Array(values) = decoded else {
11136        return Ok(None);
11137    };
11138    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
11139        stream_name: stream_name.to_string(),
11140        message_id: message_id.to_string(),
11141        position,
11142        arguments: values,
11143    })))
11144}
11145
11146#[derive(Clone, Debug)]
11147enum RecordedCommand {
11148    CancellationScope {
11149        sequence: u64,
11150        scope_id: String,
11151        parent_scope_id: String,
11152        shield_parent: bool,
11153    },
11154    CancellationGroup {
11155        sequence: u64,
11156        span: u64,
11157        original: Vec<RecordedCommand>,
11158    },
11159    CancellationBoundary {
11160        sequence: u64,
11161        call_kind: CancellationCallKind,
11162        original: Option<Box<RecordedCommand>>,
11163    },
11164    Activity {
11165        sequence: u64,
11166        activity_type: Option<String>,
11167        cancellation_policy: String,
11168        options: Option<RecordedActivityOptions>,
11169        outcome: Option<ActivityOutcome>,
11170        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11171    },
11172    Timer {
11173        sequence: u64,
11174        delay_seconds: u64,
11175        fired: bool,
11176        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11177    },
11178    ChildWorkflow {
11179        sequence: u64,
11180        workflow_type: Option<String>,
11181        policies: RecordedChildPolicies,
11182        outcome: Option<ChildWorkflowOutcome>,
11183        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11184    },
11185    SignalWait {
11186        sequence: u64,
11187        signal_name: String,
11188        value: Option<Vec<AvroValue>>,
11189        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11190    },
11191    ConditionWait {
11192        sequence: u64,
11193        occurrence_id: String,
11194        condition_key: Option<String>,
11195        predicate_identity: String,
11196        timeout_seconds: Option<u64>,
11197        result: Option<ConditionWaitResult>,
11198        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
11199    },
11200    SearchAttributes {
11201        sequence: u64,
11202        attributes: Value,
11203        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
11204    },
11205    SideEffect {
11206        sequence: u64,
11207        value: AvroValue,
11208    },
11209    VersionMarker {
11210        sequence: u64,
11211        change_id: String,
11212        version: i32,
11213    },
11214    Memo {
11215        sequence: u64,
11216        entries: AvroValue,
11217    },
11218}
11219
11220#[derive(Clone, Debug, PartialEq, Eq)]
11221struct SelectionMarker {
11222    selection_group_id: String,
11223    selection_group_base_sequence: u64,
11224    selection_group_size: usize,
11225    member_key: SelectionKey,
11226    member_index: usize,
11227    member_base_sequence: u64,
11228    member_size: usize,
11229    operation_kind: String,
11230    operation_identity: String,
11231    outcome: String,
11232    resolution_event_id: String,
11233    resolution_event_type: String,
11234}
11235
11236#[derive(Clone, Debug, PartialEq, Eq)]
11237struct SelectionCancellation {
11238    selection_group_id: String,
11239    member_key: SelectionKey,
11240    member_index: usize,
11241    member_base_sequence: u64,
11242    member_size: usize,
11243    operation_kind: String,
11244    operation_identity: String,
11245}
11246
11247fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
11248    let mut markers: Vec<SelectionMarker> = Vec::new();
11249    for event in events
11250        .iter()
11251        .filter(|event| event.event_type == "SelectionResolved")
11252    {
11253        let payload = &event.payload;
11254        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
11255        let group_size = required_selection_usize(payload, "selection_group_size")?;
11256        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
11257        let member_size = required_selection_usize(payload, "member_size")?;
11258        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
11259        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
11260            invalid_recorded_history(
11261                "selection_marker_invalid",
11262                base_sequence,
11263                "non-empty selection_group_id",
11264                &payload.to_string(),
11265                "selection winner history is missing its durable group identity",
11266            )
11267        })?;
11268        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
11269        if group_id != expected_group_id {
11270            return Err(invalid_recorded_history(
11271                "selection_marker_invalid",
11272                base_sequence,
11273                &expected_group_id,
11274                &group_id,
11275                "selection winner history contains an incompatible group identity",
11276            ));
11277        }
11278        let group_end = base_sequence
11279            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
11280            .unwrap_or(u64::MAX);
11281        let member_end = member_base_sequence
11282            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
11283            .unwrap_or(u64::MAX);
11284        if member_index >= group_size
11285            || member_base_sequence < base_sequence
11286            || member_end > group_end
11287        {
11288            return Err(invalid_recorded_history(
11289                "selection_marker_invalid",
11290                base_sequence,
11291                "winner member within selection group bounds",
11292                &payload.to_string(),
11293                "selection winner history contains an invalid member range",
11294            ));
11295        }
11296        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
11297            invalid_recorded_history(
11298                "selection_marker_invalid",
11299                base_sequence,
11300                "selection operation kind",
11301                &payload.to_string(),
11302                "selection winner history is missing its operation kind",
11303            )
11304        })?;
11305        if !matches!(
11306            operation_kind.as_str(),
11307            "activity" | "child" | "timer" | "signal" | "condition" | "group"
11308        ) {
11309            return Err(invalid_recorded_history(
11310                "selection_marker_invalid",
11311                base_sequence,
11312                "activity, child, timer, signal, condition, or group",
11313                &operation_kind,
11314                "selection winner history contains an unsupported operation kind",
11315            ));
11316        }
11317        let operation_identity =
11318            payload_string(payload, "operation_identity").ok_or_else(|| {
11319                invalid_recorded_history(
11320                    "selection_marker_invalid",
11321                    base_sequence,
11322                    "non-empty operation identity",
11323                    &payload.to_string(),
11324                    "selection winner history is missing its durable operation identity",
11325                )
11326            })?;
11327        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
11328            invalid_recorded_history(
11329                "selection_marker_invalid",
11330                base_sequence,
11331                "completed or failed selection outcome",
11332                &payload.to_string(),
11333                "selection winner history is missing its outcome",
11334            )
11335        })?;
11336        if !matches!(outcome.as_str(), "completed" | "failed") {
11337            return Err(invalid_recorded_history(
11338                "selection_marker_invalid",
11339                base_sequence,
11340                "completed or failed selection outcome",
11341                &outcome,
11342                "selection winner history contains an unsupported outcome",
11343            ));
11344        }
11345        let marker = SelectionMarker {
11346            selection_group_id: group_id,
11347            selection_group_base_sequence: base_sequence,
11348            selection_group_size: group_size,
11349            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
11350            member_index,
11351            member_base_sequence,
11352            member_size,
11353            operation_kind,
11354            operation_identity,
11355            outcome,
11356            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
11357                || {
11358                    invalid_recorded_history(
11359                        "selection_marker_invalid",
11360                        base_sequence,
11361                        "durable resolution_event_id",
11362                        &payload.to_string(),
11363                        "selection winner history is missing its terminal event identity",
11364                    )
11365                },
11366            )?,
11367            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
11368                || {
11369                    invalid_recorded_history(
11370                        "selection_marker_invalid",
11371                        base_sequence,
11372                        "durable resolution_event_type",
11373                        &payload.to_string(),
11374                        "selection winner history is missing its terminal event type",
11375                    )
11376                },
11377            )?,
11378        };
11379        if let Some(existing) = markers
11380            .iter()
11381            .find(|existing| existing.selection_group_id == marker.selection_group_id)
11382        {
11383            if existing != &marker {
11384                return Err(invalid_recorded_history(
11385                    "selection_marker_conflict",
11386                    base_sequence,
11387                    &format!("one winner for {}", marker.selection_group_id),
11388                    &payload.to_string(),
11389                    "selection history records conflicting winners for one durable group",
11390                ));
11391            }
11392            continue;
11393        }
11394        markers.push(marker);
11395    }
11396    Ok(markers)
11397}
11398
11399fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
11400    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
11401    for event in events
11402        .iter()
11403        .filter(|event| event.event_type == "SelectionOperationCancelled")
11404    {
11405        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
11406            invalid_recorded_history(
11407                "selection_cancellation_invalid",
11408                0,
11409                "non-empty selection_group_id",
11410                &event.payload.to_string(),
11411                "selection cancellation history is missing its group identity",
11412            )
11413        })?;
11414        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
11415        let marker = SelectionCancellation {
11416            selection_group_id: group_id,
11417            member_key: selection_key_from_value(
11418                event.payload.get("member_key"),
11419                member_base_sequence,
11420            )?,
11421            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
11422            member_base_sequence,
11423            member_size: required_selection_usize(&event.payload, "member_size")?,
11424            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
11425                invalid_recorded_history(
11426                    "selection_cancellation_invalid",
11427                    member_base_sequence,
11428                    "selection operation kind",
11429                    &event.payload.to_string(),
11430                    "selection cancellation is missing its operation kind",
11431                )
11432            })?,
11433            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
11434                || {
11435                    invalid_recorded_history(
11436                        "selection_cancellation_invalid",
11437                        member_base_sequence,
11438                        "selection operation identity",
11439                        &event.payload.to_string(),
11440                        "selection cancellation is missing its operation identity",
11441                    )
11442                },
11443            )?,
11444        };
11445        if let Some(existing) = cancelled.iter().find(|recorded| {
11446            recorded.selection_group_id == marker.selection_group_id
11447                && recorded.member_base_sequence == marker.member_base_sequence
11448        }) {
11449            if existing != &marker {
11450                return Err(invalid_recorded_history(
11451                    "selection_cancellation_conflict",
11452                    member_base_sequence,
11453                    "one stable SelectionOperationCancelled marker",
11454                    &event.payload.to_string(),
11455                    "selection cancellation history contains conflicting member metadata",
11456                ));
11457            }
11458        } else {
11459            cancelled.push(marker);
11460        }
11461    }
11462    Ok(cancelled)
11463}
11464
11465fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
11466    payload
11467        .get(field)
11468        .and_then(value_as_u64)
11469        .filter(|value| *value > 0)
11470        .ok_or_else(|| {
11471            invalid_recorded_history(
11472                "selection_marker_invalid",
11473                0,
11474                &format!("positive integer {field}"),
11475                &payload.to_string(),
11476                "selection history contains invalid durable identity metadata",
11477            )
11478        })
11479}
11480
11481fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
11482    required_selection_usize_allow_zero(payload, field).and_then(|value| {
11483        if value > 0 {
11484            Ok(value)
11485        } else {
11486            Err(invalid_recorded_history(
11487                "selection_marker_invalid",
11488                0,
11489                &format!("positive integer {field}"),
11490                &payload.to_string(),
11491                "selection history contains invalid durable identity metadata",
11492            ))
11493        }
11494    })
11495}
11496
11497fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
11498    payload
11499        .get(field)
11500        .and_then(value_as_u64)
11501        .and_then(|value| usize::try_from(value).ok())
11502        .ok_or_else(|| {
11503            invalid_recorded_history(
11504                "selection_marker_invalid",
11505                0,
11506                &format!("non-negative integer {field}"),
11507                &payload.to_string(),
11508                "selection history contains invalid durable identity metadata",
11509            )
11510        })
11511}
11512
11513#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11514struct RecordedActivityOptions {
11515    task_queue: RecordedSnapshotValue<Option<String>>,
11516    execution_mode: RecordedSnapshotValue<Option<String>>,
11517    retry_policy: ActivityRetrySnapshot,
11518    worker_session: Option<Value>,
11519}
11520
11521#[derive(Clone, Debug)]
11522struct RecordedChildPolicies {
11523    parent_close_policy: String,
11524    cancellation_policy: String,
11525}
11526
11527fn recorded_activity_cancellation_policy(
11528    events: &[&HistoryEvent],
11529    sequence: u64,
11530) -> Result<String> {
11531    let mut policy: Option<String> = None;
11532    for event in events.iter().filter(|event| {
11533        matches!(
11534            event.event_type.as_str(),
11535            "ActivityScheduled"
11536                | "ActivityStarted"
11537                | "ActivityCompleted"
11538                | "ActivityFailed"
11539                | "ActivityTimedOut"
11540                | "ActivityCancelled"
11541        )
11542    }) {
11543        for source in [Some(&event.payload), event.payload.get("activity")]
11544            .into_iter()
11545            .flatten()
11546        {
11547            let Some(value) = source.get("cancellation_policy") else {
11548                continue;
11549            };
11550            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
11551                value.as_str()
11552            else {
11553                return Err(invalid_recorded_history(
11554                    "invalid_activity_cancellation_policy_history",
11555                    sequence,
11556                    "supported Activity cancellation policy",
11557                    &value.to_string(),
11558                    "Activity history contains an invalid cancellation policy",
11559                ));
11560            };
11561            if let Some(previous) = policy.as_deref() {
11562                if previous != incoming {
11563                    return Err(invalid_recorded_history(
11564                        "activity_cancellation_policy_history_conflict",
11565                        sequence,
11566                        previous,
11567                        incoming,
11568                        "Activity cancellation policy changed between history events",
11569                    ));
11570                }
11571            }
11572            policy = Some(incoming.to_string());
11573        }
11574        policy.get_or_insert_with(|| "try_cancel".to_string());
11575    }
11576    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
11577}
11578
11579fn recorded_child_policy_value<'a>(
11580    payload: &'a Value,
11581    field: &str,
11582    sequence: u64,
11583) -> Result<Option<&'a str>> {
11584    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
11585        return Ok(None);
11586    };
11587    let valid = match (field, value.as_str()) {
11588        (
11589            "parent_close_policy",
11590            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
11591        ) => true,
11592        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
11593            true
11594        }
11595        _ => false,
11596    };
11597    if !valid {
11598        return Err(invalid_recorded_history(
11599            "invalid_child_workflow_policy_history",
11600            sequence,
11601            "supported child workflow policy",
11602            &value.to_string(),
11603            "child workflow history contains an invalid policy",
11604        ));
11605    }
11606    Ok(value.as_str())
11607}
11608
11609fn recorded_child_policies(
11610    events: &[&HistoryEvent],
11611    scheduled: &HistoryEvent,
11612    sequence: u64,
11613) -> Result<RecordedChildPolicies> {
11614    let parent_close_policy =
11615        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
11616            .unwrap_or("abandon")
11617            .to_string();
11618    let cancellation_policy =
11619        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
11620            .unwrap_or("abandon")
11621            .to_string();
11622    for event in events {
11623        for (field, expected) in [
11624            ("parent_close_policy", parent_close_policy.as_str()),
11625            ("cancellation_policy", cancellation_policy.as_str()),
11626        ] {
11627            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
11628                if actual != expected {
11629                    return Err(invalid_recorded_history(
11630                        "child_workflow_policy_history_conflict",
11631                        sequence,
11632                        expected,
11633                        actual,
11634                        "child workflow policy changed between history events",
11635                    ));
11636                }
11637            }
11638        }
11639    }
11640    Ok(RecordedChildPolicies {
11641        parent_close_policy,
11642        cancellation_policy,
11643    })
11644}
11645
11646fn ensure_child_policies_match(
11647    sequence: u64,
11648    recorded: &RecordedChildPolicies,
11649    current: &ChildWorkflowOptions,
11650) -> Result<()> {
11651    for (field, expected, actual) in [
11652        (
11653            "parent_close_policy",
11654            recorded.parent_close_policy.as_str(),
11655            current.parent_close_policy.as_str(),
11656        ),
11657        (
11658            "cancellation_policy",
11659            recorded.cancellation_policy.as_str(),
11660            current.cancellation_policy.as_str(),
11661        ),
11662    ] {
11663        if expected != actual {
11664            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11665                "child_workflow_policy_changed",
11666                Some(sequence),
11667                Some(expected.to_string()),
11668                Some(actual.to_string()),
11669                format!("child workflow {field} changed during replay"),
11670            )));
11671        }
11672    }
11673    Ok(())
11674}
11675
11676#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11677enum RecordedSnapshotValue<T> {
11678    /// Older history did not persist this field, so it cannot constrain replay.
11679    Unknown,
11680    Known(T),
11681}
11682
11683impl<T: PartialEq> RecordedSnapshotValue<T> {
11684    fn matches_current(&self, current: &Self) -> bool {
11685        match self {
11686            Self::Unknown => true,
11687            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
11688        }
11689    }
11690}
11691
11692#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
11693struct ActivityRetrySnapshot {
11694    snapshot_version: RecordedSnapshotValue<Option<u64>>,
11695    max_attempts: RecordedSnapshotValue<Option<u64>>,
11696    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
11697    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11698    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
11699    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
11700    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
11701    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
11702}
11703
11704impl ActivityRetrySnapshot {
11705    fn matches_current(&self, current: &Self) -> bool {
11706        self.snapshot_version
11707            .matches_current(&current.snapshot_version)
11708            && self.max_attempts.matches_current(&current.max_attempts)
11709            && self
11710                .backoff_seconds
11711                .matches_current(&current.backoff_seconds)
11712            && self
11713                .start_to_close_timeout
11714                .matches_current(&current.start_to_close_timeout)
11715            && self
11716                .schedule_to_start_timeout
11717                .matches_current(&current.schedule_to_start_timeout)
11718            && self
11719                .schedule_to_close_timeout
11720                .matches_current(&current.schedule_to_close_timeout)
11721            && self
11722                .heartbeat_timeout
11723                .matches_current(&current.heartbeat_timeout)
11724            && self
11725                .non_retryable_error_types
11726                .matches_current(&current.non_retryable_error_types)
11727    }
11728}
11729
11730fn recorded_optional_u64(
11731    object: Option<&serde_json::Map<String, Value>>,
11732    field: &str,
11733) -> RecordedSnapshotValue<Option<u64>> {
11734    match object.and_then(|object| object.get(field)) {
11735        None => RecordedSnapshotValue::Unknown,
11736        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11737        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
11738    }
11739}
11740
11741fn recorded_optional_string(
11742    object: &serde_json::Map<String, Value>,
11743    field: &str,
11744) -> RecordedSnapshotValue<Option<String>> {
11745    match object.get(field) {
11746        None => RecordedSnapshotValue::Unknown,
11747        Some(Value::Null) => RecordedSnapshotValue::Known(None),
11748        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
11749    }
11750}
11751
11752fn recorded_activity_execution_mode(
11753    events: &[&HistoryEvent],
11754    sequence: u64,
11755) -> Result<RecordedSnapshotValue<Option<String>>> {
11756    let mut recorded = RecordedSnapshotValue::Unknown;
11757    for event in events {
11758        for object in [
11759            event.payload.as_object(),
11760            event.payload.get("activity").and_then(Value::as_object),
11761        ]
11762        .into_iter()
11763        .flatten()
11764        {
11765            let mode = match object.get("execution_mode") {
11766                None => None,
11767                Some(Value::Null) => Some(None),
11768                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
11769                Some(_) => {
11770                    return Err(invalid_recorded_history(
11771                        "activity_execution_mode_invalid",
11772                        sequence,
11773                        "null or a non-empty execution mode",
11774                        "invalid execution_mode",
11775                        "activity history contains an invalid execution mode",
11776                    ))
11777                }
11778            };
11779            let legacy_mode = match object.get("local_activity") {
11780                None => None,
11781                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
11782                Some(_) => {
11783                    return Err(invalid_recorded_history(
11784                        "activity_execution_mode_invalid",
11785                        sequence,
11786                        "boolean local_activity",
11787                        "invalid local_activity",
11788                        "activity history contains an invalid local-activity marker",
11789                    ))
11790                }
11791            };
11792            for mode in [mode, legacy_mode].into_iter().flatten() {
11793                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
11794                {
11795                    return Err(invalid_recorded_history(
11796                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
11797                        "activity lifecycle events at one workflow sequence disagree on execution mode",
11798                    ));
11799                }
11800                recorded = RecordedSnapshotValue::Known(mode);
11801            }
11802        }
11803    }
11804    Ok(recorded)
11805}
11806
11807fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
11808    let policy = policy.and_then(Value::as_object);
11809    let backoff_seconds = policy
11810        .and_then(|policy| policy.get("backoff_seconds"))
11811        .and_then(Value::as_array)
11812        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11813        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
11814    let mut non_retryable_error_types = Vec::new();
11815    for error_type in policy
11816        .and_then(|policy| policy.get("non_retryable_error_types"))
11817        .and_then(Value::as_array)
11818        .into_iter()
11819        .flatten()
11820        .filter_map(Value::as_str)
11821        .map(str::trim)
11822        .filter(|error_type| !error_type.is_empty())
11823    {
11824        if !non_retryable_error_types
11825            .iter()
11826            .any(|recorded| recorded == error_type)
11827        {
11828            non_retryable_error_types.push(error_type.to_string());
11829        }
11830    }
11831
11832    ActivityRetrySnapshot {
11833        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
11834        max_attempts: recorded_optional_u64(policy, "max_attempts"),
11835        backoff_seconds,
11836        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
11837        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
11838        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
11839        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
11840        non_retryable_error_types: if policy
11841            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
11842        {
11843            RecordedSnapshotValue::Known(non_retryable_error_types)
11844        } else {
11845            RecordedSnapshotValue::Unknown
11846        },
11847    }
11848}
11849
11850fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
11851    let policy = options.retry_policy.as_ref();
11852    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
11853        Some(Value::Null) => None,
11854        Some(value) => value_as_u64(value),
11855        None => Some(1),
11856    };
11857    let backoff_seconds = policy
11858        .and_then(|policy| policy.get("backoff_seconds"))
11859        .and_then(Value::as_array)
11860        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
11861        .unwrap_or_default();
11862    let non_retryable_error_types = policy
11863        .and_then(|policy| policy.get("non_retryable_error_types"))
11864        .and_then(Value::as_array)
11865        .into_iter()
11866        .flatten()
11867        .filter_map(Value::as_str)
11868        .map(str::to_string)
11869        .collect();
11870
11871    ActivityRetrySnapshot {
11872        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
11873        max_attempts: RecordedSnapshotValue::Known(max_attempts),
11874        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
11875        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
11876        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
11877        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
11878        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
11879        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
11880    }
11881}
11882
11883fn activity_options_description(options: &RecordedActivityOptions) -> String {
11884    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
11885}
11886
11887impl RecordedCommand {
11888    fn sequence(&self) -> u64 {
11889        match self {
11890            Self::CancellationGroup { sequence, .. }
11891            | Self::CancellationScope { sequence, .. }
11892            | Self::CancellationBoundary { sequence, .. }
11893            | Self::Activity { sequence, .. }
11894            | Self::Timer { sequence, .. }
11895            | Self::ChildWorkflow { sequence, .. }
11896            | Self::SignalWait { sequence, .. }
11897            | Self::ConditionWait { sequence, .. }
11898            | Self::SearchAttributes { sequence, .. }
11899            | Self::SideEffect { sequence, .. }
11900            | Self::VersionMarker { sequence, .. }
11901            | Self::Memo { sequence, .. } => *sequence,
11902        }
11903    }
11904
11905    fn shape(&self) -> &'static str {
11906        match self {
11907            Self::CancellationScope { .. } => "cancellation scope",
11908            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
11909                "cooperative cancellation"
11910            }
11911            Self::Activity { .. } => "activity",
11912            Self::Timer { .. } => "timer",
11913            Self::ChildWorkflow { .. } => "child workflow",
11914            Self::SignalWait { .. } => "signal wait",
11915            Self::ConditionWait { .. } => "condition wait",
11916            Self::SearchAttributes { .. } => "search-attribute update",
11917            Self::SideEffect { .. } => "side effect",
11918            Self::VersionMarker { .. } => "version marker",
11919            Self::Memo { .. } => "memo upsert",
11920        }
11921    }
11922}
11923
11924fn ensure_version_supported(
11925    change_id: &str,
11926    version: i32,
11927    min_supported: i32,
11928    max_supported: i32,
11929    sequence: u64,
11930) -> Result<()> {
11931    if (min_supported..=max_supported).contains(&version) {
11932        return Ok(());
11933    }
11934    Err(Error::NonDeterministicReplay(ReplayFailure::new(
11935        "version_marker_incompatible_range",
11936        (sequence != 0).then_some(sequence),
11937        Some(format!("{min_supported}..={max_supported}")),
11938        Some(format!("{change_id}:{version}")),
11939        "recorded workflow version is outside the range supported by current code",
11940    )))
11941}
11942
11943#[derive(Clone, Debug)]
11944struct ResumeSignal {
11945    signal_name: String,
11946    arguments: Vec<AvroValue>,
11947}
11948
11949const MAX_PARALLEL_OPERATIONS: usize = 1000;
11950
11951fn parallel_group_prefix(kind: &str) -> &'static str {
11952    match kind {
11953        "activity" => "parallel-activities",
11954        "child" => "parallel-children",
11955        "timer" => "parallel-timers",
11956        _ => "parallel-calls",
11957    }
11958}
11959
11960fn parallel_group_entry(
11961    base_sequence: u64,
11962    size: usize,
11963    index: usize,
11964    kind: &str,
11965) -> ParallelGroupMetadata {
11966    ParallelGroupMetadata {
11967        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
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: None,
11973        selection_member_key: None,
11974        selection_member_index: None,
11975        selection_member_base_sequence: None,
11976        selection_member_size: None,
11977        selection_member_kind: None,
11978    }
11979}
11980
11981struct SelectionMemberMetadata {
11982    key: SelectionKey,
11983    index: usize,
11984    base_sequence: u64,
11985    size: usize,
11986    kind: String,
11987}
11988
11989fn selection_group_entry(
11990    base_sequence: u64,
11991    size: usize,
11992    index: usize,
11993    kind: &str,
11994    member: &SelectionMemberMetadata,
11995) -> ParallelGroupMetadata {
11996    ParallelGroupMetadata {
11997        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
11998        parallel_group_kind: kind.to_string(),
11999        parallel_group_base_sequence: base_sequence,
12000        parallel_group_size: size,
12001        parallel_group_index: index,
12002        parallel_group_mode: Some("select".to_string()),
12003        selection_member_key: Some(member.key.clone()),
12004        selection_member_index: Some(member.index),
12005        selection_member_base_sequence: Some(member.base_sequence),
12006        selection_member_size: Some(member.size),
12007        selection_member_kind: Some(member.kind.clone()),
12008    }
12009}
12010
12011fn apply_parallel_group_path(
12012    command: &mut serde_json::Map<String, Value>,
12013    path: &[ParallelGroupMetadata],
12014) {
12015    let Some(inner) = path.last() else {
12016        return;
12017    };
12018    command.insert(
12019        "parallel_group_id".to_string(),
12020        json!(inner.parallel_group_id),
12021    );
12022    command.insert(
12023        "parallel_group_kind".to_string(),
12024        json!(inner.parallel_group_kind),
12025    );
12026    command.insert(
12027        "parallel_group_base_sequence".to_string(),
12028        json!(inner.parallel_group_base_sequence),
12029    );
12030    command.insert(
12031        "parallel_group_size".to_string(),
12032        json!(inner.parallel_group_size),
12033    );
12034    command.insert(
12035        "parallel_group_index".to_string(),
12036        json!(inner.parallel_group_index),
12037    );
12038    if let Some(mode) = &inner.parallel_group_mode {
12039        command.insert("parallel_group_mode".to_string(), json!(mode));
12040    }
12041    if let Some(key) = &inner.selection_member_key {
12042        command.insert("selection_member_key".to_string(), json!(key));
12043    }
12044    if let Some(index) = inner.selection_member_index {
12045        command.insert("selection_member_index".to_string(), json!(index));
12046    }
12047    if let Some(base_sequence) = inner.selection_member_base_sequence {
12048        command.insert(
12049            "selection_member_base_sequence".to_string(),
12050            json!(base_sequence),
12051        );
12052    }
12053    if let Some(size) = inner.selection_member_size {
12054        command.insert("selection_member_size".to_string(), json!(size));
12055    }
12056    if let Some(kind) = &inner.selection_member_kind {
12057        command.insert("selection_member_kind".to_string(), json!(kind));
12058    }
12059    command.insert("parallel_group_path".to_string(), json!(path));
12060}
12061
12062fn ensure_parallel_path_matches(
12063    sequence: u64,
12064    recorded: Option<&[ParallelGroupMetadata]>,
12065    expected: &[ParallelGroupMetadata],
12066) -> Result<()> {
12067    match (recorded, expected.is_empty()) {
12068        (None, true) => Ok(()),
12069        (Some(recorded), false) if recorded == expected => Ok(()),
12070        (None, false) => Err(invalid_recorded_history(
12071            "parallel_group_metadata_missing",
12072            sequence,
12073            &serde_json::to_string(expected).unwrap_or_default(),
12074            "<missing>",
12075            "recorded parallel member is missing its durable group path",
12076        )),
12077        (Some(recorded), true) => Err(invalid_recorded_history(
12078            "parallel_group_shape_mismatch",
12079            sequence,
12080            "sequential command",
12081            &serde_json::to_string(recorded).unwrap_or_default(),
12082            "recorded command belonged to a parallel group but current code schedules it sequentially",
12083        )),
12084        (Some(recorded), false) => Err(invalid_recorded_history(
12085            "parallel_group_shape_mismatch",
12086            sequence,
12087            &serde_json::to_string(recorded).unwrap_or_default(),
12088            &serde_json::to_string(expected).unwrap_or_default(),
12089            "recorded parallel-group identity or path changed during replay",
12090        )),
12091    }
12092}
12093
12094#[derive(Clone, Debug)]
12095enum ParallelShape {
12096    Leaf,
12097    Group(Vec<ParallelShape>),
12098}
12099
12100struct ParallelDescriptor {
12101    operation: ParallelOperation,
12102    offset: usize,
12103    member_path: Vec<usize>,
12104    group_path: Vec<ParallelGroupMetadata>,
12105}
12106
12107fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
12108    operations
12109        .iter()
12110        .map(|operation| match operation {
12111            ParallelOperation::Group(children) => parallel_leaf_count(children),
12112            _ => 1,
12113        })
12114        .sum()
12115}
12116
12117fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
12118    match operation {
12119        ParallelOperation::Activity { .. } => Some("activity"),
12120        ParallelOperation::ChildWorkflow { .. } => Some("child"),
12121        ParallelOperation::Timer(_) => Some("timer"),
12122        ParallelOperation::Signal(_) => Some("signal"),
12123        ParallelOperation::Condition { .. } => Some("condition"),
12124        ParallelOperation::Group(children) => parallel_group_kind(children),
12125    }
12126}
12127
12128fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
12129    let mut kind = None;
12130    for operation in operations {
12131        let Some(operation_kind) = parallel_operation_kind(operation) else {
12132            continue;
12133        };
12134        match kind {
12135            None => kind = Some(operation_kind),
12136            Some(current) if current == operation_kind => {}
12137            Some(_) => return Some("mixed"),
12138        }
12139    }
12140    kind
12141}
12142
12143fn validate_parallel_operations(
12144    operations: &[ParallelOperation],
12145    member_path: &mut Vec<usize>,
12146    root: bool,
12147) -> Result<()> {
12148    let leaves = parallel_leaf_count(operations);
12149    if leaves > MAX_PARALLEL_OPERATIONS {
12150        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12151            reason: "fan_out_limit_exceeded",
12152            member_path: member_path.clone(),
12153            message: format!(
12154                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12155            ),
12156        }));
12157    }
12158    if !root && operations.is_empty() {
12159        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12160            reason: "nested_group_empty",
12161            member_path: member_path.clone(),
12162            message: "a nested group must contain at least one durable leaf".to_string(),
12163        }));
12164    }
12165
12166    for (index, operation) in operations.iter().enumerate() {
12167        member_path.push(index);
12168        match operation {
12169            ParallelOperation::Activity {
12170                options, arguments, ..
12171            } => {
12172                options
12173                    .validate()
12174                    .map_err(|error| Error::InvalidActivityOptions(error))?;
12175                if let Err(error) = arguments {
12176                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12177                        reason: "arguments_invalid",
12178                        member_path: member_path.clone(),
12179                        message: error.to_string(),
12180                    }));
12181                }
12182            }
12183            ParallelOperation::ChildWorkflow {
12184                options, arguments, ..
12185            } => {
12186                validate_parallel_child_options(options)?;
12187                if let Err(error) = arguments {
12188                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12189                        reason: "arguments_invalid",
12190                        member_path: member_path.clone(),
12191                        message: error.to_string(),
12192                    }));
12193                }
12194            }
12195            ParallelOperation::Timer(duration)
12196                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
12197            {
12198                return Err(Error::TimerDurationOverflow);
12199            }
12200            ParallelOperation::Timer(_) => {}
12201            ParallelOperation::Signal(signal_name) => {
12202                validate_user_signal_name(signal_name)?;
12203                if signal_name.trim().is_empty() {
12204                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
12205                        reason: "signal_name_empty",
12206                        member_path: member_path.clone(),
12207                        message: "signal wait name must not be empty".to_string(),
12208                    }));
12209                }
12210            }
12211            ParallelOperation::Condition { options, .. } => {
12212                options.validate()?;
12213            }
12214            ParallelOperation::Group(children) => {
12215                validate_parallel_operations(children, member_path, false)?;
12216            }
12217        }
12218        member_path.pop();
12219    }
12220    Ok(())
12221}
12222
12223fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
12224    if options.task_queue.trim().is_empty() {
12225        return Err(Error::InvalidChildWorkflowOptions(
12226            "task_queue must not be empty".to_string(),
12227        ));
12228    }
12229    for (name, value) in [
12230        (
12231            "execution_timeout_seconds",
12232            options.execution_timeout_seconds,
12233        ),
12234        ("run_timeout_seconds", options.run_timeout_seconds),
12235    ] {
12236        if value == Some(0) {
12237            return Err(Error::InvalidChildWorkflowOptions(format!(
12238                "{name} must be at least 1"
12239            )));
12240        }
12241    }
12242    if options
12243        .retry_policy
12244        .as_ref()
12245        .is_some_and(|policy| policy.max_attempts == Some(0))
12246    {
12247        return Err(Error::InvalidChildWorkflowOptions(
12248            "retry_policy.max_attempts must be at least 1".to_string(),
12249        ));
12250    }
12251    Ok(())
12252}
12253
12254fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
12255    ParallelShape::Group(
12256        operations
12257            .iter()
12258            .map(|operation| match operation {
12259                ParallelOperation::Group(children) => parallel_shape(children),
12260                _ => ParallelShape::Leaf,
12261            })
12262            .collect(),
12263    )
12264}
12265
12266fn parallel_descriptors(
12267    operations: Vec<ParallelOperation>,
12268    base_sequence: u64,
12269) -> Result<Vec<ParallelDescriptor>> {
12270    let size = parallel_leaf_count(&operations);
12271    let kind = parallel_group_kind(&operations).unwrap_or("activity");
12272    let mut descriptors = Vec::with_capacity(size);
12273    let mut cursor = 0;
12274
12275    for (index, operation) in operations.into_iter().enumerate() {
12276        match operation {
12277            ParallelOperation::Group(children) => {
12278                let child_base = base_sequence
12279                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12280                    .ok_or(Error::TimerDurationOverflow)?;
12281                for mut descriptor in parallel_descriptors(children, child_base)? {
12282                    let outer_index = cursor + descriptor.offset;
12283                    descriptor.group_path.insert(
12284                        0,
12285                        parallel_group_entry(base_sequence, size, outer_index, kind),
12286                    );
12287                    descriptor.member_path.insert(0, index);
12288                    descriptor.offset = outer_index;
12289                    descriptors.push(descriptor);
12290                }
12291                cursor = descriptors.len();
12292            }
12293            operation => {
12294                descriptors.push(ParallelDescriptor {
12295                    operation,
12296                    offset: cursor,
12297                    member_path: vec![index],
12298                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
12299                });
12300                cursor += 1;
12301            }
12302        }
12303    }
12304    Ok(descriptors)
12305}
12306
12307enum ParallelLeafCall {
12308    Activity(ActivityCall),
12309    ChildWorkflow(ChildWorkflowCall),
12310    Timer(TimerCall),
12311    Signal(SignalCall),
12312    Condition(ConditionWaitCall),
12313}
12314
12315fn parallel_leaf_call(
12316    ctx: &WorkflowContext,
12317    operation: ParallelOperation,
12318    parallel_group_path: Vec<ParallelGroupMetadata>,
12319) -> ParallelLeafCall {
12320    match operation {
12321        ParallelOperation::Activity {
12322            activity_type,
12323            options,
12324            arguments,
12325        } => ParallelLeafCall::Activity(ActivityCall {
12326            ctx: ctx.clone(),
12327            activity_type,
12328            options,
12329            worker_session: None,
12330            args: Some(arguments),
12331            scheduled: false,
12332            local: false,
12333            local_result: None,
12334            parallel_group_path,
12335        }),
12336        ParallelOperation::ChildWorkflow {
12337            workflow_type,
12338            options,
12339            arguments,
12340        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
12341            ctx: ctx.clone(),
12342            workflow_type,
12343            options,
12344            args: Some(arguments),
12345            scheduled: false,
12346            matched_pending: false,
12347            parallel_group_path,
12348        }),
12349        ParallelOperation::Timer(duration) => {
12350            let delay_seconds = duration
12351                .as_secs()
12352                .checked_add(u64::from(duration.subsec_nanos() > 0));
12353            ParallelLeafCall::Timer(TimerCall {
12354                ctx: ctx.clone(),
12355                delay_seconds,
12356                scheduled: false,
12357                matched_pending: false,
12358                parallel_group_path,
12359            })
12360        }
12361        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
12362            ctx: ctx.clone(),
12363            signal_name,
12364            runtime_reserved_allowed: false,
12365            opened_wait: false,
12366            matched_pending: false,
12367            parallel_group_path,
12368        }),
12369        ParallelOperation::Condition { options, predicate } => {
12370            ParallelLeafCall::Condition(ConditionWaitCall {
12371                ctx: ctx.clone(),
12372                options,
12373                predicate,
12374                occurrence_id: None,
12375                opened_wait: false,
12376                parallel_group_path,
12377            })
12378        }
12379        ParallelOperation::Group(_) => {
12380            unreachable!("parallel descriptors contain only durable leaves")
12381        }
12382    }
12383}
12384
12385impl ParallelLeafCall {
12386    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
12387        match self {
12388            Self::Activity(call) => Pin::new(call)
12389                .poll_avro_value(cx)
12390                .map_ok(ParallelAvroResult::Activity),
12391            Self::ChildWorkflow(call) => Pin::new(call)
12392                .poll_avro_value(cx)
12393                .map_ok(ParallelAvroResult::ChildWorkflow),
12394            Self::Timer(call) => Pin::new(call)
12395                .poll(cx)
12396                .map_ok(|()| ParallelAvroResult::Timer),
12397            Self::Signal(call) => Pin::new(call)
12398                .poll_avro_value(cx)
12399                .map_ok(ParallelAvroResult::Signal),
12400            Self::Condition(call) => Pin::new(call)
12401                .poll(cx)
12402                .map_ok(ParallelAvroResult::Condition),
12403        }
12404    }
12405}
12406
12407struct ParallelLeaf {
12408    call: ParallelLeafCall,
12409    sequence: u64,
12410    member_path: Vec<usize>,
12411    group_path: Vec<ParallelGroupMetadata>,
12412    result: Option<ParallelAvroResult>,
12413}
12414
12415/// Future returned by [`WorkflowContext::parallel`].
12416pub struct ParallelCall {
12417    ctx: WorkflowContext,
12418    operations: Option<Vec<ParallelOperation>>,
12419    shape: Option<ParallelShape>,
12420    leaves: Vec<ParallelLeaf>,
12421    pending_scope_delivery: bool,
12422    worker_session: Option<WorkerSessionOptions>,
12423}
12424
12425impl ParallelCall {
12426    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
12427        Self {
12428            ctx,
12429            operations: Some(operations),
12430            shape: None,
12431            leaves: Vec::new(),
12432            pending_scope_delivery: false,
12433            worker_session: None,
12434        }
12435    }
12436
12437    fn initialize(&mut self) -> Result<()> {
12438        if let Some(session) = &self.worker_session {
12439            session.to_wire()?;
12440        }
12441        let operations = self.operations.take().unwrap_or_default();
12442        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
12443        self.shape = Some(parallel_shape(&operations));
12444        if operations.is_empty() {
12445            return Ok(());
12446        }
12447
12448        let base_sequence = {
12449            let state = self
12450                .ctx
12451                .state
12452                .lock()
12453                .map_err(|_| Error::WorkflowStatePoisoned)?;
12454            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12455                recorded.sequence()
12456            } else {
12457                let last = state
12458                    .recorded_commands
12459                    .last()
12460                    .map(RecordedCommand::sequence)
12461                    .unwrap_or(0);
12462                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12463                    .and_then(|sequence| sequence.checked_add(1))
12464                    .ok_or_else(|| {
12465                        Error::InvalidParallelGroup(ParallelGroupError {
12466                            reason: "sequence_overflow",
12467                            member_path: Vec::new(),
12468                            message: "parallel group sequence identity overflowed u64".to_string(),
12469                        })
12470                    })?
12471            }
12472        };
12473
12474        let descriptors = parallel_descriptors(operations, base_sequence)?;
12475        {
12476            let mut state = self
12477                .ctx
12478                .state
12479                .lock()
12480                .map_err(|_| Error::WorkflowStatePoisoned)?;
12481            let cursor = state.command_cursor;
12482            self.ctx.validate_scope_membership(&mut state, cursor)?;
12483            if state.prepare_parallel_scope_cancellation(&descriptors)? {
12484                self.pending_scope_delivery = true;
12485                return Ok(());
12486            }
12487            state.expand_cancellation_group(&descriptors)?;
12488            state.prepare_group_cancellation(&descriptors)?;
12489        }
12490        self.leaves = descriptors
12491            .into_iter()
12492            .map(|descriptor| {
12493                let mut call = parallel_leaf_call(
12494                    &self.ctx,
12495                    descriptor.operation,
12496                    descriptor.group_path.clone(),
12497                );
12498                if let (Some(session), ParallelLeafCall::Activity(activity)) =
12499                    (&self.worker_session, &mut call)
12500                {
12501                    activity.worker_session = Some(session.clone());
12502                }
12503                ParallelLeaf {
12504                    call,
12505                    sequence: base_sequence + descriptor.offset as u64,
12506                    member_path: descriptor.member_path,
12507                    group_path: descriptor.group_path,
12508                    result: None,
12509                }
12510            })
12511            .collect();
12512        Ok(())
12513    }
12514
12515    fn poll_avro_value(
12516        mut self: Pin<&mut Self>,
12517        cx: &mut TaskContext<'_>,
12518    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
12519        if self.operations.is_some() {
12520            if let Err(error) = self.initialize() {
12521                return Poll::Ready(Err(error));
12522            }
12523        }
12524        if self.pending_scope_delivery {
12525            return Poll::Pending;
12526        }
12527        if self.leaves.is_empty() {
12528            return Poll::Ready(Ok(Vec::new()));
12529        }
12530
12531        let mut failures = Vec::new();
12532        let mut pending = false;
12533        for (index, leaf) in self.leaves.iter_mut().enumerate() {
12534            if leaf.result.is_some() {
12535                continue;
12536            }
12537            match leaf.call.poll_avro_value(cx) {
12538                Poll::Ready(Ok(result)) => leaf.result = Some(result),
12539                Poll::Ready(Err(error)) => failures.push((index, error)),
12540                Poll::Pending => pending = true,
12541            }
12542        }
12543
12544        if !failures.is_empty() {
12545            if let Some(position) = failures
12546                .iter()
12547                .position(|(_, error)| workflow_task_integrity_error(error))
12548            {
12549                return Poll::Ready(Err(failures.remove(position).1));
12550            }
12551            if self
12552                .ctx
12553                .state
12554                .lock()
12555                .map_err(|_| Error::WorkflowStatePoisoned)?
12556                .cancellation_delivery_intent
12557                .is_some()
12558            {
12559                return Poll::Pending;
12560            }
12561            if let Some(position) = failures
12562                .iter()
12563                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
12564            {
12565                return Poll::Ready(Err(failures.remove(position).1));
12566            }
12567            failures.sort_by_key(|(index, _)| *index);
12568            let (failed_index, cause) = failures.remove(0);
12569            let failed = &self.leaves[failed_index];
12570            let completed = self
12571                .leaves
12572                .iter()
12573                .filter_map(|leaf| {
12574                    leaf.result
12575                        .clone()
12576                        .and_then(|result| result.into_json_result().ok())
12577                        .map(|result| ParallelCompletion {
12578                            member_path: leaf.member_path.clone(),
12579                            result,
12580                        })
12581                })
12582                .collect();
12583            let group_id = failed
12584                .group_path
12585                .first()
12586                .map(|entry| entry.parallel_group_id.clone())
12587                .unwrap_or_default();
12588            let sequences = self
12589                .leaves
12590                .iter()
12591                .map(|leaf| leaf.sequence)
12592                .collect::<Vec<_>>();
12593            self.ctx
12594                .state
12595                .lock()
12596                .map_err(|_| Error::WorkflowStatePoisoned)?
12597                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
12598            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
12599                group_id,
12600                member_path: failed.member_path.clone(),
12601                group_path: failed.group_path.clone(),
12602                completed,
12603                cause: Box::new(cause),
12604            })));
12605        }
12606        if pending
12607            || self
12608                .ctx
12609                .state
12610                .lock()
12611                .map_err(|_| Error::WorkflowStatePoisoned)?
12612                .cancellation_delivery_intent
12613                .is_some()
12614        {
12615            return Poll::Pending;
12616        }
12617
12618        let mut flat_results = self
12619            .leaves
12620            .iter_mut()
12621            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
12622            .collect::<Vec<_>>()
12623            .into_iter();
12624        let results = parallel_results_for_shape(
12625            self.shape.as_ref().expect("initialized parallel shape"),
12626            &mut flat_results,
12627        );
12628        let sequences = self
12629            .leaves
12630            .iter()
12631            .map(|leaf| leaf.sequence)
12632            .collect::<Vec<_>>();
12633        self.ctx
12634            .state
12635            .lock()
12636            .map_err(|_| Error::WorkflowStatePoisoned)?
12637            .advance_cancellation_sequences(&sequences, None);
12638        Poll::Ready(Ok(match results {
12639            ParallelAvroResult::Group(results) => results,
12640            ParallelAvroResult::Activity(_)
12641            | ParallelAvroResult::ChildWorkflow(_)
12642            | ParallelAvroResult::Timer
12643            | ParallelAvroResult::Signal(_)
12644            | ParallelAvroResult::Condition(_) => {
12645                unreachable!("root parallel shape is a group")
12646            }
12647        }))
12648    }
12649}
12650
12651fn parallel_results_for_shape(
12652    shape: &ParallelShape,
12653    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
12654) -> ParallelAvroResult {
12655    match shape {
12656        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
12657        ParallelShape::Group(children) => ParallelAvroResult::Group(
12658            children
12659                .iter()
12660                .map(|child| parallel_results_for_shape(child, flat_results))
12661                .collect(),
12662        ),
12663    }
12664}
12665
12666impl Future for ParallelCall {
12667    type Output = Result<Vec<ParallelResult>>;
12668
12669    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
12670        self.poll_avro_value(cx)
12671            .map_ok(|results| {
12672                results
12673                    .into_iter()
12674                    .map(ParallelAvroResult::into_json_result)
12675                    .collect::<Result<Vec<_>>>()
12676            })
12677            .map_ok(|result| result)
12678            .flatten_result()
12679    }
12680}
12681
12682#[derive(Clone, Debug)]
12683struct SelectionMemberPlan {
12684    key: SelectionKey,
12685    index: usize,
12686    base_sequence: u64,
12687    size: usize,
12688    kind: String,
12689    shape: ParallelShape,
12690    leaf_start: usize,
12691}
12692
12693fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
12694    match operation {
12695        ParallelOperation::Activity { .. } => "activity",
12696        ParallelOperation::ChildWorkflow { .. } => "child",
12697        ParallelOperation::Timer(_) => "timer",
12698        ParallelOperation::Signal(_) => "signal",
12699        ParallelOperation::Condition { .. } => "condition",
12700        ParallelOperation::Group(_) => "group",
12701    }
12702}
12703
12704fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
12705    match operation {
12706        ParallelOperation::Group(children) => parallel_shape(children),
12707        _ => ParallelShape::Leaf,
12708    }
12709}
12710
12711fn selection_descriptors(
12712    operations: Vec<(SelectionKey, ParallelOperation)>,
12713    base_sequence: u64,
12714) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
12715    if operations.is_empty() {
12716        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12717            reason: "selection_empty",
12718            member_path: Vec::new(),
12719            message: "durable selection requires at least one operation".to_string(),
12720        }));
12721    }
12722    let operation_refs = operations
12723        .iter()
12724        .map(|(_, operation)| operation)
12725        .collect::<Vec<_>>();
12726    let total_size = operation_refs
12727        .iter()
12728        .map(|operation| match operation {
12729            ParallelOperation::Group(children) => parallel_leaf_count(children),
12730            _ => 1,
12731        })
12732        .sum::<usize>();
12733    if total_size > MAX_PARALLEL_OPERATIONS {
12734        return Err(Error::InvalidParallelGroup(ParallelGroupError {
12735            reason: "fan_out_limit_exceeded",
12736            member_path: Vec::new(),
12737            message: format!(
12738                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
12739            ),
12740        }));
12741    }
12742    let group_kind = {
12743        let mut kind = None;
12744        for operation in &operation_refs {
12745            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
12746            match kind {
12747                None => kind = Some(operation_kind),
12748                Some(current) if current == operation_kind => {}
12749                Some(_) => {
12750                    kind = Some("mixed");
12751                    break;
12752                }
12753            }
12754        }
12755        kind.unwrap_or("mixed")
12756    };
12757
12758    let mut descriptors = Vec::with_capacity(total_size);
12759    let mut members = Vec::with_capacity(operations.len());
12760    let mut cursor = 0usize;
12761    let mut seen_keys: Vec<SelectionKey> = Vec::new();
12762    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
12763        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
12764            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12765                reason: "selection_key_invalid",
12766                member_path: vec![member_index],
12767                message: "selection member keys must be non-empty strings or non-negative integers"
12768                    .to_string(),
12769            }));
12770        }
12771        if seen_keys.contains(&key) {
12772            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12773                reason: "selection_key_duplicate",
12774                member_path: vec![member_index],
12775                message: format!("selection member key {key:?} is duplicated"),
12776            }));
12777        }
12778        seen_keys.push(key.clone());
12779        let member_size = match &operation {
12780            ParallelOperation::Group(children) => parallel_leaf_count(children),
12781            _ => 1,
12782        };
12783        if member_size == 0 {
12784            return Err(Error::InvalidParallelGroup(ParallelGroupError {
12785                reason: "selection_member_empty",
12786                member_path: vec![member_index],
12787                message: "a selection member must contain at least one durable leaf".to_string(),
12788            }));
12789        }
12790        let member_base = base_sequence
12791            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
12792            .ok_or(Error::TimerDurationOverflow)?;
12793        let member_kind = selection_operation_kind(&operation).to_string();
12794        let member_shape = selection_operation_shape(&operation);
12795        let leaf_start = descriptors.len();
12796        match operation {
12797            ParallelOperation::Group(children) => {
12798                validate_parallel_operations(&children, &mut vec![member_index], false)?;
12799                for mut descriptor in parallel_descriptors(children, member_base)? {
12800                    let flat_index = cursor + descriptor.offset;
12801                    descriptor.group_path.insert(
12802                        0,
12803                        selection_group_entry(
12804                            base_sequence,
12805                            total_size,
12806                            flat_index,
12807                            group_kind,
12808                            &SelectionMemberMetadata {
12809                                key: key.clone(),
12810                                index: member_index,
12811                                base_sequence: member_base,
12812                                size: member_size,
12813                                kind: member_kind.clone(),
12814                            },
12815                        ),
12816                    );
12817                    descriptor.member_path.insert(0, member_index);
12818                    descriptor.offset = flat_index;
12819                    descriptors.push(descriptor);
12820                }
12821            }
12822            operation => {
12823                validate_parallel_operations(
12824                    std::slice::from_ref(&operation),
12825                    &mut Vec::new(),
12826                    true,
12827                )?;
12828                descriptors.push(ParallelDescriptor {
12829                    operation,
12830                    offset: cursor,
12831                    member_path: vec![member_index],
12832                    group_path: vec![selection_group_entry(
12833                        base_sequence,
12834                        total_size,
12835                        cursor,
12836                        group_kind,
12837                        &SelectionMemberMetadata {
12838                            key: key.clone(),
12839                            index: member_index,
12840                            base_sequence: member_base,
12841                            size: member_size,
12842                            kind: member_kind.clone(),
12843                        },
12844                    )],
12845                });
12846            }
12847        }
12848        members.push(SelectionMemberPlan {
12849            key,
12850            index: member_index,
12851            base_sequence: member_base,
12852            size: member_size,
12853            kind: member_kind,
12854            shape: member_shape,
12855            leaf_start,
12856        });
12857        cursor += member_size;
12858    }
12859    Ok((descriptors, members))
12860}
12861
12862struct SelectionLeaf {
12863    call: ParallelLeafCall,
12864    outcome: Option<Result<ParallelAvroResult>>,
12865}
12866
12867/// Stable reference to one member of a durable selection group.
12868#[derive(Clone)]
12869pub struct DurableOperationHandle {
12870    ctx: WorkflowContext,
12871    pub key: SelectionKey,
12872    pub index: usize,
12873    pub kind: String,
12874    pub identity: String,
12875    pub base_sequence: u64,
12876    pub size: usize,
12877    pub selection_group_id: String,
12878    shape: ParallelShape,
12879}
12880
12881impl std::fmt::Debug for DurableOperationHandle {
12882    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12883        formatter
12884            .debug_struct("DurableOperationHandle")
12885            .field("key", &self.key)
12886            .field("index", &self.index)
12887            .field("kind", &self.kind)
12888            .field("identity", &self.identity)
12889            .field("base_sequence", &self.base_sequence)
12890            .field("size", &self.size)
12891            .field("selection_group_id", &self.selection_group_id)
12892            .finish()
12893    }
12894}
12895
12896impl DurableOperationHandle {
12897    /// Await this member after another member has already won the selection.
12898    pub fn await_result(&self) -> DurableOperationAwaitCall {
12899        DurableOperationAwaitCall {
12900            handle: self.clone(),
12901        }
12902    }
12903
12904    /// Request cancellation without affecting siblings. The future resolves
12905    /// to unit; only `SelectionOperationCancelled` history proves cancellation
12906    /// beat a concurrently committed terminal result.
12907    pub fn cancel(&self) -> CancelDurableOperationCall {
12908        CancelDurableOperationCall {
12909            handle: self.clone(),
12910            emitted: false,
12911        }
12912    }
12913}
12914
12915/// The one winner committed for a durable selection group.
12916#[derive(Debug)]
12917pub struct SelectionResult {
12918    pub key: SelectionKey,
12919    pub index: usize,
12920    pub kind: String,
12921    pub identity: String,
12922    pub value: Option<ParallelResult>,
12923    pub failure: Option<Error>,
12924    pub winner: DurableOperationHandle,
12925    pub handles: Vec<DurableOperationHandle>,
12926}
12927
12928impl SelectionResult {
12929    pub fn succeeded(&self) -> bool {
12930        self.failure.is_none()
12931    }
12932
12933    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
12934        self.handles.iter().find(|handle| &handle.key == key)
12935    }
12936
12937    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
12938        self.handles
12939            .iter()
12940            .filter(|handle| handle.index != self.index)
12941            .collect()
12942    }
12943
12944    pub fn into_result(self) -> Result<ParallelResult> {
12945        match (self.value, self.failure) {
12946            (Some(value), None) => Ok(value),
12947            (_, Some(error)) => Err(error),
12948            _ => Err(Error::WorkerLoop(
12949                "selection result contained neither a value nor a failure".to_string(),
12950            )),
12951        }
12952    }
12953}
12954
12955/// Future returned by [`WorkflowContext::select`].
12956pub struct SelectCall {
12957    ctx: WorkflowContext,
12958    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
12959    members: Vec<SelectionMemberPlan>,
12960    leaves: Vec<SelectionLeaf>,
12961    group_id: Option<String>,
12962}
12963
12964impl SelectCall {
12965    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
12966        Self {
12967            ctx,
12968            operations: Some(operations),
12969            members: Vec::new(),
12970            leaves: Vec::new(),
12971            group_id: None,
12972        }
12973    }
12974
12975    fn initialize(&mut self) -> Result<()> {
12976        let operations = self.operations.take().unwrap_or_default();
12977        let base_sequence = {
12978            let state = self
12979                .ctx
12980                .state
12981                .lock()
12982                .map_err(|_| Error::WorkflowStatePoisoned)?;
12983            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
12984                state.recorded_commands.get(state.command_cursor)
12985            {
12986                *sequence
12987            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
12988            {
12989                marker.selection_group_base_sequence
12990            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
12991                recorded.sequence()
12992            } else {
12993                let last = state
12994                    .recorded_commands
12995                    .last()
12996                    .map(RecordedCommand::sequence)
12997                    .unwrap_or(0);
12998                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
12999                    .and_then(|sequence| sequence.checked_add(1))
13000                    .ok_or(Error::TimerDurationOverflow)?
13001            }
13002        };
13003        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
13004        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
13005        {
13006            let mut state = self
13007                .ctx
13008                .state
13009                .lock()
13010                .map_err(|_| Error::WorkflowStatePoisoned)?;
13011            state.expand_cancellation_group(&descriptors)?;
13012            state.prepare_group_cancellation(&descriptors)?;
13013        }
13014        self.leaves = descriptors
13015            .into_iter()
13016            .map(|descriptor| SelectionLeaf {
13017                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
13018                outcome: None,
13019            })
13020            .collect();
13021        self.members = members;
13022        self.group_id = Some(group_id);
13023        Ok(())
13024    }
13025}
13026
13027impl Future for SelectCall {
13028    type Output = Result<SelectionResult>;
13029
13030    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13031        if self.operations.is_some() {
13032            if let Err(error) = self.initialize() {
13033                return Poll::Ready(Err(error));
13034            }
13035        }
13036
13037        for leaf in &mut self.leaves {
13038            if leaf.outcome.is_some() {
13039                continue;
13040            }
13041            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
13042                if outcome
13043                    .as_ref()
13044                    .err()
13045                    .is_some_and(workflow_task_integrity_error)
13046                {
13047                    return Poll::Ready(outcome.map(|_| unreachable!()));
13048                }
13049                leaf.outcome = Some(outcome);
13050            }
13051        }
13052
13053        if self
13054            .ctx
13055            .state
13056            .lock()
13057            .map_err(|_| Error::WorkflowStatePoisoned)?
13058            .cancellation_delivery_intent
13059            .is_some()
13060        {
13061            return Poll::Pending;
13062        }
13063
13064        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
13065            matches!(
13066                leaf.outcome,
13067                Some(Err(Error::CooperativeCancellationRequested(_)))
13068            )
13069        }) {
13070            return Poll::Ready(
13071                leaf.outcome
13072                    .take()
13073                    .expect("matched cancellation")
13074                    .map(|_| unreachable!()),
13075            );
13076        }
13077
13078        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
13079        let selection_member_range = self
13080            .members
13081            .first()
13082            .map(|member| member.base_sequence)
13083            .zip(self.leaves.len().try_into().ok())
13084            .map(|(base_sequence, size): (u64, u64)| {
13085                base_sequence..base_sequence.saturating_add(size)
13086            });
13087        let marker = {
13088            let mut state = match self.ctx.state.lock() {
13089                Ok(state) => state,
13090                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13091            };
13092            let marker = state
13093                .selection_markers
13094                .get(state.selection_marker_cursor)
13095                .cloned();
13096            if marker.is_none()
13097                && all_members_terminal
13098                && selection_member_range.as_ref().is_some_and(|member_range| {
13099                    state
13100                        .recorded_commands
13101                        .iter()
13102                        .any(|command| member_range.contains(&command.sequence()))
13103                })
13104            {
13105                // Terminal member history can be committed before the server's
13106                // SelectionResolved marker becomes visible to this task. That
13107                // marker is the durable barrier the selection is still waiting
13108                // on, so an otherwise commandless replay remains legitimately
13109                // pending instead of failing as an untracked yield.
13110                state.matched_recorded_pending = true;
13111            }
13112            marker
13113        };
13114        let Some(marker) = marker else {
13115            return Poll::Pending;
13116        };
13117        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
13118            || marker.selection_group_size != self.leaves.len()
13119            || self.members.first().map(|member| member.base_sequence)
13120                != Some(marker.selection_group_base_sequence)
13121        {
13122            return Poll::Ready(Err(invalid_recorded_history(
13123                "selection_group_shape_mismatch",
13124                marker.selection_group_base_sequence,
13125                self.group_id
13126                    .as_deref()
13127                    .unwrap_or("initialized selection group"),
13128                &marker.selection_group_id,
13129                "recorded selection group differs from current workflow code",
13130            )));
13131        }
13132        let Some(member_position) = self.members.iter().position(|member| {
13133            member.key == marker.member_key
13134                && member.index == marker.member_index
13135                && member.base_sequence == marker.member_base_sequence
13136                && member.size == marker.member_size
13137                && member.kind == marker.operation_kind
13138        }) else {
13139            return Poll::Ready(Err(invalid_recorded_history(
13140                "selection_member_shape_mismatch",
13141                marker.member_base_sequence,
13142                "winner member matching current workflow code",
13143                &format!("{:?}", marker.member_key),
13144                "recorded selection winner differs from the authored member identity",
13145            )));
13146        };
13147        let member = self.members[member_position].clone();
13148        let (handles, resolution_sequence) = {
13149            let mut state = match self.ctx.state.lock() {
13150                Ok(state) => state,
13151                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13152            };
13153            let identities = self
13154                .members
13155                .iter()
13156                .map(|candidate| {
13157                    selection_operation_identity(
13158                        &state,
13159                        &candidate.kind,
13160                        candidate.base_sequence,
13161                        candidate.size,
13162                    )
13163                })
13164                .collect::<Vec<_>>();
13165            if let Some((position, missing)) = identities
13166                .iter()
13167                .enumerate()
13168                .find(|(_, identity)| identity.is_empty())
13169                .map(|(position, identity)| (position, identity.clone()))
13170            {
13171                let candidate = &self.members[position];
13172                return Poll::Ready(Err(invalid_recorded_history(
13173                    "selection_operation_identity_missing",
13174                    candidate.base_sequence,
13175                    &format!(
13176                        "durable {} resource identity from scheduled/open history",
13177                        candidate.kind
13178                    ),
13179                    &missing,
13180                    "selection member history is missing its canonical durable identity",
13181                )));
13182            }
13183            let expected_winner_identity = &identities[member_position];
13184            let resolution_sequence = match validated_selection_resolution_sequence(
13185                &state,
13186                &marker,
13187                &member,
13188                expected_winner_identity,
13189            ) {
13190                Ok(sequence) => sequence,
13191                Err(error) => return Poll::Ready(Err(error)),
13192            };
13193            let handles = self
13194                .members
13195                .iter()
13196                .zip(identities)
13197                .map(|(member, identity)| DurableOperationHandle {
13198                    ctx: self.ctx.clone(),
13199                    key: member.key.clone(),
13200                    index: member.index,
13201                    kind: member.kind.clone(),
13202                    identity,
13203                    base_sequence: member.base_sequence,
13204                    size: member.size,
13205                    selection_group_id: marker.selection_group_id.clone(),
13206                    shape: member.shape.clone(),
13207                })
13208                .collect::<Vec<_>>();
13209            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
13210                return Poll::Ready(Err(error));
13211            }
13212            state.selection_marker_cursor += 1;
13213            (handles, resolution_sequence)
13214        };
13215
13216        let mut winner_failure = None;
13217        let mut flat_results = Vec::with_capacity(member.size);
13218        if marker.outcome == "failed" {
13219            let resolution_offset = match resolution_sequence
13220                .checked_sub(member.base_sequence)
13221                .and_then(|offset| usize::try_from(offset).ok())
13222            {
13223                Some(offset) if offset < member.size => offset,
13224                _ => {
13225                    return Poll::Ready(Err(invalid_recorded_history(
13226                        "selection_resolution_event_mismatch",
13227                        member.base_sequence,
13228                        "failure event within selected member bounds",
13229                        &resolution_sequence.to_string(),
13230                        "selection failure event is outside the authored member",
13231                    )))
13232                }
13233            };
13234            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
13235            match leaf.outcome.take() {
13236                Some(Err(error)) => winner_failure = Some(error),
13237                _ => {
13238                    return Poll::Ready(Err(invalid_recorded_history(
13239                        "selection_winner_outcome_mismatch",
13240                        member.base_sequence,
13241                        "exact failed terminal history referenced by SelectionResolved",
13242                        "missing or successful resolution event",
13243                        "selection winner marker disagrees with terminal operation history",
13244                    )))
13245                }
13246            }
13247        } else {
13248            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
13249                match leaf.outcome.take() {
13250                    Some(Ok(result)) => flat_results.push(result),
13251                    Some(Err(_)) => {
13252                        return Poll::Ready(Err(invalid_recorded_history(
13253                            "selection_winner_outcome_mismatch",
13254                            member.base_sequence,
13255                            "fully completed nested selection member",
13256                            "failed durable leaf",
13257                            "completed selection winner contains a failed leaf",
13258                        )))
13259                    }
13260                    None => {
13261                        return Poll::Ready(Err(invalid_recorded_history(
13262                            "selection_winner_unresolved",
13263                            member.base_sequence,
13264                            "terminal history for every completed winner leaf",
13265                            "pending member history",
13266                            "completed SelectionResolved member has an unfinished durable barrier",
13267                        )))
13268                    }
13269                }
13270            }
13271        }
13272        let value = if winner_failure.is_none() {
13273            let mut flat_results = flat_results.into_iter();
13274            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
13275            match value.into_json_result() {
13276                Ok(value) => Some(value),
13277                Err(error) => return Poll::Ready(Err(error)),
13278            }
13279        } else {
13280            None
13281        };
13282        let winner = handles[member_position].clone();
13283        self.ctx
13284            .state
13285            .lock()
13286            .map_err(|_| Error::WorkflowStatePoisoned)?
13287            .advance_cancellation_selection(&marker.selection_group_id);
13288        Poll::Ready(Ok(SelectionResult {
13289            key: winner.key.clone(),
13290            index: winner.index,
13291            kind: winner.kind.clone(),
13292            identity: winner.identity.clone(),
13293            value,
13294            failure: winner_failure,
13295            winner,
13296            handles,
13297        }))
13298    }
13299}
13300
13301fn selection_operation_identity(
13302    state: &WorkflowState,
13303    kind: &str,
13304    base_sequence: u64,
13305    size: usize,
13306) -> String {
13307    if kind == "group" {
13308        return format!("group:{base_sequence}:{size}");
13309    }
13310    let fields: &[&str] = match kind {
13311        "activity" => &["activity_execution_id"],
13312        "child" => &["child_workflow_run_id"],
13313        "timer" => &["timer_id"],
13314        "signal" => &["signal_wait_id"],
13315        "condition" => &["condition_wait_id"],
13316        _ => &[],
13317    };
13318    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
13319        for event in state
13320            .history_events
13321            .iter()
13322            .filter(|event| durable_event_sequence(event) == Some(sequence))
13323        {
13324            for field in fields {
13325                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
13326                    if !identity.is_empty() {
13327                        return identity.to_string();
13328                    }
13329                }
13330            }
13331        }
13332    }
13333    String::new()
13334}
13335
13336fn validated_selection_resolution_sequence(
13337    state: &WorkflowState,
13338    marker: &SelectionMarker,
13339    member: &SelectionMemberPlan,
13340    expected_identity: &str,
13341) -> Result<u64> {
13342    if expected_identity.is_empty() {
13343        return Err(invalid_recorded_history(
13344            "selection_operation_identity_missing",
13345            member.base_sequence,
13346            &format!(
13347                "durable {} resource identity from scheduled/open history",
13348                member.kind
13349            ),
13350            "missing operation identity",
13351            "selection member history is missing its canonical durable identity",
13352        ));
13353    }
13354    if marker.operation_identity != expected_identity {
13355        return Err(invalid_recorded_history(
13356            "selection_operation_identity_mismatch",
13357            member.base_sequence,
13358            expected_identity,
13359            &marker.operation_identity,
13360            "selection winner identity does not match durable scheduled/open history",
13361        ));
13362    }
13363
13364    let failure_types = [
13365        "ActivityFailed",
13366        "ActivityCancelled",
13367        "ActivityTimedOut",
13368        "ChildRunFailed",
13369        "ChildRunCancelled",
13370        "ChildRunTerminated",
13371    ];
13372    let success_types = [
13373        "ActivityCompleted",
13374        "ChildRunCompleted",
13375        "TimerFired",
13376        "SignalApplied",
13377        "ConditionWaitSatisfied",
13378        "ConditionWaitTimedOut",
13379    ];
13380    let terminal_types: &[&str] = if marker.outcome == "failed" {
13381        &failure_types
13382    } else {
13383        &success_types
13384    };
13385    let mut candidates = Vec::new();
13386    let member_commands = (member.base_sequence
13387        ..member.base_sequence.saturating_add(member.size as u64))
13388        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
13389        .map(|command| (command.sequence(), command))
13390        .collect::<BTreeMap<_, _>>();
13391    let mut resolved_conditions = BTreeSet::new();
13392    for event in state.history_events.iter() {
13393        let Some(sequence) = durable_event_sequence(event) else {
13394            continue;
13395        };
13396        let Some(command) = member_commands.get(&sequence) else {
13397            continue;
13398        };
13399        if !terminal_types.contains(&event.event_type.as_str()) {
13400            continue;
13401        }
13402        if matches!(command, RecordedCommand::ConditionWait { .. }) {
13403            if !matches!(
13404                event.event_type.as_str(),
13405                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
13406            ) && !(event.event_type == "TimerFired"
13407                && event.payload.get("timer_kind").and_then(Value::as_str)
13408                    == Some("condition_timeout"))
13409            {
13410                continue;
13411            }
13412            if !resolved_conditions.insert(sequence) {
13413                continue;
13414            }
13415        }
13416        let event_id = event
13417            .raw
13418            .get("id")
13419            .or_else(|| event.raw.get("event_id"))
13420            .and_then(Value::as_str)
13421            .filter(|value| !value.is_empty())
13422            .ok_or_else(|| {
13423                invalid_recorded_history(
13424                    "selection_resolution_event_id_missing",
13425                    member.base_sequence,
13426                    "terminal selection history with a durable event id",
13427                    &event.payload.to_string(),
13428                    "selection terminal history cannot be bound to its winner marker",
13429                )
13430            })?;
13431        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
13432    }
13433    let resolution = if marker.outcome == "failed" {
13434        candidates.first()
13435    } else {
13436        candidates.last()
13437    };
13438    let Some((event_id, event_type, sequence)) = resolution else {
13439        return Err(invalid_recorded_history(
13440            "selection_resolution_event_missing",
13441            member.base_sequence,
13442            "terminal history for the selected member",
13443            &format!("{:?}", marker.member_key),
13444            "selection winner marker has no matching durable terminal event",
13445        ));
13446    };
13447    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
13448        return Err(invalid_recorded_history(
13449            "selection_resolution_event_mismatch",
13450            member.base_sequence,
13451            &format!("{event_type}:{event_id}"),
13452            &format!(
13453                "{}:{}",
13454                marker.resolution_event_type, marker.resolution_event_id
13455            ),
13456            "selection winner marker does not reference the event that made its member terminal",
13457        ));
13458    }
13459    Ok(*sequence)
13460}
13461
13462fn selection_member_recorded_command(
13463    state: &WorkflowState,
13464    authored_sequence: u64,
13465) -> Option<&RecordedCommand> {
13466    let original = state
13467        .recorded_commands
13468        .iter()
13469        .find(|command| command.sequence() == authored_sequence)?;
13470    let RecordedCommand::ConditionWait {
13471        occurrence_id,
13472        parallel_group_path: Some(_),
13473        ..
13474    } = original
13475    else {
13476        return Some(original);
13477    };
13478    // Decoding proves each physical reopen has the same authored identity and
13479    // group path after a satisfied predecessor. Only its latest wait can make
13480    // this logical member terminal.
13481    state
13482        .recorded_commands
13483        .iter()
13484        .filter(|command| {
13485            matches!(command, RecordedCommand::ConditionWait {
13486                occurrence_id: candidate, ..
13487            } if candidate == occurrence_id)
13488        })
13489        .max_by_key(|command| command.sequence())
13490}
13491
13492fn recorded_selection_member_outcome(
13493    state: &WorkflowState,
13494    handle: &DurableOperationHandle,
13495) -> Result<Option<ParallelResult>> {
13496    for event in state.history_events.iter() {
13497        let Some(sequence) = durable_event_sequence(event) else {
13498            continue;
13499        };
13500        if sequence < handle.base_sequence
13501            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
13502            || !matches!(
13503                event.event_type.as_str(),
13504                "ActivityFailed"
13505                    | "ActivityCancelled"
13506                    | "ActivityTimedOut"
13507                    | "ChildRunFailed"
13508                    | "ChildRunCancelled"
13509                    | "ChildRunTerminated"
13510            )
13511        {
13512            continue;
13513        }
13514        let Some(command) = state
13515            .recorded_commands
13516            .iter()
13517            .find(|command| command.sequence() == sequence)
13518        else {
13519            continue;
13520        };
13521        match command {
13522            RecordedCommand::Activity {
13523                outcome: Some(Err(failure)),
13524                ..
13525            } => return Err(Error::ActivityFailed(failure.clone())),
13526            RecordedCommand::ChildWorkflow {
13527                outcome: Some(Err(failure)),
13528                ..
13529            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
13530            _ => {}
13531        }
13532    }
13533
13534    let mut results = Vec::with_capacity(handle.size);
13535    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13536        let Some(command) = selection_member_recorded_command(state, sequence) else {
13537            return Ok(None);
13538        };
13539        let result = match command {
13540            RecordedCommand::Activity { outcome, .. } => match outcome {
13541                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
13542                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
13543                None => return Ok(None),
13544            },
13545            RecordedCommand::Timer { fired, .. } => {
13546                if !fired {
13547                    return Ok(None);
13548                }
13549                ParallelAvroResult::Timer
13550            }
13551            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
13552                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
13553                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
13554                None => return Ok(None),
13555            },
13556            RecordedCommand::SignalWait { value, .. } => match value {
13557                Some(value) => ParallelAvroResult::Signal(value.clone()),
13558                None => return Ok(None),
13559            },
13560            RecordedCommand::ConditionWait { result, .. } => match result {
13561                Some(result) => ParallelAvroResult::Condition(*result),
13562                None => return Ok(None),
13563            },
13564            other => {
13565                return Err(command_mismatch(
13566                    other,
13567                    format!("selected {} member", handle.kind),
13568                ))
13569            }
13570        };
13571        results.push(result);
13572    }
13573    let mut results = results.into_iter();
13574    parallel_results_for_shape(&handle.shape, &mut results)
13575        .into_json_result()
13576        .map(Some)
13577}
13578
13579fn recorded_selection_member_is_terminal(
13580    state: &WorkflowState,
13581    handle: &DurableOperationHandle,
13582) -> bool {
13583    let mut completed = 0usize;
13584    let mut all_completed = true;
13585    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
13586        let Some(command) = selection_member_recorded_command(state, sequence) else {
13587            all_completed = false;
13588            continue;
13589        };
13590        let terminal = match command {
13591            RecordedCommand::Activity {
13592                outcome: Some(Err(_)),
13593                ..
13594            }
13595            | RecordedCommand::ChildWorkflow {
13596                outcome: Some(Err(_)),
13597                ..
13598            } => return true,
13599            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
13600            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
13601            RecordedCommand::Timer { fired, .. } => *fired,
13602            RecordedCommand::SignalWait { value, .. } => value.is_some(),
13603            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
13604            RecordedCommand::SearchAttributes { .. }
13605            | RecordedCommand::CancellationScope { .. }
13606            | RecordedCommand::SideEffect { .. }
13607            | RecordedCommand::VersionMarker { .. }
13608            | RecordedCommand::Memo { .. }
13609            | RecordedCommand::CancellationBoundary { .. }
13610            | RecordedCommand::CancellationGroup { .. } => false,
13611        };
13612        if !terminal {
13613            all_completed = false;
13614            continue;
13615        }
13616        completed += 1;
13617    }
13618    all_completed && completed == handle.size
13619}
13620
13621fn selection_cancellation_for_handle(
13622    state: &WorkflowState,
13623    handle: &DurableOperationHandle,
13624) -> Result<bool> {
13625    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
13626        recorded.selection_group_id == handle.selection_group_id
13627            && recorded.member_base_sequence == handle.base_sequence
13628    }) else {
13629        return Ok(false);
13630    };
13631    validate_selection_cancellation_marker(marker, handle)?;
13632    Ok(true)
13633}
13634
13635fn validate_selection_cancellations_for_handles(
13636    state: &WorkflowState,
13637    handles: &[DurableOperationHandle],
13638) -> Result<()> {
13639    let Some(group_id) = handles
13640        .first()
13641        .map(|handle| handle.selection_group_id.as_str())
13642    else {
13643        return Ok(());
13644    };
13645    for marker in state
13646        .cancelled_selection_members
13647        .iter()
13648        .filter(|marker| marker.selection_group_id == group_id)
13649    {
13650        let Some(handle) = handles
13651            .iter()
13652            .find(|handle| handle.base_sequence == marker.member_base_sequence)
13653        else {
13654            return Err(invalid_recorded_history(
13655                "selection_cancellation_member_mismatch",
13656                marker.member_base_sequence,
13657                "SelectionOperationCancelled matching an authored selection handle",
13658                &format!("{marker:?}"),
13659                "selection cancellation member base does not name an authored member",
13660            ));
13661        };
13662        validate_selection_cancellation_marker(marker, handle)?;
13663    }
13664    Ok(())
13665}
13666
13667fn validate_selection_cancellation_marker(
13668    marker: &SelectionCancellation,
13669    handle: &DurableOperationHandle,
13670) -> Result<()> {
13671    if marker.selection_group_id != handle.selection_group_id
13672        || marker.member_key != handle.key
13673        || marker.member_index != handle.index
13674        || marker.member_base_sequence != handle.base_sequence
13675        || marker.member_size != handle.size
13676        || marker.operation_kind != handle.kind
13677        || marker.operation_identity != handle.identity
13678    {
13679        return Err(invalid_recorded_history(
13680            "selection_cancellation_member_mismatch",
13681            handle.base_sequence,
13682            "SelectionOperationCancelled matching the authored selection handle",
13683            &format!("{marker:?}"),
13684            "selection cancellation history targets different authored member metadata",
13685        ));
13686    }
13687    Ok(())
13688}
13689
13690/// Future returned by [`DurableOperationHandle::await_result`].
13691pub struct DurableOperationAwaitCall {
13692    handle: DurableOperationHandle,
13693}
13694
13695impl Future for DurableOperationAwaitCall {
13696    type Output = Result<ParallelResult>;
13697
13698    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13699        let mut state = match self.handle.ctx.state.lock() {
13700            Ok(state) => state,
13701            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13702        };
13703        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
13704            return Poll::Ready(Err(error));
13705        }
13706        match state.prepare_selection_handle_cancellation(&self.handle) {
13707            Ok(true) => return Poll::Pending,
13708            Ok(false) => {}
13709            Err(error) => return Poll::Ready(Err(error)),
13710        }
13711        match selection_cancellation_for_handle(&state, &self.handle) {
13712            Err(error) => return Poll::Ready(Err(error)),
13713            Ok(false) => {}
13714            Ok(true) => {
13715                state.advance_cancellation_receipt(
13716                    &self.handle.selection_group_id,
13717                    self.handle.base_sequence,
13718                );
13719                return Poll::Ready(Err(Error::DurableOperationCancelled(
13720                    DurableOperationCancelled {
13721                        selection_group_id: self.handle.selection_group_id.clone(),
13722                        member_key: self.handle.key.clone(),
13723                        member_index: self.handle.index,
13724                        operation_kind: self.handle.kind.clone(),
13725                        operation_identity: self.handle.identity.clone(),
13726                    },
13727                )));
13728            }
13729        }
13730        match recorded_selection_member_outcome(&state, &self.handle) {
13731            Ok(Some(result)) => {
13732                state.advance_cancellation_handle(&self.handle, false);
13733                Poll::Ready(Ok(result))
13734            }
13735            Ok(None) => Poll::Pending,
13736            Err(error) => {
13737                if !workflow_task_integrity_error(&error) {
13738                    state.advance_cancellation_handle(&self.handle, true);
13739                }
13740                Poll::Ready(Err(error))
13741            }
13742        }
13743    }
13744}
13745
13746fn validate_selection_delivery_handle(
13747    state: &WorkflowState,
13748    handle: &DurableOperationHandle,
13749) -> Result<()> {
13750    let path = state
13751        .recorded_commands
13752        .iter()
13753        .find(|command| command.sequence() == handle.base_sequence)
13754        .and_then(|command| match command {
13755            RecordedCommand::Activity {
13756                parallel_group_path,
13757                ..
13758            }
13759            | RecordedCommand::ChildWorkflow {
13760                parallel_group_path,
13761                ..
13762            }
13763            | RecordedCommand::Timer {
13764                parallel_group_path,
13765                ..
13766            }
13767            | RecordedCommand::SignalWait {
13768                parallel_group_path,
13769                ..
13770            }
13771            | RecordedCommand::ConditionWait {
13772                parallel_group_path,
13773                ..
13774            } => parallel_group_path.as_ref(),
13775            _ => None,
13776        })
13777        .and_then(|path| path.first());
13778    let matches = path.is_some_and(|entry| {
13779        entry.parallel_group_mode.as_deref() == Some("select")
13780            && entry.parallel_group_id == handle.selection_group_id
13781            && entry.selection_member_key.as_ref() == Some(&handle.key)
13782            && entry.selection_member_index == Some(handle.index)
13783            && entry.selection_member_base_sequence == Some(handle.base_sequence)
13784            && entry.selection_member_size == Some(handle.size)
13785            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
13786    });
13787    if !matches
13788        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
13789            != handle.identity
13790    {
13791        return Err(invalid_recorded_history(
13792            "cooperative_cancellation_call_mismatch",
13793            handle.base_sequence,
13794            "selection handle matching its authored durable identity",
13795            &format!("{handle:?}"),
13796            "selection handle identity or member metadata changed before cancellation replay",
13797        ));
13798    }
13799    Ok(())
13800}
13801
13802/// Future returned by [`DurableOperationHandle::cancel`].
13803pub struct CancelDurableOperationCall {
13804    handle: DurableOperationHandle,
13805    emitted: bool,
13806}
13807
13808impl Future for CancelDurableOperationCall {
13809    type Output = Result<()>;
13810
13811    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13812        let ctx = self.handle.ctx.clone();
13813        let mut state = match ctx.state.lock() {
13814            Ok(state) => state,
13815            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13816        };
13817        match selection_cancellation_for_handle(&state, &self.handle) {
13818            Err(error) => return Poll::Ready(Err(error)),
13819            Ok(true) => {
13820                state.advance_cancellation_receipt(
13821                    &self.handle.selection_group_id,
13822                    self.handle.base_sequence,
13823                );
13824                return Poll::Ready(Ok(()));
13825            }
13826            Ok(false) => {}
13827        }
13828        if recorded_selection_member_is_terminal(&state, &self.handle) {
13829            return Poll::Ready(Ok(()));
13830        }
13831        if !self.emitted {
13832            state.commands.push(json!({
13833                "type": "cancel_selection_operation",
13834                "selection_group_id": self.handle.selection_group_id,
13835                "member_key": self.handle.key,
13836                "member_index": self.handle.index,
13837                "member_base_sequence": self.handle.base_sequence,
13838                "member_size": self.handle.size,
13839                "operation_kind": self.handle.kind,
13840                "operation_identity": self.handle.identity,
13841            }));
13842            self.emitted = true;
13843        }
13844        // The cancellation command is only a request. Do not expose workflow
13845        // state after cancel until committed SelectionOperationCancelled
13846        // history proves that the request won the race with member completion.
13847        Poll::Pending
13848    }
13849}
13850
13851trait PollNestedResultExt<T> {
13852    fn flatten_result(self) -> Poll<Result<T>>;
13853}
13854
13855impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
13856    fn flatten_result(self) -> Poll<Result<T>> {
13857        match self {
13858            Poll::Ready(Ok(result)) => Poll::Ready(result),
13859            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
13860            Poll::Pending => Poll::Pending,
13861        }
13862    }
13863}
13864
13865struct SagaCompensation {
13866    activity_type: String,
13867    options: ActivityOptions,
13868    arguments: AvroValue,
13869    registration_order: usize,
13870}
13871
13872/// Workflow-local deterministic saga compensation helper.
13873///
13874/// Register each compensation only after its forward step succeeds. Passing
13875/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
13876/// reverse registration order after any failure, including cooperative
13877/// cancellation. Each compensation is an ordinary durable activity, so replay,
13878/// duplicate delivery, and worker restart use existing history semantics.
13879pub struct Saga {
13880    ctx: WorkflowContext,
13881    compensations: Vec<SagaCompensation>,
13882}
13883
13884impl Saga {
13885    fn new(ctx: WorkflowContext) -> Self {
13886        Self {
13887            ctx,
13888            compensations: Vec::new(),
13889        }
13890    }
13891
13892    pub fn add_compensation<T: Serialize>(
13893        &mut self,
13894        activity_type: impl Into<String>,
13895        args: T,
13896    ) -> Result<&mut Self> {
13897        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
13898    }
13899
13900    pub fn add_compensation_with_options<T: Serialize>(
13901        &mut self,
13902        activity_type: impl Into<String>,
13903        options: ActivityOptions,
13904        args: T,
13905    ) -> Result<&mut Self> {
13906        let activity_type = activity_type.into();
13907        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
13908            return Err(Error::Codec(
13909                "saga compensation activity type must be non-empty without surrounding whitespace"
13910                    .to_string(),
13911            ));
13912        }
13913        options.validate().map_err(Error::InvalidActivityOptions)?;
13914        let arguments = AvroValue::from_serialize(&args)?;
13915        let registration_order = self.compensations.len() + 1;
13916        self.compensations.push(SagaCompensation {
13917            activity_type,
13918            options,
13919            arguments,
13920            registration_order,
13921        });
13922        Ok(self)
13923    }
13924
13925    /// Compensate `initiating_failure` and return the failure that must remain.
13926    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
13927        let _shield = match self.ctx.cancellation_shield() {
13928            Ok(shield) => shield,
13929            Err(error) => return error,
13930        };
13931        while let Some(compensation) = self.compensations.pop() {
13932            if let Err(compensation_failure) = self
13933                .ctx
13934                .activity_with_options(
13935                    compensation.activity_type.clone(),
13936                    compensation.options,
13937                    compensation.arguments,
13938                )
13939                .await
13940            {
13941                if workflow_task_integrity_error(&compensation_failure) {
13942                    return compensation_failure;
13943                }
13944                return Error::SagaCompensationFailed(SagaCompensationFailure {
13945                    initiating_failure: Box::new(initiating_failure),
13946                    compensation_failure: Box::new(compensation_failure),
13947                    compensation_activity_type: compensation.activity_type,
13948                    compensation_registration_order: compensation.registration_order,
13949                });
13950            }
13951        }
13952        initiating_failure
13953    }
13954
13955    /// Return a successful forward value or compensate and preserve its failure.
13956    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
13957        match outcome {
13958            Ok(value) => Ok(value),
13959            Err(error) => Err(self.compensate(error).await),
13960        }
13961    }
13962}
13963
13964pub struct ActivityCall {
13965    ctx: WorkflowContext,
13966    activity_type: String,
13967    options: ActivityOptions,
13968    worker_session: Option<WorkerSessionOptions>,
13969    args: Option<Result<AvroValue>>,
13970    scheduled: bool,
13971    local: bool,
13972    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
13973    parallel_group_path: Vec<ParallelGroupMetadata>,
13974}
13975
13976impl ActivityCall {
13977    fn poll_avro_value(
13978        mut self: Pin<&mut Self>,
13979        _cx: &mut TaskContext<'_>,
13980    ) -> Poll<Result<AvroValue>> {
13981        let ctx = self.ctx.clone();
13982        let mut state = match ctx.state.lock() {
13983            Ok(state) => state,
13984            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13985        };
13986
13987        if let Some(result) = &self.local_result {
13988            return match result.lock() {
13989                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
13990                    Poll::Ready(result.map_err(Error::ActivityFailed))
13991                }),
13992                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
13993            };
13994        }
13995        if self.scheduled {
13996            return Poll::Pending;
13997        }
13998
13999        let options = match self.options.validate() {
14000            Ok(options) => options,
14001            Err(error) => {
14002                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
14003            }
14004        };
14005        if self.local {
14006            if self.worker_session.is_some() {
14007                return Poll::Ready(Err(Error::WorkerLoop(
14008                    "local activities cannot use worker-session routing".into(),
14009                )));
14010            }
14011            if let Err(error) = local_activity::validate(&options) {
14012                return Poll::Ready(Err(error));
14013            }
14014        }
14015        let session = match self
14016            .worker_session
14017            .as_ref()
14018            .map(WorkerSessionOptions::to_wire)
14019            .transpose()
14020        {
14021            Ok(value) => value,
14022            Err(error) => return Poll::Ready(Err(error)),
14023        };
14024        let session_queue = session
14025            .as_ref()
14026            .and_then(|session| session["queue"].as_str());
14027        let task_queue = options
14028            .task_queue
14029            .clone()
14030            .or_else(|| session_queue.map(str::to_owned))
14031            .unwrap_or_else(|| state.task_queue.clone());
14032        if session_queue.is_some_and(|queue| queue != task_queue) {
14033            return Poll::Ready(Err(Error::WorkerLoop(
14034                "worker-session queue must match the activity task queue".into(),
14035            )));
14036        }
14037        let current_recorded_options = RecordedActivityOptions {
14038            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
14039            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
14040            retry_policy: current_activity_retry_snapshot(&options),
14041            worker_session: session,
14042        };
14043
14044        let cursor = state.command_cursor;
14045        let call_kind = if self.local {
14046            CancellationCallKind::LocalActivity
14047        } else {
14048            CancellationCallKind::Activity
14049        };
14050        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14051            return Poll::Ready(Err(error));
14052        }
14053        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
14054            Ok(recorded) => recorded,
14055            Err(error) => return Poll::Ready(Err(error)),
14056        };
14057        if let Some(recorded) = recorded {
14058            let sequence = recorded.sequence();
14059            match recorded {
14060                RecordedCommand::Activity {
14061                    activity_type,
14062                    cancellation_policy,
14063                    options: recorded_options,
14064                    outcome,
14065                    parallel_group_path,
14066                    ..
14067                } => {
14068                    let current_policy = options
14069                        .cancellation_policy
14070                        .unwrap_or(CancellationPolicy::TryCancel)
14071                        .as_str();
14072                    if cancellation_policy != current_policy {
14073                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14074                            ReplayFailure::new(
14075                                "activity_cancellation_policy_changed",
14076                                Some(sequence),
14077                                Some(cancellation_policy),
14078                                Some(current_policy.to_string()),
14079                                "Activity cancellation policy changed during replay",
14080                            ),
14081                        )));
14082                    }
14083                    if let Err(error) = ensure_parallel_path_matches(
14084                        sequence,
14085                        parallel_group_path.as_deref(),
14086                        &self.parallel_group_path,
14087                    ) {
14088                        return Poll::Ready(Err(error));
14089                    }
14090                    if let Some(recorded_type) = activity_type {
14091                        if recorded_type != self.activity_type {
14092                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14093                                ReplayFailure::new(
14094                                    "recorded_command_detail_mismatch",
14095                                    Some(sequence),
14096                                    Some(format!("activity:{recorded_type}")),
14097                                    Some(format!("activity:{}", self.activity_type)),
14098                                    "recorded activity type differs from the current workflow command",
14099                                ),
14100                            )));
14101                        }
14102                    }
14103                    if let Some(recorded_options) = recorded_options {
14104                        if recorded_options.worker_session
14105                            != current_recorded_options.worker_session
14106                        {
14107                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14108                                "activity_worker_session_mismatch", Some(sequence),
14109                                Some(activity_options_description(&recorded_options)),
14110                                Some(activity_options_description(&current_recorded_options)),
14111                                "recorded worker-session routing differs from the current activity",
14112                            ))));
14113                        }
14114                        if !recorded_options
14115                            .task_queue
14116                            .matches_current(&current_recorded_options.task_queue)
14117                        {
14118                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14119                                ReplayFailure::new(
14120                                    "activity_task_queue_mismatch",
14121                                    Some(sequence),
14122                                    Some(activity_options_description(&recorded_options)),
14123                                    Some(activity_options_description(&current_recorded_options)),
14124                                    "recorded activity task queue differs from the current workflow command",
14125                                ),
14126                            )));
14127                        }
14128                        if (self.local
14129                            && matches!(
14130                                recorded_options.execution_mode,
14131                                RecordedSnapshotValue::Unknown
14132                            ))
14133                            || !recorded_options
14134                                .execution_mode
14135                                .matches_current(&current_recorded_options.execution_mode)
14136                        {
14137                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14138                                ReplayFailure::new(
14139                                    "activity_execution_mode_mismatch",
14140                                    Some(sequence),
14141                                    Some(activity_options_description(&recorded_options)),
14142                                    Some(activity_options_description(&current_recorded_options)),
14143                                    "recorded activity execution mode differs from the current workflow command",
14144                                ),
14145                            )));
14146                        }
14147                        if !recorded_options
14148                            .retry_policy
14149                            .matches_current(&current_recorded_options.retry_policy)
14150                        {
14151                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14152                                ReplayFailure::new(
14153                                    "activity_retry_policy_mismatch",
14154                                    Some(sequence),
14155                                    Some(activity_options_description(&recorded_options)),
14156                                    Some(activity_options_description(&current_recorded_options)),
14157                                    "recorded activity retry policy differs from the current workflow command",
14158                                ),
14159                            )));
14160                        }
14161                    }
14162                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
14163                        return Poll::Ready(Err(error));
14164                    }
14165                    match state.prepare_scalar_cancellation(
14166                        cursor,
14167                        call_kind,
14168                        &self.parallel_group_path,
14169                    ) {
14170                        Ok(true) => {
14171                            self.scheduled = true;
14172                            return Poll::Pending;
14173                        }
14174                        Ok(false) => {}
14175                        Err(error) => return Poll::Ready(Err(error)),
14176                    }
14177                    state.command_cursor += 1;
14178                    if let Some(outcome) = outcome {
14179                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14180                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
14181                    }
14182                    state.matched_recorded_pending = true;
14183                    self.scheduled = true;
14184                    return Poll::Pending;
14185                }
14186                other => {
14187                    return Poll::Ready(Err(command_mismatch(
14188                        &other,
14189                        format!("activity:{}", self.activity_type),
14190                    )));
14191                }
14192            }
14193        }
14194
14195        if !self.scheduled {
14196            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14197                Ok(args) => args,
14198                Err(error) => return Poll::Ready(Err(error)),
14199            };
14200            let arguments = normalize_avro_arguments(args);
14201            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
14202                Ok(envelope) => envelope,
14203                Err(error) => return Poll::Ready(Err(error)),
14204            };
14205
14206            let mut command = serde_json::Map::from_iter([
14207                (
14208                    "type".to_string(),
14209                    json!(if self.local {
14210                        "record_local_activity"
14211                    } else {
14212                        "schedule_activity"
14213                    }),
14214                ),
14215                (
14216                    "activity_type".to_string(),
14217                    json!(self.activity_type.clone()),
14218                ),
14219                ("queue".to_string(), json!(task_queue)),
14220                ("arguments".to_string(), envelope),
14221            ]);
14222            for (field, value) in [
14223                ("start_to_close_timeout", options.start_to_close_timeout),
14224                (
14225                    "schedule_to_start_timeout",
14226                    options.schedule_to_start_timeout,
14227                ),
14228                (
14229                    "schedule_to_close_timeout",
14230                    options.schedule_to_close_timeout,
14231                ),
14232                ("heartbeat_timeout", options.heartbeat_timeout),
14233            ] {
14234                if let Some(value) = value {
14235                    command.insert(field.to_string(), json!(value));
14236                }
14237            }
14238            if let Some(retry_policy) = &options.retry_policy {
14239                command.insert("retry_policy".to_string(), retry_policy.clone());
14240            }
14241            if let Some(policy) = options.cancellation_policy {
14242                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
14243            }
14244            if let Some(session) = current_recorded_options.worker_session {
14245                command.insert("worker_session".into(), session);
14246            }
14247            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14248            ctx.apply_scope_membership(&mut command);
14249            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
14250                Ok(true) => {
14251                    self.scheduled = true;
14252                    return Poll::Pending;
14253                }
14254                Ok(false) => {}
14255                Err(error) => return Poll::Ready(Err(error)),
14256            }
14257            if self.local {
14258                command.remove("queue");
14259                command.insert("execution_mode".into(), json!("local"));
14260                let result = Arc::new(Mutex::new(None));
14261                let command_index = state.commands.len();
14262                state.local_activity_requests.push(local_activity::Request {
14263                    command_index,
14264                    options,
14265                    arguments,
14266                    result: result.clone(),
14267                });
14268                self.local_result = Some(result);
14269            }
14270            state.commands.push(Value::Object(command));
14271            self.scheduled = true;
14272        }
14273
14274        Poll::Pending
14275    }
14276}
14277
14278impl Future for ActivityCall {
14279    type Output = Result<Value>;
14280
14281    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14282        match self.poll_avro_value(cx) {
14283            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
14284            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14285            Poll::Pending => Poll::Pending,
14286        }
14287    }
14288}
14289
14290/// Future returned by [`WorkflowContext::sleep`].
14291pub struct TimerCall {
14292    ctx: WorkflowContext,
14293    delay_seconds: Option<u64>,
14294    scheduled: bool,
14295    matched_pending: bool,
14296    parallel_group_path: Vec<ParallelGroupMetadata>,
14297}
14298
14299impl Future for TimerCall {
14300    type Output = Result<()>;
14301
14302    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14303        if self.matched_pending {
14304            return Poll::Pending;
14305        }
14306
14307        let ctx = self.ctx.clone();
14308        let Some(requested_delay) = self.delay_seconds else {
14309            return Poll::Ready(Err(Error::TimerDurationOverflow));
14310        };
14311        let mut state = match ctx.state.lock() {
14312            Ok(state) => state,
14313            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14314        };
14315
14316        let cursor = state.command_cursor;
14317        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14318            return Poll::Ready(Err(error));
14319        }
14320        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
14321        {
14322            Ok(recorded) => recorded,
14323            Err(error) => return Poll::Ready(Err(error)),
14324        };
14325        if let Some(recorded) = recorded {
14326            match recorded {
14327                RecordedCommand::Timer {
14328                    sequence,
14329                    delay_seconds,
14330                    fired,
14331                    parallel_group_path,
14332                    ..
14333                } => {
14334                    if let Err(error) =
14335                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
14336                    {
14337                        return Poll::Ready(Err(error));
14338                    }
14339                    if let Err(error) = ensure_parallel_path_matches(
14340                        sequence,
14341                        parallel_group_path.as_deref(),
14342                        &self.parallel_group_path,
14343                    ) {
14344                        return Poll::Ready(Err(error));
14345                    }
14346                    if delay_seconds != requested_delay {
14347                        return Poll::Ready(Err(Error::NonDeterministicReplay(
14348                            ReplayFailure::new(
14349                                "timer_delay_mismatch",
14350                                Some(sequence),
14351                                Some(format!("timer:{delay_seconds}s")),
14352                                Some(format!("timer:{requested_delay}s")),
14353                                "recorded timer delay differs from the current workflow command",
14354                            ),
14355                        )));
14356                    }
14357                    if let Err(error) =
14358                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
14359                    {
14360                        return Poll::Ready(Err(error));
14361                    }
14362                    match state.prepare_scalar_cancellation(
14363                        cursor,
14364                        CancellationCallKind::Timer,
14365                        &self.parallel_group_path,
14366                    ) {
14367                        Ok(true) => {
14368                            self.scheduled = true;
14369                            self.matched_pending = true;
14370                            return Poll::Pending;
14371                        }
14372                        Ok(false) => {}
14373                        Err(error) => return Poll::Ready(Err(error)),
14374                    }
14375                    state.command_cursor += 1;
14376                    if fired {
14377                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14378                        return Poll::Ready(Ok(()));
14379                    }
14380                    state.matched_recorded_pending = true;
14381                    self.scheduled = true;
14382                    self.matched_pending = true;
14383                    return Poll::Pending;
14384                }
14385                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
14386            }
14387        }
14388
14389        if !self.scheduled {
14390            let mut command = serde_json::Map::from_iter([
14391                ("type".to_string(), json!("start_timer")),
14392                ("delay_seconds".to_string(), json!(requested_delay)),
14393            ]);
14394            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
14395                Ok(Some(proof)) => {
14396                    command.insert("cancellation_cleanup".into(), proof);
14397                }
14398                Ok(None) => {}
14399                Err(error) => return Poll::Ready(Err(error)),
14400            }
14401            apply_parallel_group_path(&mut command, &self.parallel_group_path);
14402            ctx.apply_scope_membership(&mut command);
14403            match state.prepare_scalar_cancellation(
14404                cursor,
14405                CancellationCallKind::Timer,
14406                &self.parallel_group_path,
14407            ) {
14408                Ok(true) => {
14409                    self.scheduled = true;
14410                    self.matched_pending = true;
14411                    return Poll::Pending;
14412                }
14413                Ok(false) => {}
14414                Err(error) => return Poll::Ready(Err(error)),
14415            }
14416            state.commands.push(Value::Object(command));
14417            self.scheduled = true;
14418        }
14419
14420        Poll::Pending
14421    }
14422}
14423
14424/// Future returned by [`WorkflowContext::wait_condition`].
14425pub struct ConditionWaitCall {
14426    ctx: WorkflowContext,
14427    options: ConditionWaitOptions,
14428    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
14429    occurrence_id: Option<String>,
14430    opened_wait: bool,
14431    parallel_group_path: Vec<ParallelGroupMetadata>,
14432}
14433
14434impl Future for ConditionWaitCall {
14435    type Output = Result<ConditionWaitResult>;
14436
14437    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14438        if self.opened_wait {
14439            return Poll::Pending;
14440        }
14441
14442        let options = match self.options.validate() {
14443            Ok(options) => options,
14444            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
14445        };
14446        let ctx = self.ctx.clone();
14447        let occurrence_id = match self.occurrence_id.as_ref() {
14448            Some(occurrence_id) => occurrence_id.clone(),
14449            None => {
14450                let mut state = match ctx.state.lock() {
14451                    Ok(state) => state,
14452                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14453                };
14454                let ordinal = state.condition_wait_occurrence_counter;
14455                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
14456                    Some(next) => next,
14457                    None => {
14458                        return Poll::Ready(Err(Error::WorkerLoop(
14459                            "condition wait occurrence counter overflowed".to_string(),
14460                        )))
14461                    }
14462                };
14463                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
14464                drop(state);
14465                self.occurrence_id = Some(occurrence_id.clone());
14466                occurrence_id
14467            }
14468        };
14469
14470        let recorded_result = {
14471            let mut state = match ctx.state.lock() {
14472                Ok(state) => state,
14473                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14474            };
14475            let initial_cursor = state.command_cursor;
14476            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
14477                return Poll::Ready(Err(error));
14478            }
14479            let recorded = match state
14480                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
14481            {
14482                Ok(recorded) => recorded,
14483                Err(error) => return Poll::Ready(Err(error)),
14484            };
14485            let Some(recorded) = recorded else {
14486                drop(state);
14487                return self.poll_new_condition(options);
14488            };
14489            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
14490                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
14491            }
14492
14493            let mut cursor = state.command_cursor;
14494            let mut result = None;
14495            let mut pending_delivery = false;
14496            loop {
14497                if cursor > initial_cursor
14498                    && matches!(
14499                        state.recorded_commands.get(cursor),
14500                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
14501                    )
14502                {
14503                    break;
14504                }
14505                let recorded = match state
14506                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
14507                {
14508                    Ok(recorded) => recorded,
14509                    Err(error) => return Poll::Ready(Err(error)),
14510                };
14511                let Some(RecordedCommand::ConditionWait {
14512                    sequence,
14513                    occurrence_id: ref recorded_occurrence_id,
14514                    ref condition_key,
14515                    ref predicate_identity,
14516                    timeout_seconds,
14517                    result: recorded_result,
14518                    ref parallel_group_path,
14519                    ..
14520                }) = recorded
14521                else {
14522                    break;
14523                };
14524
14525                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
14526                    break;
14527                }
14528                if let Err(error) = ensure_parallel_path_matches(
14529                    sequence,
14530                    parallel_group_path.as_deref(),
14531                    &self.parallel_group_path,
14532                ) {
14533                    return Poll::Ready(Err(error));
14534                }
14535                if let Err(error) = validate_recorded_condition_wait(
14536                    sequence,
14537                    recorded_occurrence_id,
14538                    condition_key.as_deref(),
14539                    predicate_identity,
14540                    timeout_seconds,
14541                    &occurrence_id,
14542                    &options,
14543                ) {
14544                    return Poll::Ready(Err(error));
14545                }
14546                if result == Some(ConditionWaitResult::TimedOut) {
14547                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
14548                        "condition_wait_reopened_after_timeout",
14549                        Some(sequence),
14550                        Some("timed-out condition is terminal".to_string()),
14551                        Some("another physical wait-open".to_string()),
14552                        "condition history reopened one logical wait after its durable timeout",
14553                    ))));
14554                }
14555                if let Err(error) =
14556                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
14557                {
14558                    return Poll::Ready(Err(error));
14559                }
14560                match state.prepare_scalar_cancellation(
14561                    cursor,
14562                    CancellationCallKind::Condition,
14563                    &self.parallel_group_path,
14564                ) {
14565                    Ok(pending) => pending_delivery |= pending,
14566                    Err(error) => return Poll::Ready(Err(error)),
14567                }
14568                result = recorded_result;
14569                if result.is_some() {
14570                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14571                }
14572                cursor += 1;
14573            }
14574            state.command_cursor = cursor;
14575            if pending_delivery {
14576                self.opened_wait = true;
14577                return Poll::Pending;
14578            }
14579            result
14580        };
14581
14582        if let Some(result) = recorded_result {
14583            return Poll::Ready(Ok(result));
14584        }
14585
14586        self.poll_open_condition(options, true)
14587    }
14588}
14589
14590impl ConditionWaitCall {
14591    fn poll_new_condition(
14592        self: Pin<&mut Self>,
14593        options: ValidatedConditionWaitOptions,
14594    ) -> Poll<Result<ConditionWaitResult>> {
14595        self.poll_open_condition(options, false)
14596    }
14597
14598    fn poll_open_condition(
14599        mut self: Pin<&mut Self>,
14600        options: ValidatedConditionWaitOptions,
14601        recorded_wait: bool,
14602    ) -> Poll<Result<ConditionWaitResult>> {
14603        {
14604            let ctx = self.ctx.clone();
14605            let mut state = match ctx.state.lock() {
14606                Ok(state) => state,
14607                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14608            };
14609            let cursor = state.command_cursor;
14610            match state.prepare_scalar_cancellation(
14611                cursor,
14612                CancellationCallKind::Condition,
14613                &self.parallel_group_path,
14614            ) {
14615                Ok(true) => {
14616                    self.opened_wait = true;
14617                    return Poll::Pending;
14618                }
14619                Ok(false) => {}
14620                Err(error) => return Poll::Ready(Err(error)),
14621            }
14622        }
14623        let selection_member = self
14624            .parallel_group_path
14625            .first()
14626            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
14627        match (self.predicate)() {
14628            Ok(true) if !selection_member || recorded_wait => {
14629                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
14630            }
14631            Ok(_) => {}
14632            Err(error) => return Poll::Ready(Err(error)),
14633        }
14634        if options.timeout_seconds == Some(0) && !selection_member {
14635            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
14636        }
14637
14638        let ctx = self.ctx.clone();
14639        let mut state = match ctx.state.lock() {
14640            Ok(state) => state,
14641            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14642        };
14643        let mut command = serde_json::Map::from_iter([
14644            ("type".to_string(), json!("open_condition_wait")),
14645            (
14646                "condition_wait_occurrence_id".to_string(),
14647                json!(self.occurrence_id.as_deref().unwrap_or_default()),
14648            ),
14649            ("condition_key".to_string(), json!(options.condition_key)),
14650            (
14651                "condition_definition_fingerprint".to_string(),
14652                json!(options.predicate_identity),
14653            ),
14654        ]);
14655        if let Some(timeout_seconds) = options.timeout_seconds {
14656            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
14657        }
14658        apply_parallel_group_path(&mut command, &self.parallel_group_path);
14659        ctx.apply_scope_membership(&mut command);
14660        state.commands.push(Value::Object(command));
14661        drop(state);
14662        self.opened_wait = true;
14663        Poll::Pending
14664    }
14665}
14666
14667fn validate_recorded_condition_wait(
14668    sequence: u64,
14669    recorded_occurrence_id: &str,
14670    recorded_key: Option<&str>,
14671    recorded_predicate_identity: &str,
14672    recorded_timeout_seconds: Option<u64>,
14673    current_occurrence_id: &str,
14674    current: &ValidatedConditionWaitOptions,
14675) -> Result<()> {
14676    if recorded_occurrence_id != current_occurrence_id {
14677        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14678            "condition_wait_occurrence_mismatch",
14679            Some(sequence),
14680            Some(recorded_occurrence_id.to_string()),
14681            Some(current_occurrence_id.to_string()),
14682            "recorded condition occurrence differs from the current authored wait position",
14683        )));
14684    }
14685    if recorded_key != Some(current.condition_key.as_str()) {
14686        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14687            "condition_wait_key_mismatch",
14688            Some(sequence),
14689            recorded_key.map(str::to_string),
14690            Some(current.condition_key.clone()),
14691            "recorded condition identity differs from the current workflow wait",
14692        )));
14693    }
14694    if recorded_predicate_identity != current.predicate_identity {
14695        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14696            "condition_wait_predicate_mismatch",
14697            Some(sequence),
14698            Some(recorded_predicate_identity.to_string()),
14699            Some(current.predicate_identity.clone()),
14700            "recorded condition predicate behavior differs from current workflow code",
14701        )));
14702    }
14703    if recorded_timeout_seconds != current.timeout_seconds {
14704        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14705            "condition_wait_timeout_mismatch",
14706            Some(sequence),
14707            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
14708            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
14709            "recorded condition timeout differs from the current workflow wait",
14710        )));
14711    }
14712    Ok(())
14713}
14714
14715/// Future returned by [`WorkflowContext::start_child_workflow`].
14716pub struct ChildWorkflowCall {
14717    ctx: WorkflowContext,
14718    workflow_type: String,
14719    options: ChildWorkflowOptions,
14720    args: Option<Result<AvroValue>>,
14721    scheduled: bool,
14722    matched_pending: bool,
14723    parallel_group_path: Vec<ParallelGroupMetadata>,
14724}
14725
14726impl ChildWorkflowCall {
14727    fn poll_avro_value(
14728        mut self: Pin<&mut Self>,
14729        _cx: &mut TaskContext<'_>,
14730    ) -> Poll<Result<ChildWorkflowAvroResult>> {
14731        if self.matched_pending {
14732            return Poll::Pending;
14733        }
14734
14735        let ctx = self.ctx.clone();
14736        let mut state = match ctx.state.lock() {
14737            Ok(state) => state,
14738            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14739        };
14740
14741        let cursor = state.command_cursor;
14742        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14743            return Poll::Ready(Err(error));
14744        }
14745        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
14746        {
14747            Ok(recorded) => recorded,
14748            Err(error) => return Poll::Ready(Err(error)),
14749        };
14750        if let Some(recorded) = recorded {
14751            let sequence = recorded.sequence();
14752            match recorded {
14753                RecordedCommand::ChildWorkflow {
14754                    workflow_type,
14755                    policies,
14756                    outcome,
14757                    parallel_group_path,
14758                    ..
14759                } => {
14760                    if let Err(error) = ensure_parallel_path_matches(
14761                        sequence,
14762                        parallel_group_path.as_deref(),
14763                        &self.parallel_group_path,
14764                    ) {
14765                        return Poll::Ready(Err(error));
14766                    }
14767                    if let Some(recorded_type) = workflow_type {
14768                        if recorded_type != self.workflow_type {
14769                            return Poll::Ready(Err(Error::NonDeterministicReplay(
14770                                ReplayFailure::new(
14771                                    "recorded_command_detail_mismatch",
14772                                    Some(sequence),
14773                                    Some(format!("child workflow:{recorded_type}")),
14774                                    Some(format!("child workflow:{}", self.workflow_type)),
14775                                    "recorded child workflow type differs from the current workflow command",
14776                                ),
14777                            )));
14778                        }
14779                    }
14780                    if let Err(error) =
14781                        ensure_child_policies_match(sequence, &policies, &self.options)
14782                    {
14783                        return Poll::Ready(Err(error));
14784                    }
14785                    if let Err(error) =
14786                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
14787                    {
14788                        return Poll::Ready(Err(error));
14789                    }
14790                    match state.prepare_scalar_cancellation(
14791                        cursor,
14792                        CancellationCallKind::Child,
14793                        &self.parallel_group_path,
14794                    ) {
14795                        Ok(true) => {
14796                            self.scheduled = true;
14797                            self.matched_pending = true;
14798                            return Poll::Pending;
14799                        }
14800                        Ok(false) => {}
14801                        Err(error) => return Poll::Ready(Err(error)),
14802                    }
14803                    state.command_cursor += 1;
14804                    if let Some(outcome) = outcome {
14805                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
14806                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
14807                    }
14808                    state.matched_recorded_pending = true;
14809                    self.scheduled = true;
14810                    self.matched_pending = true;
14811                    return Poll::Pending;
14812                }
14813                other => {
14814                    return Poll::Ready(Err(command_mismatch(
14815                        &other,
14816                        format!("child workflow:{}", self.workflow_type),
14817                    )));
14818                }
14819            }
14820        }
14821
14822        if !self.scheduled {
14823            if self.options.task_queue.trim().is_empty() {
14824                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14825                    "task_queue must not be empty".to_string(),
14826                )));
14827            }
14828            for (name, value) in [
14829                (
14830                    "execution_timeout_seconds",
14831                    self.options.execution_timeout_seconds,
14832                ),
14833                ("run_timeout_seconds", self.options.run_timeout_seconds),
14834            ] {
14835                if value == Some(0) {
14836                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
14837                        "{name} must be at least 1"
14838                    ))));
14839                }
14840            }
14841
14842            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
14843                Ok(args) => args,
14844                Err(error) => return Poll::Ready(Err(error)),
14845            };
14846            let arguments = match encode_typed_envelope(
14847                &normalize_avro_arguments(args),
14848                &state.payload_codec,
14849            ) {
14850                Ok(arguments) => arguments,
14851                Err(error) => return Poll::Ready(Err(error)),
14852            };
14853            let mut command = json!({
14854                "type": "start_child_workflow",
14855                "workflow_type": self.workflow_type,
14856                "queue": self.options.task_queue,
14857                "parent_close_policy": self.options.parent_close_policy.as_str(),
14858                "arguments": arguments,
14859            });
14860            let object = command
14861                .as_object_mut()
14862                .expect("child workflow command is always an object");
14863            if self.options.cancellation_policy != CancellationPolicy::Abandon {
14864                object.insert(
14865                    "cancellation_policy".to_string(),
14866                    json!(self.options.cancellation_policy.as_str()),
14867                );
14868            }
14869            if let Some(policy) = &self.options.retry_policy {
14870                let mut retry_policy = serde_json::Map::new();
14871                if let Some(max_attempts) = policy.max_attempts {
14872                    if max_attempts == 0 {
14873                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14874                            "retry_policy.max_attempts must be at least 1".to_string(),
14875                        )));
14876                    }
14877                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
14878                }
14879                if !policy.backoff_seconds.is_empty() {
14880                    retry_policy
14881                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
14882                }
14883                if !policy.non_retryable_error_types.is_empty() {
14884                    retry_policy.insert(
14885                        "non_retryable_error_types".to_string(),
14886                        json!(policy.non_retryable_error_types),
14887                    );
14888                }
14889                if retry_policy.is_empty() {
14890                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
14891                        "retry_policy must configure at least one field".to_string(),
14892                    )));
14893                }
14894                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
14895            }
14896            if let Some(seconds) = self.options.execution_timeout_seconds {
14897                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
14898            }
14899            if let Some(seconds) = self.options.run_timeout_seconds {
14900                object.insert("run_timeout_seconds".to_string(), json!(seconds));
14901            }
14902            apply_parallel_group_path(object, &self.parallel_group_path);
14903            ctx.apply_scope_membership(object);
14904            match state.prepare_scalar_cancellation(
14905                cursor,
14906                CancellationCallKind::Child,
14907                &self.parallel_group_path,
14908            ) {
14909                Ok(true) => {
14910                    self.scheduled = true;
14911                    self.matched_pending = true;
14912                    return Poll::Pending;
14913                }
14914                Ok(false) => {}
14915                Err(error) => return Poll::Ready(Err(error)),
14916            }
14917            state.commands.push(command);
14918            self.scheduled = true;
14919        }
14920
14921        Poll::Pending
14922    }
14923}
14924
14925impl Future for ChildWorkflowCall {
14926    type Output = Result<ChildWorkflowResult>;
14927
14928    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14929        match self.poll_avro_value(cx) {
14930            Poll::Ready(Ok(result)) => match result.result.into_json() {
14931                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
14932                    parent: result.parent,
14933                    child: result.child,
14934                    child_workflow_type: result.child_workflow_type,
14935                    result: projected,
14936                })),
14937                Err(error) => Poll::Ready(Err(error)),
14938            },
14939            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14940            Poll::Pending => Poll::Pending,
14941        }
14942    }
14943}
14944
14945fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
14946    Error::NonDeterministicReplay(ReplayFailure::new(
14947        "recorded_command_mismatch",
14948        Some(recorded.sequence()),
14949        Some(recorded.shape().to_string()),
14950        Some(actual.into()),
14951        "current workflow command does not match the recorded durable command sequence",
14952    ))
14953}
14954
14955pub struct SignalCall {
14956    ctx: WorkflowContext,
14957    signal_name: String,
14958    runtime_reserved_allowed: bool,
14959    opened_wait: bool,
14960    matched_pending: bool,
14961    parallel_group_path: Vec<ParallelGroupMetadata>,
14962}
14963
14964impl SignalCall {
14965    fn poll_avro_value(
14966        mut self: Pin<&mut Self>,
14967        _cx: &mut TaskContext<'_>,
14968    ) -> Poll<Result<Vec<AvroValue>>> {
14969        if self.matched_pending {
14970            return Poll::Pending;
14971        }
14972        if !self.runtime_reserved_allowed {
14973            if let Err(error) = validate_user_signal_name(&self.signal_name) {
14974                return Poll::Ready(Err(error));
14975            }
14976        }
14977
14978        let ctx = self.ctx.clone();
14979        let mut state = match ctx.state.lock() {
14980            Ok(state) => state,
14981            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14982        };
14983
14984        let cursor = state.command_cursor;
14985        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
14986            return Poll::Ready(Err(error));
14987        }
14988        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
14989        {
14990            Ok(recorded) => recorded,
14991            Err(error) => return Poll::Ready(Err(error)),
14992        };
14993        if let Some(recorded) = recorded {
14994            match recorded {
14995                RecordedCommand::SignalWait {
14996                    sequence,
14997                    signal_name,
14998                    value,
14999                    parallel_group_path,
15000                } => {
15001                    if let Err(error) = ensure_parallel_path_matches(
15002                        sequence,
15003                        parallel_group_path.as_deref(),
15004                        &self.parallel_group_path,
15005                    ) {
15006                        return Poll::Ready(Err(error));
15007                    }
15008                    if signal_name != self.signal_name {
15009                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15010                            ReplayFailure::new(
15011                                "recorded_command_detail_mismatch",
15012                                Some(sequence),
15013                                Some(format!("signal wait:{signal_name}")),
15014                                Some(format!("signal wait:{}", self.signal_name)),
15015                                "recorded signal name differs from the current workflow command",
15016                            ),
15017                        )));
15018                    }
15019
15020                    if let Err(error) =
15021                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
15022                    {
15023                        return Poll::Ready(Err(error));
15024                    }
15025                    match state.prepare_scalar_cancellation(
15026                        cursor,
15027                        CancellationCallKind::Signal,
15028                        &self.parallel_group_path,
15029                    ) {
15030                        Ok(true) => {
15031                            self.opened_wait = true;
15032                            self.matched_pending = true;
15033                            return Poll::Pending;
15034                        }
15035                        Ok(false) => {}
15036                        Err(error) => return Poll::Ready(Err(error)),
15037                    }
15038                    state.command_cursor += 1;
15039                    if let Some(value) = value {
15040                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15041                        return Poll::Ready(Ok(value));
15042                    }
15043                    if state
15044                        .resume_signal
15045                        .as_ref()
15046                        .is_some_and(|signal| signal.signal_name == self.signal_name)
15047                    {
15048                        let signal = state
15049                            .resume_signal
15050                            .take()
15051                            .expect("matching resume signal is present");
15052                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
15053                        return Poll::Ready(Ok(signal.arguments));
15054                    }
15055
15056                    state.matched_recorded_pending = true;
15057                    self.opened_wait = true;
15058                    self.matched_pending = true;
15059                    return Poll::Pending;
15060                }
15061                other => {
15062                    return Poll::Ready(Err(command_mismatch(
15063                        &other,
15064                        format!("signal wait:{}", self.signal_name),
15065                    )));
15066                }
15067            }
15068        }
15069
15070        match state.prepare_scalar_cancellation(
15071            cursor,
15072            CancellationCallKind::Signal,
15073            &self.parallel_group_path,
15074        ) {
15075            Ok(true) => {
15076                self.opened_wait = true;
15077                self.matched_pending = true;
15078                return Poll::Pending;
15079            }
15080            Ok(false) => {}
15081            Err(error) => return Poll::Ready(Err(error)),
15082        }
15083
15084        if state
15085            .resume_signal
15086            .as_ref()
15087            .is_some_and(|signal| signal.signal_name == self.signal_name)
15088        {
15089            let signal = state
15090                .resume_signal
15091                .take()
15092                .expect("matching resume signal is present");
15093            state.unavailable_cancellation_boundary(&self.parallel_group_path);
15094            return Poll::Ready(Ok(signal.arguments));
15095        }
15096
15097        if !self.opened_wait {
15098            let mut command = serde_json::Map::from_iter([
15099                ("type".to_string(), json!("open_signal_wait")),
15100                ("signal_name".to_string(), json!(self.signal_name)),
15101            ]);
15102            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15103            ctx.apply_scope_membership(&mut command);
15104            state.commands.push(Value::Object(command));
15105            self.opened_wait = true;
15106        }
15107
15108        Poll::Pending
15109    }
15110}
15111
15112impl Future for SignalCall {
15113    type Output = Result<Vec<Value>>;
15114
15115    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15116        match self.poll_avro_value(cx) {
15117            Poll::Ready(Ok(values)) => Poll::Ready(
15118                values
15119                    .into_iter()
15120                    .map(AvroValue::into_json)
15121                    .collect::<Result<Vec<_>>>(),
15122            ),
15123            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15124            Poll::Pending => Poll::Pending,
15125        }
15126    }
15127}
15128
15129#[derive(Clone, Debug)]
15130pub struct ActivityContext {
15131    client: Client,
15132    pub task_id: String,
15133    pub activity_attempt_id: String,
15134    pub lease_owner: String,
15135    pub activity_type: String,
15136    pub attempt_number: u64,
15137    pub task_queue: String,
15138    pub worker_id: String,
15139    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
15140    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
15141    worker_session: Option<WorkerSession>,
15142}
15143
15144impl ActivityContext {
15145    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
15146        if let Some(heartbeats) = &self.local_heartbeats {
15147            return heartbeats
15148                .lock()
15149                .map_err(|_| Error::WorkflowStatePoisoned)?
15150                .record(details);
15151        }
15152        if let Some(guard) = &self.claim_guard {
15153            return guard.heartbeat(self, details).await;
15154        }
15155        if let Some(session) = &self.worker_session {
15156            if !session.active() {
15157                return Err(Error::ActivityExecutionAbandoned(
15158                    "worker-session lease or TTL is no longer active".into(),
15159                ));
15160            }
15161            let result = self
15162                .client
15163                .heartbeat_activity_task_value(
15164                    &self.task_id,
15165                    &self.activity_attempt_id,
15166                    &self.lease_owner,
15167                    details,
15168                )
15169                .await;
15170            return worker_session::settle_activity_heartbeat(
15171                session,
15172                result,
15173                &self.task_id,
15174                &self.activity_attempt_id,
15175                &self.lease_owner,
15176            );
15177        }
15178        self.client
15179            .heartbeat_activity_task(
15180                &self.task_id,
15181                &self.activity_attempt_id,
15182                &self.lease_owner,
15183                details,
15184            )
15185            .await
15186    }
15187}
15188
15189fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
15190    validate_payload_codec(codec)?;
15191    match value {
15192        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
15193            value, codec,
15194        )?)),
15195        None => Ok(AvroValue::Array(Vec::new())),
15196    }
15197}
15198
15199fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
15200    let Some(signal_name) = task
15201        .signal_name
15202        .as_deref()
15203        .filter(|value| !value.is_empty())
15204    else {
15205        return Ok(None);
15206    };
15207    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
15208    let AvroValue::Array(arguments) = decoded else {
15209        unreachable!("normalize_avro_arguments always returns an array");
15210    };
15211
15212    Ok(Some(ResumeSignal {
15213        signal_name: signal_name.to_string(),
15214        arguments,
15215    }))
15216}
15217
15218fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
15219    validate_payload_codec(&task.payload_codec)?;
15220    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
15221    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
15222    for event in &task.history_events {
15223        validate_history_event_payloads(event, &task.payload_codec)?;
15224    }
15225    Ok(())
15226}
15227
15228fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
15229    validate_payload_codec(&task.payload_codec)?;
15230    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
15231}
15232
15233fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
15234    validate_payload_codec(&task.payload_codec)?;
15235    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
15236    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
15237    for event in &task.history_events {
15238        validate_history_event_payloads(event, &task.payload_codec)?;
15239    }
15240
15241    let Some(export) = task.history_export.as_ref() else {
15242        return Ok(());
15243    };
15244    let export_codec = match export.get("payloads") {
15245        Some(payloads) => declared_payload_codec(payloads, "codec")?,
15246        None => None,
15247    }
15248    .unwrap_or(&task.payload_codec);
15249    validate_payload_codec(export_codec)?;
15250
15251    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
15252        for event in events {
15253            let event_type = event
15254                .get("event_type")
15255                .or_else(|| event.get("type"))
15256                .and_then(Value::as_str)
15257                .unwrap_or_default();
15258            if let Some(payload) = event.get("payload") {
15259                validate_history_payloads(event_type, payload, export_codec)?;
15260            }
15261        }
15262    }
15263    for signal in export
15264        .get("signals")
15265        .and_then(Value::as_array)
15266        .into_iter()
15267        .flatten()
15268    {
15269        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
15270        validate_payload_codec(codec)?;
15271        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
15272    }
15273    for activity in export
15274        .get("activities")
15275        .and_then(Value::as_array)
15276        .into_iter()
15277        .flatten()
15278    {
15279        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
15280        validate_payload_codec(codec)?;
15281        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
15282        validate_optional_inbound_payload(activity.get("result"), codec)?;
15283    }
15284    Ok(())
15285}
15286
15287fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
15288    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
15289}
15290
15291fn validate_history_payloads(
15292    event_type: &str,
15293    payload: &Value,
15294    fallback_codec: &str,
15295) -> Result<()> {
15296    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
15297    validate_payload_codec(codec)?;
15298    for field in history_payload_fields(event_type) {
15299        validate_optional_inbound_payload(payload.get(*field), codec)?;
15300    }
15301    Ok(())
15302}
15303
15304const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
15305
15306fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
15307    match event_type {
15308        "ActivityCompleted" => &["result"],
15309        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
15310        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
15311        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
15312        "ChildRunCompleted" => &["result", "output"],
15313        "WorkflowCompleted" => &["output"],
15314        "ServiceCallStarted"
15315        | "ServiceCallCompleted"
15316        | "ServiceCallFailed"
15317        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
15318        _ => &[],
15319    }
15320}
15321
15322fn signal_history_payload(payload: &Value) -> Option<&Value> {
15323    SIGNAL_HISTORY_PAYLOAD_FIELDS
15324        .iter()
15325        .find_map(|field| payload.get(*field))
15326}
15327
15328fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
15329    match value.get(field) {
15330        None => Ok(None),
15331        Some(Value::String(codec)) => Ok(Some(codec)),
15332        Some(_) => Err(invalid_payload_envelope()),
15333    }
15334}
15335
15336fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
15337    validate_payload_codec(codec)?;
15338    if let Some(value) = value.filter(|value| !value.is_null()) {
15339        decode_wire_avro_value(value, codec)?;
15340    }
15341    Ok(())
15342}
15343
15344fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
15345    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
15346        invalid_recorded_history(
15347            "parallel_group_metadata_invalid",
15348            sequence,
15349            "non-empty parallel_group_id",
15350            &payload.to_string(),
15351            "parallel-group history is missing its stable identity",
15352        )
15353    })?;
15354    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
15355        invalid_recorded_history(
15356            "parallel_group_metadata_invalid",
15357            sequence,
15358            "activity, child, timer, signal, condition, or mixed group kind",
15359            &payload.to_string(),
15360            "parallel-group history is missing its group kind",
15361        )
15362    })?;
15363    if !matches!(
15364        kind.as_str(),
15365        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
15366    ) {
15367        return Err(invalid_recorded_history(
15368            "parallel_group_metadata_invalid",
15369            sequence,
15370            "activity, child, timer, signal, condition, or mixed group kind",
15371            &kind,
15372            "parallel-group history contains an unsupported group kind",
15373        ));
15374    }
15375    let base_sequence = payload
15376        .get("parallel_group_base_sequence")
15377        .and_then(value_as_u64)
15378        .filter(|value| *value > 0)
15379        .ok_or_else(|| {
15380            invalid_recorded_history(
15381                "parallel_group_metadata_invalid",
15382                sequence,
15383                "positive parallel_group_base_sequence",
15384                &payload.to_string(),
15385                "parallel-group history contains an invalid base sequence",
15386            )
15387        })?;
15388    let size = payload
15389        .get("parallel_group_size")
15390        .and_then(value_as_u64)
15391        .and_then(|value| usize::try_from(value).ok())
15392        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
15393        .ok_or_else(|| {
15394            invalid_recorded_history(
15395                "parallel_group_metadata_invalid",
15396                sequence,
15397                "bounded positive parallel_group_size",
15398                &payload.to_string(),
15399                "parallel-group history contains an invalid group size",
15400            )
15401        })?;
15402    let index = payload
15403        .get("parallel_group_index")
15404        .and_then(value_as_u64)
15405        .and_then(|value| usize::try_from(value).ok())
15406        .filter(|value| *value < size)
15407        .ok_or_else(|| {
15408            invalid_recorded_history(
15409                "parallel_group_metadata_invalid",
15410                sequence,
15411                "parallel_group_index within group bounds",
15412                &payload.to_string(),
15413                "parallel-group history contains an invalid member index",
15414            )
15415        })?;
15416    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
15417        return Err(invalid_recorded_history(
15418            "parallel_group_metadata_invalid",
15419            sequence,
15420            "base sequence plus member index equals workflow sequence",
15421            &payload.to_string(),
15422            "parallel-group path does not preserve durable workflow position",
15423        ));
15424    }
15425    let mode = payload
15426        .get("parallel_group_mode")
15427        .and_then(Value::as_str)
15428        .unwrap_or("all");
15429    if !matches!(mode, "all" | "select") {
15430        return Err(invalid_recorded_history(
15431            "parallel_group_metadata_invalid",
15432            sequence,
15433            "parallel group mode all or select",
15434            mode,
15435            "parallel-group history contains an unsupported group mode",
15436        ));
15437    }
15438    let expected_id = if mode == "select" {
15439        format!("select-calls:{base_sequence}:{size}")
15440    } else {
15441        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
15442    };
15443    if group_id != expected_id {
15444        return Err(invalid_recorded_history(
15445            "parallel_group_metadata_invalid",
15446            sequence,
15447            &expected_id,
15448            &group_id,
15449            "parallel-group history contains an incompatible stable group ID",
15450        ));
15451    }
15452    let selection_member_key = if mode == "select" {
15453        Some(selection_key_from_value(
15454            payload.get("selection_member_key"),
15455            sequence,
15456        )?)
15457    } else {
15458        None
15459    };
15460    let selection_member_index = if mode == "select" {
15461        Some(required_parallel_usize(
15462            payload,
15463            "selection_member_index",
15464            sequence,
15465        )?)
15466    } else {
15467        None
15468    };
15469    let selection_member_base_sequence = if mode == "select" {
15470        Some(
15471            payload
15472                .get("selection_member_base_sequence")
15473                .and_then(value_as_u64)
15474                .filter(|value| *value >= base_sequence)
15475                .ok_or_else(|| {
15476                    invalid_recorded_history(
15477                        "parallel_group_metadata_invalid",
15478                        sequence,
15479                        "selection member base within its group",
15480                        &payload.to_string(),
15481                        "selection history contains an invalid member base sequence",
15482                    )
15483                })?,
15484        )
15485    } else {
15486        None
15487    };
15488    let selection_member_size = if mode == "select" {
15489        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
15490        if member_size == 0 {
15491            return Err(invalid_recorded_history(
15492                "parallel_group_metadata_invalid",
15493                sequence,
15494                "positive selection member size",
15495                &payload.to_string(),
15496                "selection history contains an invalid member size",
15497            ));
15498        }
15499        Some(member_size)
15500    } else {
15501        None
15502    };
15503    let selection_member_kind = if mode == "select" {
15504        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
15505            invalid_recorded_history(
15506                "parallel_group_metadata_invalid",
15507                sequence,
15508                "selection member operation kind",
15509                &payload.to_string(),
15510                "selection history is missing its authored member kind",
15511            )
15512        })?;
15513        if !matches!(
15514            kind.as_str(),
15515            "activity" | "child" | "timer" | "signal" | "condition" | "group"
15516        ) {
15517            return Err(invalid_recorded_history(
15518                "parallel_group_metadata_invalid",
15519                sequence,
15520                "activity, child, timer, signal, condition, or group selection member kind",
15521                &kind,
15522                "selection history contains an unsupported member kind",
15523            ));
15524        }
15525        Some(kind)
15526    } else {
15527        None
15528    };
15529    if let (Some(member_base), Some(member_size)) =
15530        (selection_member_base_sequence, selection_member_size)
15531    {
15532        let member_end = member_base
15533            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
15534            .ok_or_else(|| {
15535                invalid_recorded_history(
15536                    "parallel_group_metadata_invalid",
15537                    sequence,
15538                    "bounded selection member range",
15539                    &payload.to_string(),
15540                    "selection member range overflowed",
15541                )
15542            })?;
15543        let group_end = base_sequence
15544            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
15545            .unwrap_or(u64::MAX);
15546        if sequence < member_base || sequence >= member_end || member_end > group_end {
15547            return Err(invalid_recorded_history(
15548                "parallel_group_metadata_invalid",
15549                sequence,
15550                "workflow sequence within one bounded selection member",
15551                &payload.to_string(),
15552                "selection member range does not contain its durable leaf",
15553            ));
15554        }
15555    }
15556    Ok(ParallelGroupMetadata {
15557        parallel_group_id: group_id,
15558        parallel_group_kind: kind,
15559        parallel_group_base_sequence: base_sequence,
15560        parallel_group_size: size,
15561        parallel_group_index: index,
15562        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
15563        selection_member_key,
15564        selection_member_index,
15565        selection_member_base_sequence,
15566        selection_member_size,
15567        selection_member_kind,
15568    })
15569}
15570
15571fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
15572    payload
15573        .get(field)
15574        .and_then(value_as_u64)
15575        .and_then(|value| usize::try_from(value).ok())
15576        .ok_or_else(|| {
15577            invalid_recorded_history(
15578                "parallel_group_metadata_invalid",
15579                sequence,
15580                &format!("non-negative integer {field}"),
15581                &payload.to_string(),
15582                "selection history contains invalid member metadata",
15583            )
15584        })
15585}
15586
15587fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
15588    match value {
15589        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
15590        Some(value) => value_as_u64(value)
15591            .and_then(|value| usize::try_from(value).ok())
15592            .map(SelectionKey::Index)
15593            .ok_or_else(|| {
15594                invalid_recorded_history(
15595                    "selection_member_key_invalid",
15596                    sequence,
15597                    "non-empty string or non-negative integer member key",
15598                    &value.to_string(),
15599                    "selection history contains an invalid member key",
15600                )
15601            }),
15602        None => Err(invalid_recorded_history(
15603            "selection_member_key_missing",
15604            sequence,
15605            "selection_member_key",
15606            "<missing>",
15607            "selection history is missing its stable member key",
15608        )),
15609    }
15610}
15611
15612fn recorded_parallel_group_path(
15613    events: &[&HistoryEvent],
15614    sequence: u64,
15615) -> Result<Option<Vec<ParallelGroupMetadata>>> {
15616    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
15617    for event in events {
15618        let payload = &event.payload;
15619        let has_metadata = payload.get("parallel_group_path").is_some()
15620            || payload.get("parallel_group_id").is_some()
15621            || payload.get("parallel_group_kind").is_some()
15622            || payload.get("parallel_group_base_sequence").is_some()
15623            || payload.get("parallel_group_size").is_some()
15624            || payload.get("parallel_group_index").is_some()
15625            || payload.get("parallel_group_mode").is_some()
15626            || payload.get("selection_member_key").is_some();
15627        if !has_metadata {
15628            continue;
15629        }
15630
15631        let top_level = recorded_parallel_group_entry(payload, sequence)?;
15632        let path = match payload.get("parallel_group_path") {
15633            None => vec![top_level.clone()],
15634            Some(Value::Array(entries)) if !entries.is_empty() => entries
15635                .iter()
15636                .map(|entry| recorded_parallel_group_entry(entry, sequence))
15637                .collect::<Result<Vec<_>>>()?,
15638            Some(value) => {
15639                return Err(invalid_recorded_history(
15640                    "parallel_group_metadata_invalid",
15641                    sequence,
15642                    "non-empty parallel_group_path list",
15643                    &value.to_string(),
15644                    "parallel-group history contains an invalid group path",
15645                ));
15646            }
15647        };
15648        if path.last() != Some(&top_level) {
15649            return Err(invalid_recorded_history(
15650                "parallel_group_metadata_invalid",
15651                sequence,
15652                &serde_json::to_string(&path.last()).unwrap_or_default(),
15653                &serde_json::to_string(&top_level).unwrap_or_default(),
15654                "parallel-group top-level fields do not match the innermost path entry",
15655            ));
15656        }
15657        if recorded.as_ref().is_some_and(|existing| existing != &path) {
15658            return Err(invalid_recorded_history(
15659                "parallel_group_history_conflict",
15660                sequence,
15661                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
15662                &serde_json::to_string(&path).unwrap_or_default(),
15663                "parallel-group metadata changed between scheduling and resolution history",
15664            ));
15665        }
15666        recorded = Some(path);
15667    }
15668    Ok(recorded)
15669}
15670
15671fn recorded_commands(
15672    events: &[HistoryEvent],
15673    fallback_codec: &str,
15674    parent: WorkflowIdentity,
15675) -> Result<Vec<RecordedCommand>> {
15676    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
15677    let mut last_new_sequence = None;
15678
15679    for event in events {
15680        let is_activity = matches!(
15681            event.event_type.as_str(),
15682            "ActivityScheduled"
15683                | "ActivityStarted"
15684                | "ActivityHeartbeatRecorded"
15685                | "ActivityRetryScheduled"
15686                | "ActivityCompleted"
15687                | "ActivityFailed"
15688                | "ActivityCancelled"
15689                | "ActivityTimedOut"
15690        );
15691        let is_workflow_timer = matches!(
15692            event.event_type.as_str(),
15693            "TimerScheduled" | "TimerCancelled" | "TimerFired"
15694        ) && !is_internal_timer_event(event);
15695        let is_child_workflow = matches!(
15696            event.event_type.as_str(),
15697            "ChildWorkflowScheduled"
15698                | "ChildRunStarted"
15699                | "ChildRunCompleted"
15700                | "ChildRunFailed"
15701                | "ChildRunCancelled"
15702                | "ChildRunTerminated"
15703        );
15704        let is_signal_wait = is_recorded_signal_wait_event(event);
15705        let is_condition_wait = is_recorded_condition_wait_event(event);
15706        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
15707        let is_side_effect = event.event_type == "SideEffectRecorded";
15708        let is_version_marker = event.event_type == "VersionMarkerRecorded";
15709        let is_memo = event.event_type == "MemoUpserted";
15710        if !is_activity
15711            && !is_workflow_timer
15712            && !is_child_workflow
15713            && !is_signal_wait
15714            && !is_condition_wait
15715            && !is_search_attributes
15716            && !is_side_effect
15717            && !is_version_marker
15718            && !is_memo
15719        {
15720            continue;
15721        }
15722
15723        let sequence = durable_event_sequence(event).ok_or_else(|| {
15724            Error::NonDeterministicReplay(ReplayFailure::new(
15725                "durable_command_sequence_missing",
15726                None,
15727                Some("positive workflow sequence".to_string()),
15728                Some(event.event_type.clone()),
15729                "durable command history event has no workflow sequence",
15730            ))
15731        })?;
15732        if sequence == 0 {
15733            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15734                "durable_command_sequence_invalid",
15735                Some(sequence),
15736                Some("positive workflow sequence".to_string()),
15737                Some(sequence.to_string()),
15738                "durable command history uses an invalid workflow sequence",
15739            )));
15740        }
15741        if !events_by_sequence.contains_key(&sequence) {
15742            if let Some(previous) = last_new_sequence {
15743                if sequence < previous {
15744                    return Err(invalid_recorded_history(
15745                        "durable_command_sequence_mismatch",
15746                        sequence,
15747                        &format!("workflow sequence greater than {previous}"),
15748                        &sequence.to_string(),
15749                        "durable commands are not strictly ordered by their recorded workflow sequence",
15750                    ));
15751                }
15752            }
15753            last_new_sequence = Some(sequence);
15754        }
15755        events_by_sequence.entry(sequence).or_default().push(event);
15756    }
15757
15758    let commands: Vec<RecordedCommand> = events_by_sequence
15759        .into_iter()
15760        .map(|(sequence, sequence_events)| {
15761            let activity_events: Vec<_> = sequence_events
15762                .iter()
15763                .copied()
15764                .filter(|event| event.event_type.starts_with("Activity"))
15765                .collect();
15766            let timer_events: Vec<_> = sequence_events
15767                .iter()
15768                .copied()
15769                .filter(|event| event.event_type.starts_with("Timer"))
15770                .collect();
15771            let child_events: Vec<_> = sequence_events
15772                .iter()
15773                .copied()
15774                .filter(|event| {
15775                    event.event_type == "ChildWorkflowScheduled"
15776                        || event.event_type.starts_with("ChildRun")
15777                })
15778                .collect();
15779            let signal_wait_events: Vec<_> = sequence_events
15780                .iter()
15781                .copied()
15782                .filter(|event| is_recorded_signal_wait_event(event))
15783                .collect();
15784            let condition_wait_events: Vec<_> = sequence_events
15785                .iter()
15786                .copied()
15787                .filter(|event| is_recorded_condition_wait_event(event))
15788                .collect();
15789            let search_attribute_events: Vec<_> = sequence_events
15790                .iter()
15791                .copied()
15792                .filter(|event| event.event_type == "SearchAttributesUpserted")
15793                .collect();
15794            let side_effect_events: Vec<_> = sequence_events
15795                .iter()
15796                .copied()
15797                .filter(|event| event.event_type == "SideEffectRecorded")
15798                .collect();
15799            let version_marker_events: Vec<_> = sequence_events
15800                .iter()
15801                .copied()
15802                .filter(|event| event.event_type == "VersionMarkerRecorded")
15803                .collect();
15804            let memo_events: Vec<_> = sequence_events
15805                .iter()
15806                .copied()
15807                .filter(|event| event.event_type == "MemoUpserted")
15808                .collect();
15809
15810            let command_kind_count = usize::from(!activity_events.is_empty())
15811                + usize::from(!timer_events.is_empty())
15812                + usize::from(!child_events.is_empty())
15813                + usize::from(!signal_wait_events.is_empty())
15814                + usize::from(!condition_wait_events.is_empty())
15815                + usize::from(!search_attribute_events.is_empty())
15816                + usize::from(!side_effect_events.is_empty())
15817                + usize::from(!version_marker_events.is_empty())
15818                + usize::from(!memo_events.is_empty());
15819            if command_kind_count > 1 {
15820                let actual = [
15821                    (!activity_events.is_empty()).then_some("activity"),
15822                    (!timer_events.is_empty()).then_some("timer"),
15823                    (!child_events.is_empty()).then_some("child workflow"),
15824                    (!signal_wait_events.is_empty()).then_some("signal wait"),
15825                    (!condition_wait_events.is_empty()).then_some("condition wait"),
15826                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
15827                    (!side_effect_events.is_empty()).then_some("side effect"),
15828                    (!version_marker_events.is_empty()).then_some("version marker"),
15829                    (!memo_events.is_empty()).then_some("memo upsert"),
15830                ]
15831                .into_iter()
15832                .flatten()
15833                .collect::<Vec<_>>()
15834                .join(" and ");
15835                return Err(invalid_recorded_history(
15836                    "durable_command_sequence_collision",
15837                    sequence,
15838                    "one durable command kind",
15839                    &actual,
15840                    "one workflow sequence records more than one durable command kind",
15841                ));
15842            }
15843
15844            if !activity_events.is_empty() {
15845                let parallel_group_path =
15846                    recorded_parallel_group_path(&activity_events, sequence)?;
15847                let scheduled_count = activity_events
15848                    .iter()
15849                    .filter(|event| event.event_type == "ActivityScheduled")
15850                    .count();
15851                if scheduled_count > 1 {
15852                    return Err(invalid_recorded_history(
15853                        "duplicate_activity_schedule",
15854                        sequence,
15855                        "at most one ActivityScheduled event",
15856                        "multiple ActivityScheduled events",
15857                        "activity history schedules more than one command at one workflow sequence",
15858                    ));
15859                }
15860                let activity_type = activity_events.iter().find_map(|event| {
15861                    event
15862                        .payload
15863                        .get("activity_type")
15864                        .or_else(|| event.payload.get("activity_name"))
15865                        .and_then(Value::as_str)
15866                        .map(str::to_string)
15867                });
15868                if activity_events.iter().filter_map(|event| {
15869                    event
15870                        .payload
15871                        .get("activity_type")
15872                        .or_else(|| event.payload.get("activity_name"))
15873                        .and_then(Value::as_str)
15874                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
15875                    return Err(invalid_recorded_history(
15876                        "activity_identity_mismatch",
15877                        sequence,
15878                        activity_type.as_deref().unwrap_or("one activity identity"),
15879                        "conflicting activity identities",
15880                        "activity lifecycle events at one workflow sequence disagree on identity",
15881                    ));
15882                }
15883                let terminal: Vec<_> = activity_events
15884                    .iter()
15885                    .copied()
15886                    .filter(|event| {
15887                        matches!(
15888                            event.event_type.as_str(),
15889                            "ActivityCompleted"
15890                                | "ActivityFailed"
15891                                | "ActivityCancelled"
15892                                | "ActivityTimedOut"
15893                        )
15894                    })
15895                    .collect();
15896                let duplicate_delivery = terminal.first().is_some_and(|first| {
15897                    terminal.iter().all(|event| {
15898                        event.event_type == first.event_type && event.payload == first.payload
15899                    })
15900                });
15901                if terminal.len() > 1 && !duplicate_delivery {
15902                    return Err(invalid_recorded_history(
15903                        "duplicate_activity_terminal_event",
15904                        sequence,
15905                        "at most one terminal activity event",
15906                        "multiple terminal activity events",
15907                        "activity history settles one command more than once",
15908                    ));
15909                }
15910                let outcome = terminal
15911                    .first()
15912                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
15913                    .transpose()?;
15914                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
15915                let activity_snapshot = activity_events
15916                    .iter()
15917                    .find(|event| event.event_type == "ActivityScheduled")
15918                    .and_then(|event| event.payload.get("activity"))
15919                    .and_then(Value::as_object);
15920                let options = Some(match activity_snapshot {
15921                    Some(activity) => RecordedActivityOptions {
15922                        task_queue: recorded_optional_string(activity, "queue"),
15923                        execution_mode,
15924                        retry_policy: recorded_activity_retry_snapshot(
15925                            activity.get("retry_policy"),
15926                        ),
15927                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15928                    },
15929                    None => RecordedActivityOptions {
15930                        task_queue: RecordedSnapshotValue::Unknown,
15931                        execution_mode,
15932                        retry_policy: recorded_activity_retry_snapshot(None),
15933                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
15934                    },
15935                });
15936                return Ok(RecordedCommand::Activity {
15937                    sequence,
15938                    activity_type,
15939                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
15940                    options,
15941                    outcome,
15942                    parallel_group_path,
15943                });
15944            }
15945
15946            if !child_events.is_empty() {
15947                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
15948                let scheduled: Vec<_> = child_events
15949                    .iter()
15950                    .copied()
15951                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
15952                    .collect();
15953                if scheduled.len() != 1 {
15954                    return Err(invalid_recorded_history(
15955                        "child_workflow_schedule_missing_or_duplicate",
15956                        sequence,
15957                        "one ChildWorkflowScheduled event",
15958                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
15959                        "child workflow replay requires exactly one recorded schedule event",
15960                    ));
15961                }
15962                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
15963                let workflow_type = child_events.iter().find_map(|event| {
15964                    event
15965                        .payload
15966                        .get("child_workflow_type")
15967                        .or_else(|| event.payload.get("workflow_type"))
15968                        .and_then(Value::as_str)
15969                        .filter(|value| !value.is_empty())
15970                        .map(str::to_string)
15971                });
15972                if child_events
15973                    .iter()
15974                    .filter_map(|event| {
15975                        event
15976                            .payload
15977                            .get("child_workflow_type")
15978                            .or_else(|| event.payload.get("workflow_type"))
15979                            .and_then(Value::as_str)
15980                    })
15981                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
15982                {
15983                    return Err(invalid_recorded_history(
15984                        "child_workflow_identity_mismatch",
15985                        sequence,
15986                        workflow_type
15987                            .as_deref()
15988                            .unwrap_or("one child workflow type"),
15989                        "conflicting child workflow types",
15990                        "child workflow lifecycle events at one sequence disagree on type",
15991                    ));
15992                }
15993                let mut outcomes = child_workflow_outcomes(
15994                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
15995                    fallback_codec,
15996                    parent.clone(),
15997                )?;
15998                let terminal_events = child_events
15999                    .iter()
16000                    .copied()
16001                    .filter(|event| event.event_type.starts_with("ChildRun"))
16002                    .collect::<Vec<_>>();
16003                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
16004                    terminal_events.iter().all(|event| {
16005                        event.event_type == first.event_type && event.payload == first.payload
16006                    })
16007                });
16008                if outcomes.len() > 1 && !duplicate_delivery {
16009                    return Err(invalid_recorded_history(
16010                        "duplicate_child_workflow_terminal_event",
16011                        sequence,
16012                        "at most one terminal child event",
16013                        "multiple terminal child events",
16014                        "child workflow history settles one command more than once",
16015                    ));
16016                }
16017                return Ok(RecordedCommand::ChildWorkflow {
16018                    sequence,
16019                    workflow_type,
16020                    policies,
16021                    outcome: outcomes.pop(),
16022                    parallel_group_path,
16023                });
16024            }
16025
16026            if !signal_wait_events.is_empty() {
16027                let opened: Vec<_> = signal_wait_events
16028                    .iter()
16029                    .copied()
16030                    .filter(|event| event.event_type == "SignalWaitOpened")
16031                    .collect();
16032                if opened.len() != 1 {
16033                    return Err(invalid_recorded_history(
16034                        "signal_wait_open_missing_or_duplicate",
16035                        sequence,
16036                        "one SignalWaitOpened event",
16037                        &format!("{} SignalWaitOpened events", opened.len()),
16038                        "signal replay requires exactly one canonical wait-open event",
16039                    ));
16040                }
16041
16042                let applied: Vec<_> = signal_wait_events
16043                    .iter()
16044                    .copied()
16045                    .filter(|event| event.event_type == "SignalApplied")
16046                    .collect();
16047                if applied.len() > 1 {
16048                    return Err(invalid_recorded_history(
16049                        "duplicate_signal_wait_apply",
16050                        sequence,
16051                        "at most one SignalApplied event",
16052                        "multiple SignalApplied events",
16053                        "signal history applies one durable wait more than once",
16054                    ));
16055                }
16056
16057                let signal_names = signal_wait_events
16058                    .iter()
16059                    .map(|event| required_signal_wait_name(event, sequence))
16060                    .collect::<Result<Vec<_>>>()?;
16061                let signal_name = signal_names
16062                    .first()
16063                    .expect("signal wait events are not empty")
16064                    .clone();
16065                if signal_names.iter().any(|candidate| candidate != &signal_name) {
16066                    return Err(invalid_recorded_history(
16067                        "signal_wait_identity_mismatch",
16068                        sequence,
16069                        &signal_name,
16070                        "conflicting signal names",
16071                        "signal wait lifecycle events at one workflow sequence disagree on identity",
16072                    ));
16073                }
16074                let value = applied
16075                    .first()
16076                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
16077                    .transpose()?;
16078                return Ok(RecordedCommand::SignalWait {
16079                    sequence,
16080                    signal_name,
16081                    value,
16082                    parallel_group_path: recorded_parallel_group_path(
16083                        &signal_wait_events,
16084                        sequence,
16085                    )?,
16086                });
16087            }
16088
16089            if !condition_wait_events.is_empty() {
16090                return recorded_condition_wait(
16091                    sequence,
16092                    &condition_wait_events,
16093                    events,
16094                );
16095            }
16096
16097            if !search_attribute_events.is_empty() {
16098                if search_attribute_events.len() != 1 {
16099                    return Err(invalid_recorded_history(
16100                        "duplicate_search_attribute_update",
16101                        sequence,
16102                        "one SearchAttributesUpserted event",
16103                        &format!(
16104                            "{} SearchAttributesUpserted events",
16105                            search_attribute_events.len()
16106                        ),
16107                        "search-attribute history records one workflow command more than once",
16108                    ));
16109                }
16110                let payload = &search_attribute_events[0].payload;
16111                let attributes = payload
16112                    .get("attributes")
16113                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
16114                    .cloned()
16115                    .ok_or_else(|| {
16116                        invalid_recorded_history(
16117                            "search_attribute_update_missing",
16118                            sequence,
16119                            "non-empty attributes object",
16120                            "missing or invalid attributes",
16121                            "search-attribute history is missing its recorded mutation",
16122                        )
16123                    })?;
16124                let attribute_types =
16125                    recorded_search_attribute_types(payload, &attributes, sequence)?;
16126                return Ok(RecordedCommand::SearchAttributes {
16127                    sequence,
16128                    attributes,
16129                    attribute_types,
16130                });
16131            }
16132
16133            if !side_effect_events.is_empty() {
16134                if side_effect_events.len() != 1 {
16135                    return Err(invalid_recorded_history(
16136                        "duplicate_side_effect_record",
16137                        sequence,
16138                        "one SideEffectRecorded event",
16139                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
16140                        "side-effect history records one workflow command more than once",
16141                    ));
16142                }
16143                let event = side_effect_events[0];
16144                let result = event.payload.get("result").ok_or_else(|| {
16145                    invalid_recorded_history(
16146                        "side_effect_result_missing",
16147                        sequence,
16148                        "recorded result payload",
16149                        "missing result",
16150                        "side-effect history is missing its recorded value",
16151                    )
16152                })?;
16153                let has_published_envelope = result.as_str().is_some()
16154                    || result.as_object().is_some_and(|envelope| {
16155                        envelope.get("codec").and_then(Value::as_str).is_some()
16156                            && envelope.get("blob").and_then(Value::as_str).is_some()
16157                    });
16158                if !has_published_envelope {
16159                    return Err(invalid_recorded_history(
16160                        "side_effect_payload_malformed",
16161                        sequence,
16162                        "payload blob or {codec, blob} envelope",
16163                        &result.to_string(),
16164                        "side-effect history result does not use a published payload envelope",
16165                    ));
16166                }
16167                let codec = event
16168                    .payload
16169                    .get("payload_codec")
16170                    .and_then(Value::as_str)
16171                    .unwrap_or(fallback_codec);
16172                let value = decode_wire_avro_value(result, codec).map_err(|error| {
16173                    if error.to_string().contains("unsupported_payload_codec") {
16174                        return error;
16175                    }
16176
16177                    invalid_recorded_history(
16178                        "side_effect_payload_incompatible",
16179                        sequence,
16180                        &format!("valid {codec} payload envelope"),
16181                        &error.to_string(),
16182                        "side-effect history payload cannot be decoded with its recorded codec",
16183                    )
16184                })?;
16185                return Ok(RecordedCommand::SideEffect { sequence, value });
16186            }
16187
16188            if !version_marker_events.is_empty() {
16189                if version_marker_events.len() != 1 {
16190                    return Err(invalid_recorded_history(
16191                        "duplicate_version_marker_record",
16192                        sequence,
16193                        "one VersionMarkerRecorded event",
16194                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
16195                        "version-marker history records one workflow command more than once",
16196                    ));
16197                }
16198                let payload = &version_marker_events[0].payload;
16199                let change_id = payload
16200                    .get("change_id")
16201                    .and_then(Value::as_str)
16202                    .filter(|value| !value.is_empty())
16203                    .map(str::to_string)
16204                    .ok_or_else(|| {
16205                        invalid_recorded_history(
16206                            "version_marker_field_missing",
16207                            sequence,
16208                            "non-empty change_id",
16209                            "missing or invalid change_id",
16210                            "version-marker history is missing its stable change ID",
16211                        )
16212                    })?;
16213                let version = required_version_i32(payload, "version", sequence)?;
16214                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
16215                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
16216                if min_supported > max_supported || version < min_supported || version > max_supported {
16217                    return Err(invalid_recorded_history(
16218                        "version_marker_history_range_invalid",
16219                        sequence,
16220                        "min_supported <= version <= max_supported",
16221                        &format!("{min_supported} <= {version} <= {max_supported}"),
16222                        "recorded version marker contains an internally incompatible range",
16223                    ));
16224                }
16225                return Ok(RecordedCommand::VersionMarker {
16226                    sequence,
16227                    change_id,
16228                    version,
16229                });
16230            }
16231
16232            if !memo_events.is_empty() {
16233                if memo_events.len() != 1 {
16234                    return Err(invalid_recorded_history(
16235                        "duplicate_memo_upsert_record",
16236                        sequence,
16237                        "one MemoUpserted event",
16238                        &format!("{} MemoUpserted events", memo_events.len()),
16239                        "memo history records one workflow update more than once",
16240                    ));
16241                }
16242                let payload = &memo_events[0].payload;
16243                let entries = payload.get("entries").cloned().ok_or_else(|| {
16244                    invalid_recorded_history(
16245                        "memo_entries_missing",
16246                        sequence,
16247                        "memo entries object",
16248                        "missing entries",
16249                        "MemoUpserted history is missing replay identity entries",
16250                    )
16251                })?;
16252                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
16253                    invalid_recorded_history(
16254                        "memo_entries_invalid",
16255                        sequence,
16256                        "valid canonical memo entries",
16257                        &error.to_string(),
16258                        "MemoUpserted history contains invalid replay identity entries",
16259                    )
16260                })?;
16261                let merged = payload.get("merged").cloned().ok_or_else(|| {
16262                    invalid_recorded_history(
16263                        "memo_merged_projection_missing",
16264                        sequence,
16265                        "merged memo projection",
16266                        "missing merged",
16267                        "MemoUpserted history is missing its merged projection",
16268                    )
16269                })?;
16270                decode_memo_history_map(&merged, false).map_err(|error| {
16271                    invalid_recorded_history(
16272                        "memo_merged_projection_invalid",
16273                        sequence,
16274                        "valid merged memo projection",
16275                        &error.to_string(),
16276                        "MemoUpserted history contains an invalid merged projection",
16277                    )
16278                })?;
16279
16280                return Ok(RecordedCommand::Memo { sequence, entries });
16281            }
16282            let scheduled: Vec<_> = timer_events
16283                .iter()
16284                .copied()
16285                .filter(|event| event.event_type == "TimerScheduled")
16286                .collect();
16287            let fired: Vec<_> = timer_events
16288                .iter()
16289                .copied()
16290                .filter(|event| event.event_type == "TimerFired")
16291                .collect();
16292            if scheduled.len() != 1 {
16293                return Err(invalid_recorded_history(
16294                    "timer_schedule_missing_or_duplicate",
16295                    sequence,
16296                    "one TimerScheduled event",
16297                    &format!("{} TimerScheduled events", scheduled.len()),
16298                    "timer replay requires exactly one recorded schedule event",
16299                ));
16300            }
16301            if fired.len() > 1 {
16302                return Err(invalid_recorded_history(
16303                    "duplicate_timer_fire",
16304                    sequence,
16305                    "at most one TimerFired event",
16306                    "multiple TimerFired events",
16307                    "timer history contains more than one fire event for a workflow sequence",
16308                ));
16309            }
16310
16311            let scheduled = scheduled[0];
16312            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16313            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16314            if let Some(fired) = fired.first() {
16315                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16316                if fired_timer_id != timer_id {
16317                    return Err(invalid_recorded_history(
16318                        "timer_identity_mismatch",
16319                        sequence,
16320                        &timer_id,
16321                        &fired_timer_id,
16322                        "TimerFired does not correspond to the recorded TimerScheduled event",
16323                    ));
16324                }
16325                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16326                if fired_delay != delay_seconds {
16327                    return Err(invalid_recorded_history(
16328                        "timer_history_delay_mismatch",
16329                        sequence,
16330                        &delay_seconds.to_string(),
16331                        &fired_delay.to_string(),
16332                        "TimerScheduled and TimerFired record different delays",
16333                    ));
16334                }
16335            }
16336
16337            Ok(RecordedCommand::Timer {
16338                sequence,
16339                delay_seconds,
16340                fired: !fired.is_empty(),
16341                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
16342            })
16343        })
16344        .collect::<Result<_>>()?;
16345
16346    let mut marker_decisions = HashMap::new();
16347    for command in &commands {
16348        if let RecordedCommand::VersionMarker {
16349            sequence,
16350            change_id,
16351            version,
16352        } = command
16353        {
16354            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
16355                if version != first_version {
16356                    return Err(invalid_recorded_history(
16357                        "version_marker_conflict",
16358                        *sequence,
16359                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
16360                        &format!("version {version} at sequence {sequence}"),
16361                        "workflow history contains conflicting decisions for one stable change ID",
16362                    ));
16363                }
16364            } else {
16365                marker_decisions.insert(change_id.clone(), (*version, *sequence));
16366            }
16367        }
16368    }
16369
16370    Ok(commands)
16371}
16372
16373fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
16374    payload
16375        .get(field)
16376        .and_then(Value::as_i64)
16377        .and_then(|value| i32::try_from(value).ok())
16378        .ok_or_else(|| {
16379            invalid_recorded_history(
16380                "version_marker_field_missing",
16381                sequence,
16382                &format!("integer {field}"),
16383                "missing or out-of-range integer",
16384                "version-marker history is missing a required integer field",
16385            )
16386        })
16387}
16388
16389fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
16390    event
16391        .payload
16392        .get("sequence")
16393        .or_else(|| event.payload.get("workflow_sequence"))
16394        .or_else(|| event.raw.get("sequence"))
16395        .or_else(|| event.raw.get("workflow_sequence"))
16396        .and_then(value_as_u64)
16397}
16398
16399fn is_internal_timer_event(event: &HistoryEvent) -> bool {
16400    matches!(
16401        event
16402            .payload
16403            .get("timer_kind")
16404            .or_else(|| event.raw.get("timer_kind"))
16405            .and_then(Value::as_str),
16406        Some("condition_timeout" | "signal_timeout")
16407    )
16408}
16409
16410fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
16411    matches!(
16412        event.event_type.as_str(),
16413        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16414    )
16415}
16416
16417fn recorded_condition_wait(
16418    sequence: u64,
16419    condition_events: &[&HistoryEvent],
16420    all_events: &[HistoryEvent],
16421) -> Result<RecordedCommand> {
16422    let opened = condition_events
16423        .iter()
16424        .copied()
16425        .filter(|event| event.event_type == "ConditionWaitOpened")
16426        .collect::<Vec<_>>();
16427    if opened.len() != 1 {
16428        return Err(invalid_recorded_history(
16429            "condition_wait_open_missing_or_duplicate",
16430            sequence,
16431            "one ConditionWaitOpened event",
16432            &format!("{} ConditionWaitOpened events", opened.len()),
16433            "condition replay requires exactly one canonical wait-open event",
16434        ));
16435    }
16436    let terminal = condition_events
16437        .iter()
16438        .copied()
16439        .filter(|event| {
16440            matches!(
16441                event.event_type.as_str(),
16442                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16443            )
16444        })
16445        .collect::<Vec<_>>();
16446    if terminal.len() > 1 {
16447        return Err(invalid_recorded_history(
16448            "duplicate_condition_wait_terminal_event",
16449            sequence,
16450            "at most one condition terminal event",
16451            "multiple condition terminal events",
16452            "condition history settles one durable wait more than once",
16453        ));
16454    }
16455
16456    let opened = opened[0];
16457    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
16458    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
16459    for event in condition_events
16460        .iter()
16461        .copied()
16462        .filter(|event| !std::ptr::eq(*event, opened))
16463    {
16464        let event_wait_id = required_condition_wait_id(event, sequence)?;
16465        if event_wait_id != condition_wait_id {
16466            return Err(invalid_recorded_history(
16467                "condition_wait_id_mismatch",
16468                sequence,
16469                &condition_wait_id,
16470                &event_wait_id,
16471                "condition lifecycle events at one sequence disagree on wait identity",
16472            ));
16473        }
16474        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
16475        if event_occurrence_id != occurrence_id {
16476            return Err(invalid_recorded_history(
16477                "condition_wait_occurrence_history_mismatch",
16478                sequence,
16479                &occurrence_id,
16480                &event_occurrence_id,
16481                "condition lifecycle events at one sequence disagree on authored occurrence identity",
16482            ));
16483        }
16484    }
16485
16486    let condition_key = optional_non_empty_history_string(opened, "condition_key");
16487    let predicate_identity = opened
16488        .payload
16489        .get("condition_definition_fingerprint")
16490        .and_then(Value::as_str)
16491        .filter(|value| !value.is_empty())
16492        .map(str::to_string)
16493        .ok_or_else(|| {
16494            invalid_recorded_history(
16495                "condition_wait_predicate_fingerprint_missing",
16496                sequence,
16497                "non-empty condition_definition_fingerprint",
16498                &opened.event_type,
16499                "canonical condition history is missing its predicate identity",
16500            )
16501        })?;
16502    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
16503    for event in condition_events
16504        .iter()
16505        .copied()
16506        .filter(|event| !std::ptr::eq(*event, opened))
16507    {
16508        for (field, opened_value) in [
16509            ("condition_key", condition_key.as_deref()),
16510            (
16511                "condition_definition_fingerprint",
16512                Some(predicate_identity.as_str()),
16513            ),
16514        ] {
16515            if let Some(value) = optional_non_empty_history_string(event, field) {
16516                if opened_value.is_some_and(|opened_value| opened_value != value) {
16517                    return Err(invalid_recorded_history(
16518                        "condition_wait_definition_history_mismatch",
16519                        sequence,
16520                        opened_value.unwrap_or_default(),
16521                        &value,
16522                        "condition lifecycle events disagree on the recorded definition",
16523                    ));
16524                }
16525            }
16526        }
16527        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
16528            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
16529                return Err(invalid_recorded_history(
16530                    "condition_wait_definition_history_mismatch",
16531                    sequence,
16532                    &format!("{}s", timeout_seconds.unwrap_or_default()),
16533                    &format!("{event_timeout}s"),
16534                    "condition lifecycle events disagree on the recorded timeout",
16535                ));
16536            }
16537        }
16538    }
16539
16540    let timeout_timer_events = all_events
16541        .iter()
16542        .filter(|event| {
16543            matches!(
16544                event.event_type.as_str(),
16545                "TimerScheduled" | "TimerCancelled" | "TimerFired"
16546            ) && event.payload.get("timer_kind").and_then(Value::as_str)
16547                == Some("condition_timeout")
16548                && event
16549                    .payload
16550                    .get("condition_wait_id")
16551                    .and_then(Value::as_str)
16552                    == Some(condition_wait_id.as_str())
16553        })
16554        .collect::<Vec<_>>();
16555    let scheduled = timeout_timer_events
16556        .iter()
16557        .copied()
16558        .filter(|event| event.event_type == "TimerScheduled")
16559        .collect::<Vec<_>>();
16560    let fired = timeout_timer_events
16561        .iter()
16562        .copied()
16563        .filter(|event| event.event_type == "TimerFired")
16564        .collect::<Vec<_>>();
16565    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
16566        return Err(invalid_recorded_history(
16567            "condition_wait_timeout_history_invalid",
16568            sequence,
16569            "one timeout schedule and at most one fire",
16570            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
16571            "condition timeout history has a missing or duplicate lifecycle event",
16572        ));
16573    }
16574    if let Some(scheduled) = scheduled.first() {
16575        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
16576        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
16577        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
16578            return Err(invalid_recorded_history(
16579                "condition_wait_timeout_delay_mismatch",
16580                sequence,
16581                &format!("{}s", timeout_seconds.unwrap_or_default()),
16582                &format!("{delay_seconds}s"),
16583                "condition timeout timer differs from the wait definition",
16584            ));
16585        }
16586        if let Some(fired) = fired.first() {
16587            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
16588            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
16589            if fired_timer_id != timer_id || fired_delay != delay_seconds {
16590                return Err(invalid_recorded_history(
16591                    "condition_wait_timeout_identity_mismatch",
16592                    sequence,
16593                    &format!("{timer_id}:{delay_seconds}s"),
16594                    &format!("{fired_timer_id}:{fired_delay}s"),
16595                    "condition timeout fire does not match its durable schedule",
16596                ));
16597            }
16598        }
16599    }
16600
16601    let result = terminal.first().map(|event| {
16602        if event.event_type == "ConditionWaitTimedOut" {
16603            ConditionWaitResult::TimedOut
16604        } else {
16605            ConditionWaitResult::Satisfied
16606        }
16607    });
16608    let result = if !fired.is_empty() {
16609        if result == Some(ConditionWaitResult::Satisfied) {
16610            return Err(invalid_recorded_history(
16611                "condition_wait_terminal_conflict",
16612                sequence,
16613                "one satisfied or timed-out outcome",
16614                "satisfied event and fired timeout",
16615                "condition history records conflicting terminal outcomes",
16616            ));
16617        }
16618        Some(ConditionWaitResult::TimedOut)
16619    } else {
16620        result
16621    };
16622
16623    Ok(RecordedCommand::ConditionWait {
16624        sequence,
16625        occurrence_id,
16626        condition_key,
16627        predicate_identity,
16628        timeout_seconds,
16629        result,
16630        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
16631    })
16632}
16633
16634fn recorded_condition_group_path(
16635    condition_events: &[&HistoryEvent],
16636    all_events: &[HistoryEvent],
16637    sequence: u64,
16638) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16639    let opened = condition_events
16640        .iter()
16641        .copied()
16642        .find(|event| event.event_type == "ConditionWaitOpened")
16643        .expect("canonical condition opener is validated first");
16644    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
16645    let previous_events = all_events
16646        .iter()
16647        .take_while(|event| !std::ptr::eq(*event, opened))
16648        .collect::<Vec<_>>();
16649    let originals = previous_events
16650        .iter()
16651        .copied()
16652        .filter(|event| event.event_type == "ConditionWaitOpened")
16653        .filter(|event| {
16654            event
16655                .payload
16656                .get("condition_wait_occurrence_id")
16657                .and_then(Value::as_str)
16658                == Some(occurrence.as_str())
16659        })
16660        .collect::<Vec<_>>();
16661    let Some(original) = originals.first().copied() else {
16662        return recorded_parallel_group_path(condition_events, sequence);
16663    };
16664    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
16665    if authored_sequence == sequence {
16666        return recorded_parallel_group_path(condition_events, sequence);
16667    }
16668    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
16669    if original_path.is_none() {
16670        return recorded_parallel_group_path(condition_events, sequence);
16671    }
16672    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
16673    let identity_matches = [
16674        "condition_key",
16675        "condition_definition_fingerprint",
16676        "timeout_seconds",
16677    ]
16678    .iter()
16679    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
16680    let previous = originals
16681        .iter()
16682        .copied()
16683        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
16684        .max_by_key(|event| durable_event_sequence(event));
16685    let previously_satisfied = previous.is_some_and(|previous| {
16686        previous_events.iter().any(|event| {
16687            event.event_type == "ConditionWaitSatisfied"
16688                && event.payload.get("condition_wait_id")
16689                    == previous.payload.get("condition_wait_id")
16690                && event.payload.get("condition_wait_occurrence_id")
16691                    == previous.payload.get("condition_wait_occurrence_id")
16692                && durable_event_sequence(event) == durable_event_sequence(previous)
16693        })
16694    });
16695    if !identity_matches || reopened_path != original_path || !previously_satisfied {
16696        return Err(invalid_recorded_history(
16697            "condition_wait_group_reopen_mismatch",
16698            sequence,
16699            "same authored condition and group path after a satisfied physical wait",
16700            &opened.payload.to_string(),
16701            "grouped condition reopen has no matching recorded predecessor",
16702        ));
16703    }
16704    Ok(reopened_path)
16705}
16706
16707fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16708    event
16709        .payload
16710        .get("condition_wait_occurrence_id")
16711        .and_then(Value::as_str)
16712        .filter(|value| !value.is_empty())
16713        .map(str::to_string)
16714        .ok_or_else(|| {
16715            invalid_recorded_history(
16716                "condition_wait_occurrence_id_missing",
16717                sequence,
16718                "non-empty condition_wait_occurrence_id",
16719                &event.event_type,
16720                "condition history is missing authored occurrence identity",
16721            )
16722        })
16723}
16724
16725fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
16726    event
16727        .payload
16728        .get("condition_wait_id")
16729        .and_then(Value::as_str)
16730        .filter(|value| !value.is_empty())
16731        .map(str::to_string)
16732        .ok_or_else(|| {
16733            invalid_recorded_history(
16734                "condition_wait_id_missing",
16735                sequence,
16736                "non-empty condition_wait_id",
16737                &event.event_type,
16738                "canonical condition history is missing its durable wait identity",
16739            )
16740        })
16741}
16742
16743fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
16744    event
16745        .payload
16746        .get(field)
16747        .and_then(Value::as_str)
16748        .filter(|value| !value.is_empty())
16749        .map(str::to_string)
16750}
16751
16752fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
16753    match event.payload.get(field) {
16754        None | Some(Value::Null) => Ok(None),
16755        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
16756            invalid_recorded_history(
16757                "condition_wait_definition_invalid",
16758                sequence,
16759                &format!("non-negative integer {field}"),
16760                &value.to_string(),
16761                "condition history contains an invalid numeric definition field",
16762            )
16763        }),
16764    }
16765}
16766
16767fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
16768    event
16769        .payload
16770        .get("signal_name")
16771        .or_else(|| event.raw.get("signal_name"))
16772        .and_then(Value::as_str)
16773        .filter(|value| !value.is_empty())
16774        .map(str::to_string)
16775        .ok_or_else(|| {
16776            invalid_recorded_history(
16777                "signal_wait_name_missing",
16778                sequence,
16779                "non-empty signal_name",
16780                &event.event_type,
16781                "canonical signal-wait history is missing its signal identity",
16782            )
16783        })
16784}
16785
16786fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
16787    // Applying a buffered control-plane signal has no authored call sequence.
16788    // Its outer sequence orders history events and must not become a wait.
16789    if event.event_type == "SignalApplied"
16790        && event
16791            .payload
16792            .get("signal_wait_id")
16793            .and_then(Value::as_str)
16794            .is_some_and(|id| id.starts_with("signal-command:"))
16795        && event.payload.get("sequence").is_none()
16796        && event.payload.get("workflow_sequence").is_none()
16797    {
16798        return false;
16799    }
16800    matches!(
16801        event.event_type.as_str(),
16802        "SignalWaitOpened" | "SignalApplied"
16803    )
16804}
16805
16806fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
16807    event
16808        .payload
16809        .get(field)
16810        .and_then(Value::as_str)
16811        .filter(|value| !value.is_empty())
16812        .map(str::to_string)
16813        .ok_or_else(|| {
16814            invalid_recorded_history(
16815                "timer_history_field_missing",
16816                sequence,
16817                field,
16818                &event.event_type,
16819                "timer history is missing a required identity field",
16820            )
16821        })
16822}
16823
16824fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
16825    event
16826        .payload
16827        .get(field)
16828        .and_then(value_as_u64)
16829        .ok_or_else(|| {
16830            invalid_recorded_history(
16831                "timer_history_field_missing",
16832                sequence,
16833                field,
16834                &event.event_type,
16835                "timer history is missing a required numeric field",
16836            )
16837        })
16838}
16839
16840fn recorded_search_attribute_types(
16841    payload: &Value,
16842    attributes: &Value,
16843    sequence: u64,
16844) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
16845    let Some(raw_types) = payload.get("attribute_types") else {
16846        // This is the explicit compatibility rule for histories recorded
16847        // before typed identity was persisted. Values still constrain replay;
16848        // the unknown type snapshot does not assert a typed match.
16849        return Ok(RecordedSnapshotValue::Unknown);
16850    };
16851    let Some(raw_types) = raw_types.as_object() else {
16852        return Err(invalid_recorded_history(
16853            "search_attribute_types_malformed",
16854            sequence,
16855            "canonical attribute type map",
16856            &raw_types.to_string(),
16857            "search-attribute history contains malformed type identity",
16858        ));
16859    };
16860    let attribute_keys = attributes
16861        .as_object()
16862        .expect("recorded search attributes were validated as an object");
16863    let mut types = BTreeMap::new();
16864    for (key, value) in raw_types {
16865        let Some(attribute_type) = value.as_str() else {
16866            return Err(invalid_recorded_history(
16867                "search_attribute_types_malformed",
16868                sequence,
16869                "canonical string type name",
16870                &value.to_string(),
16871                "search-attribute history contains a non-string type identity",
16872            ));
16873        };
16874        if !attribute_keys.contains_key(key)
16875            || !matches!(
16876                attribute_type,
16877                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
16878            )
16879        {
16880            return Err(invalid_recorded_history(
16881                "search_attribute_types_malformed",
16882                sequence,
16883                "canonical types for keys present in attributes",
16884                &format!("{key}:{attribute_type}"),
16885                "search-attribute history contains unsupported or orphaned type identity",
16886            ));
16887        }
16888        types.insert(key.clone(), attribute_type.to_string());
16889    }
16890    Ok(RecordedSnapshotValue::Known(types))
16891}
16892
16893fn invalid_recorded_history(
16894    reason: &str,
16895    sequence: u64,
16896    expected: &str,
16897    actual: &str,
16898    message: &str,
16899) -> Error {
16900    Error::NonDeterministicReplay(ReplayFailure::new(
16901        reason,
16902        Some(sequence),
16903        Some(expected.to_string()),
16904        Some(actual.to_string()),
16905        message,
16906    ))
16907}
16908
16909type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
16910
16911fn activity_outcome(
16912    event: &HistoryEvent,
16913    fallback_codec: &str,
16914    recorded_activity_type: Option<String>,
16915) -> Result<ActivityOutcome> {
16916    if event.event_type == "ActivityCompleted" {
16917        let codec = event
16918            .payload
16919            .get("payload_codec")
16920            .and_then(Value::as_str)
16921            .unwrap_or(fallback_codec);
16922        return Ok(Ok(decode_wire_avro_value(
16923            event.payload.get("result").unwrap_or(&Value::Null),
16924            codec,
16925        )?));
16926    }
16927
16928    let payload = &event.payload;
16929    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
16930        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
16931        "ActivityCancelled" => (
16932            ActivityFailureKind::Cancelled,
16933            "cancelled",
16934            "activity was cancelled",
16935        ),
16936        "ActivityTimedOut" => (
16937            ActivityFailureKind::TimedOut,
16938            "timeout",
16939            "activity timed out",
16940        ),
16941        _ => unreachable!("activity_outcome is called only for terminal activity events"),
16942    };
16943    let exception = payload
16944        .get("exception")
16945        .filter(|value| !value.is_null())
16946        .cloned();
16947    let failure_category = payload_string(payload, "failure_category");
16948    let timeout_kind = payload_string(payload, "timeout_kind");
16949    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
16950        ActivityFailureKind::Failed => failure_category
16951            .clone()
16952            .unwrap_or_else(|| fallback_reason.to_string()),
16953        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
16954        ActivityFailureKind::TimedOut => timeout_kind
16955            .clone()
16956            .unwrap_or_else(|| fallback_reason.to_string()),
16957    });
16958    let message = payload_string(payload, "message")
16959        .or_else(|| {
16960            exception
16961                .as_ref()
16962                .and_then(|value| payload_string(value, "message"))
16963        })
16964        .unwrap_or_else(|| fallback_message.to_string());
16965
16966    Ok(Err(ActivityFailure {
16967        kind,
16968        reason,
16969        message,
16970        activity_execution_id: payload_string(payload, "activity_execution_id"),
16971        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
16972        activity_type: payload_string(payload, "activity_type")
16973            .or_else(|| payload_string(payload, "activity_name"))
16974            .or(recorded_activity_type),
16975        activity_class: payload_string(payload, "activity_class"),
16976        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
16977        failure_id: payload_string(payload, "failure_id"),
16978        failure_category,
16979        timeout_kind,
16980        non_retryable: payload
16981            .get("non_retryable")
16982            .and_then(Value::as_bool)
16983            .unwrap_or(false),
16984        exception_type: payload_string(payload, "exception_type").or_else(|| {
16985            exception
16986                .as_ref()
16987                .and_then(|value| payload_string(value, "type"))
16988        }),
16989        exception_class: payload_string(payload, "exception_class").or_else(|| {
16990            exception
16991                .as_ref()
16992                .and_then(|value| payload_string(value, "class"))
16993        }),
16994        code: payload
16995            .get("code")
16996            .filter(|value| !value.is_null())
16997            .cloned(),
16998        exception,
16999    }))
17000}
17001
17002type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
17003
17004fn child_workflow_outcomes(
17005    events: &[HistoryEvent],
17006    fallback_codec: &str,
17007    parent: WorkflowIdentity,
17008) -> Result<Vec<ChildWorkflowOutcome>> {
17009    let mut outcomes = Vec::new();
17010
17011    for event in events {
17012        let kind = match event.event_type.as_str() {
17013            "ChildRunCompleted" => None,
17014            "ChildRunFailed" => Some((
17015                ChildWorkflowFailureKind::Failed,
17016                "child_workflow",
17017                "child workflow failed",
17018            )),
17019            "ChildRunCancelled" => Some((
17020                ChildWorkflowFailureKind::Cancelled,
17021                "cancelled",
17022                "child workflow was cancelled",
17023            )),
17024            "ChildRunTerminated" => Some((
17025                ChildWorkflowFailureKind::Terminated,
17026                "terminated",
17027                "child workflow was terminated",
17028            )),
17029            _ => continue,
17030        };
17031        let payload = &event.payload;
17032        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
17033        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
17034        let child_workflow_type = payload_string(payload, "child_workflow_type");
17035
17036        if let Some((kind, reason, fallback_message)) = kind {
17037            let exception = payload
17038                .get("exception")
17039                .filter(|value| !value.is_null())
17040                .cloned();
17041            let message = payload_string(payload, "message")
17042                .or_else(|| {
17043                    exception
17044                        .as_ref()
17045                        .and_then(|value| payload_string(value, "message"))
17046                })
17047                .unwrap_or_else(|| fallback_message.to_string());
17048            let exception_type = payload_string(payload, "exception_type").or_else(|| {
17049                exception
17050                    .as_ref()
17051                    .and_then(|value| payload_string(value, "type"))
17052            });
17053            let exception_class = payload_string(payload, "exception_class").or_else(|| {
17054                exception
17055                    .as_ref()
17056                    .and_then(|value| payload_string(value, "class"))
17057            });
17058            outcomes.push(Err(ChildWorkflowFailure {
17059                kind,
17060                reason: reason.to_string(),
17061                message,
17062                parent_workflow_id: parent.workflow_id.clone(),
17063                parent_workflow_run_id: parent.run_id.clone(),
17064                child_workflow_id,
17065                child_workflow_run_id,
17066                child_workflow_type,
17067                failure_id: payload_string(payload, "failure_id"),
17068                failure_category: payload_string(payload, "failure_category"),
17069                exception_type,
17070                exception_class,
17071                non_retryable: payload
17072                    .get("non_retryable")
17073                    .and_then(Value::as_bool)
17074                    .unwrap_or(false),
17075                code: payload
17076                    .get("code")
17077                    .filter(|value| !value.is_null())
17078                    .cloned(),
17079                exception,
17080            }));
17081            continue;
17082        }
17083
17084        let codec = payload
17085            .get("payload_codec")
17086            .and_then(Value::as_str)
17087            .unwrap_or(fallback_codec);
17088        let result = payload
17089            .get("result")
17090            .or_else(|| payload.get("output"))
17091            .unwrap_or(&Value::Null);
17092        outcomes.push(Ok(ChildWorkflowAvroResult {
17093            parent: parent.clone(),
17094            child: WorkflowIdentity {
17095                workflow_id: child_workflow_id,
17096                run_id: child_workflow_run_id,
17097            },
17098            child_workflow_type,
17099            result: decode_wire_avro_value(result, codec)?,
17100        }));
17101    }
17102
17103    Ok(outcomes)
17104}
17105
17106fn payload_string(payload: &Value, key: &str) -> Option<String> {
17107    payload
17108        .get(key)
17109        .and_then(Value::as_str)
17110        .filter(|value| !value.is_empty())
17111        .map(str::to_string)
17112}
17113
17114fn recorded_activity_failure_boundary(
17115    ctx: &WorkflowContext,
17116    error: &Error,
17117) -> Option<(u64, String)> {
17118    let Error::ActivityFailed(failure) = error else {
17119        return None;
17120    };
17121    if failure.kind != ActivityFailureKind::Failed {
17122        return None;
17123    }
17124    let activity_execution_id = failure
17125        .activity_execution_id
17126        .as_deref()
17127        .filter(|value| !value.is_empty())?;
17128    let state = ctx.state.lock().ok()?;
17129    let mut matches = state.recorded_commands.iter().filter_map(|command| {
17130        let RecordedCommand::Activity {
17131            sequence,
17132            outcome: Some(Err(recorded_failure)),
17133            ..
17134        } = command
17135        else {
17136            return None;
17137        };
17138        (*sequence > 0 && recorded_failure == failure)
17139            .then_some((*sequence, activity_execution_id.to_string()))
17140    });
17141    let boundary = matches.next()?;
17142    matches.next().is_none().then_some(boundary)
17143}
17144
17145fn workflow_failure_command(
17146    error: &Error,
17147    failed_activity_boundary: Option<(u64, String)>,
17148) -> Value {
17149    let (exception_type, exception_class, properties) = match error {
17150        Error::ActivityFailed(failure) => (
17151            match failure.kind {
17152                ActivityFailureKind::Failed => "ActivityFailed",
17153                ActivityFailureKind::Cancelled => "ActivityCancelled",
17154                ActivityFailureKind::TimedOut => "ActivityTimedOut",
17155            },
17156            "durable_workflow::ActivityFailure",
17157            json!({
17158                "reason": failure.reason,
17159                "activity_execution_id": failure.activity_execution_id,
17160                "activity_attempt_id": failure.activity_attempt_id,
17161                "activity_type": failure.activity_type,
17162                "activity_class": failure.activity_class,
17163                "attempt_number": failure.attempt_number,
17164                "failure_id": failure.failure_id,
17165                "failure_category": failure.failure_category,
17166                "timeout_kind": failure.timeout_kind,
17167                "activity_non_retryable": failure.non_retryable,
17168                "activity_exception_type": failure.exception_type,
17169                "activity_exception_class": failure.exception_class,
17170                "activity_code": failure.code,
17171                "activity_exception": failure.exception,
17172            }),
17173        ),
17174        Error::ChildWorkflowFailed(failure) => (
17175            match failure.kind {
17176                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17177                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17178                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17179            },
17180            "durable_workflow::ChildWorkflowFailure",
17181            json!({
17182                "reason": failure.reason,
17183                "parent_workflow_id": failure.parent_workflow_id,
17184                "parent_workflow_run_id": failure.parent_workflow_run_id,
17185                "child_workflow_id": failure.child_workflow_id,
17186                "child_workflow_run_id": failure.child_workflow_run_id,
17187                "child_workflow_type": failure.child_workflow_type,
17188                "failure_id": failure.failure_id,
17189                "failure_category": failure.failure_category,
17190                "child_exception_type": failure.exception_type,
17191                "child_exception_class": failure.exception_class,
17192                "child_non_retryable": failure.non_retryable,
17193                "child_code": failure.code,
17194                "child_exception": failure.exception,
17195            }),
17196        ),
17197        Error::ParallelFailed(failure) => (
17198            "ParallelFailed",
17199            "durable_workflow::ParallelFailure",
17200            json!({
17201                "parallel_group_id": failure.group_id,
17202                "parallel_member_path": failure.member_path,
17203                "parallel_group_path": failure.group_path,
17204                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
17205                "cause_type": workflow_error_type(&failure.cause),
17206                "cause_message": failure.cause.to_string(),
17207            }),
17208        ),
17209        Error::SagaCompensationFailed(failure) => (
17210            "SagaCompensationFailed",
17211            "durable_workflow::SagaCompensationFailure",
17212            json!({
17213                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
17214                "initiating_failure_message": failure.initiating_failure.to_string(),
17215                "compensation_activity_type": failure.compensation_activity_type,
17216                "compensation_registration_order": failure.compensation_registration_order,
17217                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
17218                "compensation_failure_message": failure.compensation_failure.to_string(),
17219            }),
17220        ),
17221        Error::WorkflowCancellationRequested(_) => (
17222            "WorkflowCancellationRequested",
17223            "durable_workflow::WorkflowCancellationRequested",
17224            json!({"reason": "cancelled"}),
17225        ),
17226        Error::CooperativeCancellationRequested(cancellation) => (
17227            "WorkflowCancellationRequested",
17228            "durable_workflow::CooperativeCancellationRequested",
17229            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
17230                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
17231        ),
17232        Error::CancellationScopeRequested(cancellation) => (
17233            "WorkflowCancellationRequested",
17234            "durable_workflow::CancellationScopeRequested",
17235            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
17236                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
17237                "cancellation":cancellation.context.to_value()}),
17238        ),
17239        Error::NonDeterministicReplay(_) => (
17240            "NonDeterministicReplay",
17241            "durable_workflow::Error",
17242            Value::Null,
17243        ),
17244        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
17245    };
17246    let non_retryable = match error {
17247        Error::ActivityFailed(failure) => failure.non_retryable,
17248        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17249        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17250        Error::SagaCompensationFailed(failure) => {
17251            workflow_error_non_retryable(&failure.compensation_failure)
17252        }
17253        Error::WorkflowCancellationRequested(_)
17254        | Error::CooperativeCancellationRequested(_)
17255        | Error::CancellationScopeRequested(_) => true,
17256        Error::NonDeterministicReplay(_) => true,
17257        _ => false,
17258    };
17259
17260    let mut command = json!({
17261        "type": "fail_workflow",
17262        "message": error.to_string(),
17263        "exception_type": exception_type,
17264        "exception_class": exception_class,
17265        "non_retryable": non_retryable,
17266        "exception": {
17267            "type": exception_type,
17268            "class": exception_class,
17269            "message": error.to_string(),
17270            "properties": properties,
17271        }
17272    });
17273
17274    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
17275        command["failed_step_sequence"] = json!(sequence);
17276        command["failed_activity_execution_id"] = json!(activity_execution_id);
17277    }
17278
17279    command
17280}
17281
17282fn workflow_error_type(error: &Error) -> &'static str {
17283    match error {
17284        Error::ActivityFailed(failure) => match failure.kind {
17285            ActivityFailureKind::Failed => "ActivityFailed",
17286            ActivityFailureKind::Cancelled => "ActivityCancelled",
17287            ActivityFailureKind::TimedOut => "ActivityTimedOut",
17288        },
17289        Error::ChildWorkflowFailed(failure) => match failure.kind {
17290            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
17291            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
17292            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
17293        },
17294        Error::ParallelFailed(_) => "ParallelFailed",
17295        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
17296        Error::WorkflowCancellationRequested(_)
17297        | Error::CooperativeCancellationRequested(_)
17298        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
17299        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
17300        _ => "RustWorkflowError",
17301    }
17302}
17303
17304fn workflow_error_non_retryable(error: &Error) -> bool {
17305    match error {
17306        Error::ActivityFailed(failure) => failure.non_retryable,
17307        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
17308        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
17309        Error::SagaCompensationFailed(failure) => {
17310            workflow_error_non_retryable(&failure.compensation_failure)
17311        }
17312        Error::WorkflowCancellationRequested(_)
17313        | Error::CooperativeCancellationRequested(_)
17314        | Error::CancellationScopeRequested(_)
17315        | Error::NonDeterministicReplay(_) => true,
17316        _ => false,
17317    }
17318}
17319
17320fn workflow_task_integrity_error(error: &Error) -> bool {
17321    matches!(
17322        error,
17323        Error::NonDeterministicReplay(_)
17324            | Error::Protocol(_)
17325            | Error::CancellationScopeExecutionUnavailable
17326            | Error::MissingWorkflowCommandIdentity
17327            | Error::WorkflowStatePoisoned
17328    )
17329}
17330
17331fn decode_signal_event_arguments(
17332    event: &HistoryEvent,
17333    fallback_codec: &str,
17334) -> Result<Vec<AvroValue>> {
17335    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17336    validate_payload_codec(codec)?;
17337    let raw = signal_history_payload(&event.payload);
17338    let decoded = match raw.filter(|value| !value.is_null()) {
17339        Some(value) => decode_wire_avro_value(value, codec)?,
17340        None => AvroValue::Array(Vec::new()),
17341    };
17342    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17343        unreachable!("normalize_avro_arguments always returns an array");
17344    };
17345    Ok(arguments)
17346}
17347
17348fn decode_update_event_arguments(
17349    event: &HistoryEvent,
17350    fallback_codec: &str,
17351) -> Result<Vec<AvroValue>> {
17352    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
17353    validate_payload_codec(codec)?;
17354    let decoded = match event
17355        .payload
17356        .get("arguments")
17357        .filter(|value| !value.is_null())
17358    {
17359        Some(value) => decode_wire_avro_value(value, codec)?,
17360        None => AvroValue::Array(Vec::new()),
17361    };
17362    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
17363        unreachable!("normalize_avro_arguments always returns an array");
17364    };
17365    Ok(arguments)
17366}
17367
17368fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17369    let Some(export_events) = task
17370        .history_export
17371        .as_ref()
17372        .and_then(|export| export.get("history_events"))
17373        .and_then(Value::as_array)
17374    else {
17375        return Ok(());
17376    };
17377
17378    if export_events.len() > task.history_events.len() {
17379        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
17380    }
17381
17382    Ok(())
17383}
17384
17385fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
17386    let Some(export) = task.history_export.as_ref() else {
17387        return Ok(());
17388    };
17389    let signals = export
17390        .get("signals")
17391        .and_then(Value::as_array)
17392        .cloned()
17393        .unwrap_or_default();
17394    let activities = export
17395        .get("activities")
17396        .and_then(Value::as_array)
17397        .cloned()
17398        .unwrap_or_default();
17399    let export_codec = export
17400        .get("payloads")
17401        .and_then(|payloads| payloads.get("codec"))
17402        .and_then(Value::as_str)
17403        .unwrap_or(&task.payload_codec)
17404        .to_string();
17405    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
17406
17407    for event in &mut task.history_events {
17408        if event.event_type == "ActivityCompleted" {
17409            let sequence = event
17410                .payload
17411                .get("sequence")
17412                .or_else(|| event.payload.get("workflow_sequence"))
17413                .and_then(value_as_u64);
17414            let Some(activity) = sequence.and_then(|sequence| {
17415                activities.iter().find(|activity| {
17416                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
17417                })
17418            }) else {
17419                continue;
17420            };
17421            let Some(payload) = event.payload.as_object_mut() else {
17422                continue;
17423            };
17424            if missing_payload(payload.get("result")) {
17425                if let Some(result) = activity
17426                    .get("result")
17427                    .filter(|value| !missing_payload(Some(value)))
17428                {
17429                    payload.insert("result".to_string(), result.clone());
17430                }
17431            }
17432            for field in ["payload_codec", "activity_type"] {
17433                if payload
17434                    .get(field)
17435                    .and_then(Value::as_str)
17436                    .unwrap_or_default()
17437                    .is_empty()
17438                {
17439                    if let Some(value) = activity.get(field) {
17440                        payload.insert(field.to_string(), value.clone());
17441                    }
17442                }
17443            }
17444            continue;
17445        }
17446
17447        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
17448            continue;
17449        }
17450        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17451        let command_id = event
17452            .payload
17453            .get("workflow_command_id")
17454            .or_else(|| event.raw.get("workflow_command_id"))
17455            .and_then(Value::as_str);
17456        let signal_name = event
17457            .payload
17458            .get("signal_name")
17459            .and_then(Value::as_str)
17460            .unwrap_or_default()
17461            .to_string();
17462        let matched = signals
17463            .iter()
17464            .find(|signal| {
17465                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
17466            })
17467            .or_else(|| {
17468                signals.iter().find(|signal| {
17469                    command_id.is_some()
17470                        && signal.get("command_id").and_then(Value::as_str) == command_id
17471                })
17472            })
17473            .or_else(|| {
17474                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
17475                let signal = signals
17476                    .iter()
17477                    .filter(|signal| {
17478                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
17479                    })
17480                    .nth(*offset);
17481                if signal.is_some() {
17482                    *offset += 1;
17483                }
17484                signal
17485            });
17486        let Some(signal) = matched else {
17487            continue;
17488        };
17489        let signal_codec = signal
17490            .get("payload_codec")
17491            .and_then(Value::as_str)
17492            .unwrap_or(&export_codec);
17493        let Some(payload) = event.payload.as_object_mut() else {
17494            continue;
17495        };
17496        if missing_payload(payload.get("arguments")) {
17497            if let Some(arguments) = signal
17498                .get("arguments")
17499                .filter(|value| !missing_payload(Some(value)))
17500            {
17501                let envelope = match arguments {
17502                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
17503                    other => other.clone(),
17504                };
17505                payload.insert("arguments".to_string(), envelope);
17506            }
17507        }
17508        if payload
17509            .get("payload_codec")
17510            .and_then(Value::as_str)
17511            .unwrap_or_default()
17512            .is_empty()
17513        {
17514            payload.insert("payload_codec".to_string(), json!(signal_codec));
17515        }
17516    }
17517
17518    Ok(())
17519}
17520
17521fn missing_payload(value: Option<&Value>) -> bool {
17522    match value {
17523        None | Some(Value::Null) => true,
17524        Some(Value::String(value)) => value.is_empty(),
17525        Some(_) => false,
17526    }
17527}
17528
17529fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
17530    history_signal_events(
17531        &task.history_events,
17532        task.history_export.as_ref(),
17533        &task.payload_codec,
17534    )
17535}
17536
17537fn history_signal_events(
17538    history_events: &[HistoryEvent],
17539    history_export: Option<&Value>,
17540    payload_codec: &str,
17541) -> Result<Vec<QuerySignal>> {
17542    let export_signals = history_export
17543        .and_then(|export| export.get("signals"))
17544        .and_then(Value::as_array)
17545        .cloned()
17546        .unwrap_or_default();
17547    let export_codec = history_export
17548        .and_then(|export| export.get("payloads"))
17549        .and_then(|payloads| payloads.get("codec"))
17550        .and_then(Value::as_str)
17551        .unwrap_or(payload_codec);
17552    let mut name_offsets: HashMap<String, usize> = HashMap::new();
17553    let mut signals: Vec<QuerySignal> = Vec::new();
17554    let mut signal_indices = HashMap::new();
17555    let mut command_indices = HashMap::new();
17556
17557    for event in history_events {
17558        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
17559            continue;
17560        }
17561
17562        let name = event
17563            .payload
17564            .get("signal_name")
17565            .and_then(Value::as_str)
17566            .unwrap_or_default();
17567        if name.is_empty() {
17568            continue;
17569        }
17570        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
17571        let command_id = event
17572            .payload
17573            .get("workflow_command_id")
17574            .or_else(|| event.raw.get("workflow_command_id"))
17575            .and_then(Value::as_str);
17576        let matched_export = export_signals
17577            .iter()
17578            .find(|candidate| {
17579                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
17580            })
17581            .or_else(|| {
17582                export_signals.iter().find(|candidate| {
17583                    command_id.is_some()
17584                        && candidate.get("command_id").and_then(Value::as_str) == command_id
17585                })
17586            })
17587            .or_else(|| {
17588                let offset = name_offsets.entry(name.to_string()).or_default();
17589                let candidate = export_signals
17590                    .iter()
17591                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
17592                    .nth(*offset);
17593                if candidate.is_some() {
17594                    *offset += 1;
17595                }
17596                candidate
17597            });
17598        let codec = event
17599            .payload
17600            .get("payload_codec")
17601            .and_then(Value::as_str)
17602            .or_else(|| {
17603                matched_export
17604                    .and_then(|signal| signal.get("payload_codec"))
17605                    .and_then(Value::as_str)
17606            })
17607            .unwrap_or(export_codec);
17608        let raw_arguments = signal_history_payload(&event.payload)
17609            .filter(|value| !value.is_null())
17610            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
17611        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
17612        let workflow_sequence = event
17613            .payload
17614            .get("workflow_sequence")
17615            .and_then(value_as_u64)
17616            .or_else(|| {
17617                matched_export
17618                    .and_then(|signal| signal.get("workflow_sequence"))
17619                    .and_then(value_as_u64)
17620            });
17621
17622        let id = signal_id.or_else(|| {
17623            matched_export
17624                .and_then(|signal| signal.get("id"))
17625                .and_then(Value::as_str)
17626        });
17627        let command_id = command_id.or_else(|| {
17628            matched_export
17629                .and_then(|signal| signal.get("command_id"))
17630                .and_then(Value::as_str)
17631        });
17632        let duplicate = id
17633            .and_then(|id| signal_indices.get(id))
17634            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
17635            .copied();
17636        let index = duplicate.unwrap_or(signals.len());
17637        if let Some(index) = duplicate {
17638            let original = &mut signals[index];
17639            let same_arguments = if event.event_type == "SignalApplied" {
17640                if let Some(value) = event.payload.get("value") {
17641                    let expected = match original.avro_arguments.as_slice() {
17642                        [] => AvroValue::Boolean(true),
17643                        [value] => value.clone(),
17644                        values => AvroValue::Array(values.to_vec()),
17645                    };
17646                    let applied = decode_wire_avro_value(value, codec)?;
17647                    applied == expected
17648                        || applied == AvroValue::Array(original.avro_arguments.clone())
17649                } else {
17650                    original.avro_arguments == avro_arguments
17651                }
17652            } else {
17653                original.avro_arguments == avro_arguments
17654            };
17655            if original.name != name
17656                || !same_arguments
17657                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
17658            {
17659                return Err(Error::Codec("conflicting committed signal identity".into()));
17660            }
17661            if original.id.is_none() {
17662                original.id = id.map(str::to_string);
17663            }
17664            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
17665        } else {
17666            signals.push(QuerySignal {
17667                id: id.map(str::to_string),
17668                name: name.to_string(),
17669                arguments,
17670                avro_arguments,
17671                workflow_sequence,
17672            });
17673        }
17674        if let Some(id) = id {
17675            signal_indices.insert(id.to_string(), index);
17676        }
17677        if let Some(id) = command_id {
17678            command_indices.insert(id.to_string(), index);
17679        }
17680    }
17681
17682    if signals.is_empty() {
17683        for signal in export_signals {
17684            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
17685                continue;
17686            }
17687            let Some(name) = signal.get("name").and_then(Value::as_str) else {
17688                continue;
17689            };
17690            let codec = signal
17691                .get("payload_codec")
17692                .and_then(Value::as_str)
17693                .unwrap_or(export_codec);
17694            let (arguments, avro_arguments) =
17695                decode_query_signal_arguments(signal.get("arguments"), codec)?;
17696            signals.push(QuerySignal {
17697                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
17698                name: name.to_string(),
17699                arguments,
17700                avro_arguments,
17701                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
17702            });
17703        }
17704        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
17705    }
17706
17707    Ok(signals)
17708}
17709
17710fn decode_query_signal_arguments(
17711    raw: Option<&Value>,
17712    codec: &str,
17713) -> Result<(Vec<Value>, Vec<AvroValue>)> {
17714    validate_payload_codec(codec)?;
17715    let decoded = match raw.filter(|value| !value.is_null()) {
17716        Some(value) => decode_wire_avro_value(value, codec)?,
17717        None => AvroValue::Array(Vec::new()),
17718    };
17719    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
17720        unreachable!("normalize_avro_arguments always returns an array");
17721    };
17722    let arguments = avro_arguments
17723        .iter()
17724        .cloned()
17725        .map(AvroValue::into_json)
17726        .collect::<Result<Vec<_>>>()?;
17727    Ok((arguments, avro_arguments))
17728}
17729
17730fn value_as_u64(value: &Value) -> Option<u64> {
17731    value
17732        .as_u64()
17733        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
17734}
17735
17736#[cfg(test)]
17737mod tests {
17738    use super::*;
17739    mod activity_cancellation_policies;
17740    mod cancellation_scope_admission;
17741    mod cancellation_scope_authoring;
17742    mod cancellation_scope_history;
17743    mod cancellation_scope_opening;
17744    mod cancellation_scope_replay;
17745    mod child_workflow_policies;
17746    mod cooperative_cancellation;
17747    mod local_activity;
17748    mod runtime_payloads;
17749    mod runtime_uploads;
17750    mod worker_session;
17751    use std::{
17752        fs,
17753        io::{Read, Write},
17754        net::{SocketAddr, TcpListener, TcpStream},
17755        process::Command as ProcessCommand,
17756        sync::atomic::AtomicUsize,
17757        thread,
17758    };
17759
17760    #[derive(Clone, Copy, Debug)]
17761    enum InvalidTaskPayloadCodec {
17762        Missing,
17763        Null,
17764        NonString,
17765    }
17766
17767    impl InvalidTaskPayloadCodec {
17768        fn label(self) -> &'static str {
17769            match self {
17770                Self::Missing => "missing",
17771                Self::Null => "null",
17772                Self::NonString => "non-string",
17773            }
17774        }
17775
17776        fn apply(self, task: &mut Value) {
17777            let task = task.as_object_mut().expect("task fixture object");
17778            match self {
17779                Self::Missing => {
17780                    task.remove("payload_codec");
17781                }
17782                Self::Null => {
17783                    task.insert("payload_codec".to_string(), Value::Null);
17784                }
17785                Self::NonString => {
17786                    task.insert("payload_codec".to_string(), json!(42));
17787                }
17788            }
17789        }
17790    }
17791
17792    fn fixture_envelope(value: Value) -> Value {
17793        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
17794    }
17795
17796    fn fixture_blob(value: Value) -> String {
17797        encode_payload(&value, DEFAULT_CODEC)
17798            .expect("encode Avro test fixture")
17799            .blob
17800    }
17801
17802    #[test]
17803    fn client_builder_rejects_the_sdk_owned_api_suffix() {
17804        for base_url in [
17805            "http://127.0.0.1:8080/api",
17806            "http://localhost:8080/api/",
17807            "https://runtime.example.test/namespaces/orders/api",
17808        ] {
17809            let error = Client::builder(base_url)
17810                .build()
17811                .expect_err("SDK-owned /api suffix must be rejected during build");
17812
17813            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
17814            assert!(
17815                error.to_string().contains("SDK appends /api automatically"),
17816                "the validation error must explain how to fix the endpoint"
17817            );
17818        }
17819    }
17820
17821    #[test]
17822    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
17823        for (base_url, expected) in [
17824            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
17825            (
17826                "http://localhost:8080/durable-workflow/",
17827                "http://localhost:8080/durable-workflow",
17828            ),
17829            (
17830                "https://runtime.example.test/namespaces/orders",
17831                "https://runtime.example.test/namespaces/orders",
17832            ),
17833            (
17834                "https://runtime.example.test/gateway/api/namespaces/orders",
17835                "https://runtime.example.test/gateway/api/namespaces/orders",
17836            ),
17837            (
17838                "https://api.example.test/runtime/orders/",
17839                "https://api.example.test/runtime/orders",
17840            ),
17841        ] {
17842            let client = Client::builder(base_url)
17843                .build()
17844                .expect("Server and Cloud runtime base URL must remain valid");
17845
17846            assert_eq!(client.base_url, expected);
17847        }
17848    }
17849
17850    #[test]
17851    fn workflow_completion_uses_the_additive_command_protocol_floor() {
17852        assert_eq!(
17853            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
17854            MINIMUM_WORKER_PROTOCOL_VERSION
17855        );
17856        assert_eq!(
17857            workflow_completion_protocol_version(&[json!({
17858                "type": "upsert_search_attributes",
17859                "attributes": {"OrderStatus": "waiting"},
17860            })]),
17861            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
17862        );
17863        assert_eq!(
17864            workflow_completion_protocol_version(&[json!({
17865                "type": "upsert_search_attributes",
17866                "attributes": {"OrderStatus": "waiting"},
17867                "attribute_types": {"OrderStatus": "keyword"},
17868            })]),
17869            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
17870        );
17871        assert_eq!(
17872            workflow_completion_protocol_version(&[
17873                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
17874                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17875            ]),
17876            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
17877        );
17878        assert_eq!(
17879            workflow_completion_protocol_version(&[
17880                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
17881                json!({"type": "open_condition_wait", "condition_key": "ready"}),
17882            ]),
17883            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
17884        );
17885        assert_eq!(
17886            workflow_completion_protocol_version(&[json!({
17887                "type": "open_condition_wait",
17888                "condition_wait_occurrence_id": "rust:condition-wait:0",
17889                "condition_key": "ready",
17890            })]),
17891            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17892        );
17893        assert_eq!(
17894            workflow_completion_protocol_version_with_message_streams(
17895                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
17896                true,
17897            ),
17898            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
17899        );
17900        assert_eq!(
17901            workflow_completion_protocol_version_with_message_streams(
17902                &[json!({
17903                    "type": "open_condition_wait",
17904                    "condition_wait_occurrence_id": "rust:condition-wait:0",
17905                    "condition_key": "ready",
17906                })],
17907                true,
17908            ),
17909            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
17910        );
17911    }
17912
17913    #[test]
17914    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
17915        let manifest = portable_worker_affinity_capability_manifest();
17916
17917        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
17918            assert_eq!(manifest[capability]["supported"], json!(false));
17919            assert_eq!(
17920                manifest[capability]["minimum_protocol_version"],
17921                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
17922            );
17923            assert!(manifest[capability]["reason"]
17924                .as_str()
17925                .is_some_and(|reason| !reason.is_empty()));
17926        }
17927    }
17928
17929    fn typed_fidelity_probe() -> AvroValue {
17930        AvroValue::Map(BTreeMap::from([
17931            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
17932            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
17933            (
17934                "numeric".to_string(),
17935                AvroValue::Map(BTreeMap::from([
17936                    ("0".to_string(), AvroValue::String("zero".to_string())),
17937                    ("1".to_string(), AvroValue::String("one".to_string())),
17938                ])),
17939            ),
17940            (
17941                "nested".to_string(),
17942                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
17943                    "enabled".to_string(),
17944                    AvroValue::Boolean(true),
17945                )]))]),
17946            ),
17947            (
17948                "projection_collisions".to_string(),
17949                AvroValue::Array(projection_collision_probe()),
17950            ),
17951        ]))
17952    }
17953
17954    fn projection_collision_probe() -> Vec<AvroValue> {
17955        vec![
17956            AvroValue::Map(BTreeMap::from([
17957                ("$type".to_string(), AvroValue::String("bytes".to_string())),
17958                (
17959                    "base64".to_string(),
17960                    AvroValue::String("ordinary user text".to_string()),
17961                ),
17962            ])),
17963            AvroValue::Map(BTreeMap::from([
17964                ("$type".to_string(), AvroValue::String("map".to_string())),
17965                (
17966                    "entries".to_string(),
17967                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
17968                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
17969                        (
17970                            "value".to_string(),
17971                            AvroValue::String("user map".to_string()),
17972                        ),
17973                    ]))]),
17974                ),
17975            ])),
17976        ]
17977    }
17978
17979    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17980    struct TypedContract {
17981        nested: TypedNested,
17982        mode: TypedMode,
17983        optional: Option<String>,
17984        absent: Option<String>,
17985        items: Vec<i64>,
17986        labels: BTreeMap<String, String>,
17987        bytes: serde_bytes::ByteBuf,
17988        signed: i64,
17989        finite: f64,
17990    }
17991
17992    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17993    struct TypedNested {
17994        enabled: bool,
17995    }
17996
17997    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
17998    enum TypedMode {
17999        Detailed { label: String },
18000    }
18001
18002    fn typed_contract() -> TypedContract {
18003        TypedContract {
18004            nested: TypedNested { enabled: true },
18005            mode: TypedMode::Detailed {
18006                label: "compiler-checked".to_string(),
18007            },
18008            optional: Some("present".to_string()),
18009            absent: None,
18010            items: vec![i64::MIN, 0, i64::MAX],
18011            labels: BTreeMap::from([
18012                ("language".to_string(), "rust".to_string()),
18013                ("wire".to_string(), "avro".to_string()),
18014            ]),
18015            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
18016            signed: -9_223_372_036_854_775_000,
18017            finite: 12.5,
18018        }
18019    }
18020
18021    #[derive(Clone, Debug, Default, PartialEq)]
18022    struct ReplayCounterState {
18023        loaded: Option<String>,
18024        count: i64,
18025        finished: bool,
18026    }
18027
18028    fn replay_counter_worker() -> Worker {
18029        let client = Client::new("http://127.0.0.1:8080").expect("client");
18030        let mut worker = Worker::new(client, "rust-workers");
18031        worker.register_replayed_workflow(
18032            "replay-counter",
18033            ReplayCounterState::default,
18034            |ctx, _input, state| async move {
18035                let loaded = ctx.activity("load-counter", json!([])).await?;
18036                state.update(|current| {
18037                    current.loaded = loaded.as_str().map(str::to_string);
18038                })?;
18039                for _ in 0..2 {
18040                    let signal = ctx.wait_signal("increment").await?;
18041                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
18042                    state.update(|current| current.count += amount)?;
18043                }
18044                state.update(|current| current.finished = true)?;
18045                state.read(|current| Ok(json!(current.count)))?
18046            },
18047        );
18048        worker.register_replayed_query::<ReplayCounterState, _, _>(
18049            "replay-counter",
18050            "current",
18051            |_ctx, state, _args| async move {
18052                Ok(json!({
18053                    "loaded": state.loaded,
18054                    "count": state.count,
18055                    "finished": state.finished,
18056                }))
18057            },
18058        );
18059        worker.register_replayed_query::<ReplayCounterState, _, _>(
18060            "replay-counter",
18061            "detached-mutation",
18062            |_ctx, state, _args| async move {
18063                let mut detached = (*state).clone();
18064                detached.count = 999;
18065                Ok(json!(detached.count))
18066            },
18067        );
18068        worker.register_replayed_query::<ReplayCounterState, _, _>(
18069            "replay-counter",
18070            "failed-mutation",
18071            |_ctx, state, _args| async move {
18072                let mut detached = (*state).clone();
18073                detached.count = 999;
18074                Err(Error::WorkerLoop("query refused".to_string()))
18075            },
18076        );
18077        worker
18078    }
18079
18080    fn replay_counter_query(
18081        query_name: &str,
18082        history_events: Value,
18083        run_status: &str,
18084    ) -> QueryTask {
18085        let arguments = fixture_envelope(json!([]));
18086        serde_json::from_value(json!({
18087            "query_task_id": format!("query-{query_name}"),
18088            "workflow_type": "replay-counter",
18089            "query_name": query_name,
18090            "payload_codec": DEFAULT_CODEC,
18091            "workflow_arguments": arguments.clone(),
18092            "query_arguments": arguments,
18093            "history_events": history_events,
18094            "run_status": run_status,
18095        }))
18096        .expect("query task")
18097    }
18098
18099    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
18100        workflow_context_with_codec(history, DEFAULT_CODEC)
18101    }
18102
18103    fn workflow_context_with_codec(
18104        history: Vec<HistoryEvent>,
18105        payload_codec: &str,
18106    ) -> WorkflowContext {
18107        WorkflowContext {
18108            cancellation_scope_id: "root".into(),
18109            state: Arc::new(Mutex::new(
18110                WorkflowState::new_with_identity(
18111                    history,
18112                    None,
18113                    None,
18114                    "rust-workers".to_string(),
18115                    payload_codec.to_string(),
18116                    None,
18117                )
18118                .expect("valid workflow history"),
18119            )),
18120        }
18121    }
18122
18123    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
18124        HistoryEvent {
18125            event_type: event_type.to_string(),
18126            payload,
18127            raw: HashMap::new(),
18128        }
18129    }
18130
18131    fn parallel_path_entry(
18132        kind: &str,
18133        base: u64,
18134        size: usize,
18135        index: usize,
18136    ) -> ParallelGroupMetadata {
18137        parallel_group_entry(base, size, index, kind)
18138    }
18139
18140    fn parallel_history_event(
18141        event_type: &str,
18142        sequence: u64,
18143        identity_field: &str,
18144        identity: &str,
18145        path: Vec<ParallelGroupMetadata>,
18146        result: Option<Value>,
18147    ) -> HistoryEvent {
18148        let mut payload = serde_json::Map::from_iter([
18149            ("sequence".to_string(), json!(sequence)),
18150            (identity_field.to_string(), json!(identity)),
18151        ]);
18152        let inner = path.last().expect("parallel history path");
18153        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
18154        payload.insert("parallel_group_path".to_string(), json!(path));
18155        if let Some(result) = result {
18156            let field = if event_type == "ChildRunCompleted" {
18157                "result"
18158            } else {
18159                "result"
18160            };
18161            payload.insert(field.to_string(), fixture_envelope(result));
18162            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
18163        }
18164        history_event(event_type, Value::Object(payload))
18165    }
18166
18167    fn nested_parallel_operations() -> Vec<ParallelOperation> {
18168        vec![
18169            ParallelOperation::activity("first", json!([])),
18170            ParallelOperation::group(vec![
18171                ParallelOperation::child_workflow(
18172                    "second",
18173                    ChildWorkflowOptions::new("child-workers"),
18174                    json!([]),
18175                ),
18176                ParallelOperation::activity("third", json!([])),
18177            ]),
18178        ]
18179    }
18180
18181    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
18182        let outer = [
18183            parallel_path_entry("mixed", 1, 3, 0),
18184            parallel_path_entry("mixed", 1, 3, 1),
18185            parallel_path_entry("mixed", 1, 3, 2),
18186        ];
18187        [
18188            vec![outer[0].clone()],
18189            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
18190            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
18191        ]
18192    }
18193
18194    #[test]
18195    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
18196        let ctx = workflow_context(Vec::new());
18197        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18198        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18199
18200        assert!(matches!(
18201            call.as_mut().poll(&mut task_context),
18202            Poll::Pending
18203        ));
18204        let commands = ctx.take_commands().expect("parallel commands");
18205        assert_eq!(
18206            commands
18207                .iter()
18208                .map(|command| command["type"].as_str().unwrap_or_default())
18209                .collect::<Vec<_>>(),
18210            [
18211                "schedule_activity",
18212                "start_child_workflow",
18213                "schedule_activity"
18214            ]
18215        );
18216        let paths = nested_parallel_paths();
18217        for (command, path) in commands.iter().zip(paths) {
18218            assert_eq!(command["parallel_group_path"], json!(path));
18219            assert_eq!(
18220                command["parallel_group_id"],
18221                json!(path.last().expect("inner group").parallel_group_id)
18222            );
18223        }
18224    }
18225
18226    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
18227        let paths = nested_parallel_paths();
18228        let third = parallel_history_event(
18229            "ActivityCompleted",
18230            3,
18231            "activity_type",
18232            "third",
18233            paths[2].clone(),
18234            Some(json!("three")),
18235        );
18236        vec![
18237            parallel_history_event(
18238                "ActivityCompleted",
18239                1,
18240                "activity_type",
18241                "first",
18242                paths[0].clone(),
18243                Some(json!("one")),
18244            ),
18245            parallel_history_event(
18246                "ChildWorkflowScheduled",
18247                2,
18248                "child_workflow_type",
18249                "second",
18250                paths[1].clone(),
18251                None,
18252            ),
18253            parallel_history_event(
18254                "ChildRunCompleted",
18255                2,
18256                "child_workflow_type",
18257                "second",
18258                paths[1].clone(),
18259                Some(json!("two")),
18260            ),
18261            third.clone(),
18262            third,
18263        ]
18264    }
18265
18266    #[test]
18267    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
18268        for _restart_or_completed_replay in 0..2 {
18269            let ctx = workflow_context(completed_nested_parallel_history());
18270            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18271            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18272            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
18273                panic!("completed nested parallel history must replay");
18274            };
18275            assert_eq!(
18276                results,
18277                vec![
18278                    ParallelResult::Activity(json!("one")),
18279                    ParallelResult::Group(vec![
18280                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
18281                            parent: WorkflowIdentity {
18282                                workflow_id: None,
18283                                run_id: None,
18284                            },
18285                            child: WorkflowIdentity {
18286                                workflow_id: None,
18287                                run_id: None,
18288                            },
18289                            child_workflow_type: Some("second".to_string()),
18290                            result: json!("two"),
18291                        }),
18292                        ParallelResult::Activity(json!("three")),
18293                    ]),
18294                ]
18295            );
18296            assert!(ctx.take_commands().expect("commands").is_empty());
18297            ctx.ensure_history_consumed().expect("history consumed");
18298        }
18299    }
18300
18301    #[test]
18302    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
18303        let paths = nested_parallel_paths();
18304        let history = vec![
18305            parallel_history_event(
18306                "ActivityCompleted",
18307                1,
18308                "activity_type",
18309                "first",
18310                paths[0].clone(),
18311                Some(json!("one")),
18312            ),
18313            parallel_history_event(
18314                "ChildWorkflowScheduled",
18315                2,
18316                "child_workflow_type",
18317                "second",
18318                paths[1].clone(),
18319                None,
18320            ),
18321            parallel_history_event(
18322                "ChildRunFailed",
18323                2,
18324                "child_workflow_type",
18325                "second",
18326                paths[1].clone(),
18327                None,
18328            ),
18329            parallel_history_event(
18330                "ActivityCompleted",
18331                3,
18332                "activity_type",
18333                "third",
18334                paths[2].clone(),
18335                Some(json!("late")),
18336            ),
18337        ];
18338        let ctx = workflow_context(history);
18339        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18340        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18341        let outcome = call.as_mut().poll(&mut task_context);
18342        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
18343            panic!("one failed child must return a typed partial failure: {outcome:?}");
18344        };
18345        assert_eq!(failure.member_path, [1, 0]);
18346        assert_eq!(failure.group_id, "parallel-calls:1:3");
18347        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
18348        assert_eq!(
18349            failure
18350                .completed
18351                .iter()
18352                .map(|completion| completion.member_path.clone())
18353                .collect::<Vec<_>>(),
18354            [vec![0], vec![1, 1]]
18355        );
18356    }
18357
18358    #[test]
18359    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
18360        let paths = nested_parallel_paths();
18361        let history = vec![
18362            parallel_history_event(
18363                "ActivityScheduled",
18364                1,
18365                "activity_type",
18366                "first",
18367                paths[0].clone(),
18368                None,
18369            ),
18370            parallel_history_event(
18371                "ChildWorkflowScheduled",
18372                2,
18373                "child_workflow_type",
18374                "second",
18375                paths[1].clone(),
18376                None,
18377            ),
18378            parallel_history_event(
18379                "ActivityScheduled",
18380                3,
18381                "activity_type",
18382                "third",
18383                paths[2].clone(),
18384                None,
18385            ),
18386        ];
18387        for _restart in 0..2 {
18388            let ctx = workflow_context(history.clone());
18389            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
18390            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18391            let outcome = call.as_mut().poll(&mut task_context);
18392            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
18393            assert!(ctx.take_commands().expect("commands").is_empty());
18394        }
18395    }
18396
18397    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
18398        vec![selection_group_entry(
18399            1,
18400            2,
18401            index,
18402            "activity",
18403            &SelectionMemberMetadata {
18404                key: SelectionKey::Name(key.to_string()),
18405                index,
18406                base_sequence: index as u64 + 1,
18407                size: 1,
18408                kind: "activity".to_string(),
18409            },
18410        )]
18411    }
18412
18413    fn selection_activity_event(
18414        event_type: &str,
18415        index: usize,
18416        key: &str,
18417        result: Option<Value>,
18418    ) -> HistoryEvent {
18419        let sequence = index as u64 + 1;
18420        let mut event = parallel_history_event(
18421            event_type,
18422            sequence,
18423            "activity_type",
18424            &format!("{key}-activity"),
18425            selection_path(index, key),
18426            result,
18427        );
18428        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
18429        event.raw.insert(
18430            "id".to_string(),
18431            json!(if event_type == "ActivityCompleted" {
18432                format!("event-{key}")
18433            } else {
18434                format!("{event_type}-{key}")
18435            }),
18436        );
18437        event
18438    }
18439
18440    fn selection_winner_marker() -> HistoryEvent {
18441        history_event(
18442            "SelectionResolved",
18443            json!({
18444                "selection_group_id": "select-calls:1:2",
18445                "selection_group_base_sequence": 1,
18446                "selection_group_size": 2,
18447                "member_key": "fast",
18448                "member_index": 1,
18449                "member_base_sequence": 2,
18450                "member_size": 1,
18451                "operation_kind": "activity",
18452                "operation_identity": "activity-fast",
18453                "outcome": "completed",
18454                "resolution_event_id": "event-fast",
18455                "resolution_event_type": "ActivityCompleted",
18456            }),
18457        )
18458    }
18459
18460    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
18461        ctx.select_keyed(vec![
18462            (
18463                "slow",
18464                ParallelOperation::activity_with_options(
18465                    "slow-activity",
18466                    ActivityOptions::new().task_queue("default"),
18467                    json!([]),
18468                ),
18469            ),
18470            (
18471                "fast",
18472                ParallelOperation::activity_with_options(
18473                    "fast-activity",
18474                    ActivityOptions::new().task_queue("default"),
18475                    json!([]),
18476                ),
18477            ),
18478        ])
18479    }
18480
18481    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
18482        let ctx = workflow_context(history);
18483        let mut call = Box::pin(keyed_activity_selection(&ctx));
18484        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18485        let selected = match call.as_mut().poll(&mut task_context) {
18486            Poll::Ready(Ok(selected)) => selected,
18487            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
18488            Poll::Pending => panic!("persisted selection winner must replay without pending"),
18489        };
18490        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
18491        assert_eq!(
18492            selected.value,
18493            Some(ParallelResult::Activity(json!("winner-value")))
18494        );
18495        let slow = selected
18496            .handle(&SelectionKey::Name("slow".to_string()))
18497            .expect("slow handle")
18498            .clone();
18499        let mut await_slow = Box::pin(slow.await_result());
18500        assert!(matches!(
18501            await_slow.as_mut().poll(&mut task_context),
18502            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
18503        ));
18504        assert!(ctx.take_commands().expect("commands").is_empty());
18505    }
18506
18507    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
18508
18509    fn canonical_selection_history() -> Vec<HistoryEvent> {
18510        const FIXTURE: &[u8] =
18511            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
18512        assert_eq!(
18513            format!("{:x}", Sha256::digest(FIXTURE)),
18514            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18515        );
18516        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
18517
18518        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
18519    }
18520
18521    #[test]
18522    fn selection_fresh_process_entrypoint() {
18523        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
18524            return;
18525        };
18526        let persisted = fs::read(path).expect("persisted selection history");
18527        assert_eq!(
18528            format!("{:x}", Sha256::digest(&persisted)),
18529            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
18530        );
18531        let fixture: Value =
18532            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
18533        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
18534            .expect("valid persisted selection history");
18535
18536        assert_persisted_selection_replay(history);
18537    }
18538
18539    #[test]
18540    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
18541        let ctx = workflow_context(Vec::new());
18542        let mut call = Box::pin(keyed_activity_selection(&ctx));
18543        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18544
18545        assert!(matches!(
18546            call.as_mut().poll(&mut task_context),
18547            Poll::Pending
18548        ));
18549        let commands = ctx.take_commands().expect("selection commands");
18550        assert_eq!(commands.len(), 2);
18551        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
18552        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
18553        assert!(commands.iter().all(|command| {
18554            command["parallel_group_id"] == json!("select-calls:1:2")
18555                && command["parallel_group_mode"] == json!("select")
18556        }));
18557    }
18558
18559    #[test]
18560    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
18561        let ctx = workflow_context(Vec::new());
18562        let mut invalid = Box::pin(ctx.select_keyed(vec![(
18563            "",
18564            ParallelOperation::activity("invalid", json!([])),
18565        )]));
18566        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18567        assert!(matches!(
18568            invalid.as_mut().poll(&mut task_context),
18569            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
18570                reason: "selection_key_invalid",
18571                ..
18572            })))
18573        ));
18574
18575        for invalid_key in [json!(""), json!(-1)] {
18576            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
18577            event.payload["selection_member_key"] = invalid_key.clone();
18578            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
18579            assert!(matches!(
18580                WorkflowState::new_with_identity(
18581                    vec![event],
18582                    None,
18583                    None,
18584                    "rust-workers".to_string(),
18585                    DEFAULT_CODEC.to_string(),
18586                    None,
18587                ),
18588                Err(Error::NonDeterministicReplay(_))
18589            ));
18590        }
18591    }
18592
18593    #[test]
18594    fn selection_preserves_valid_named_and_numeric_keys() {
18595        let ctx = workflow_context(Vec::new());
18596        let mut selection = Box::pin(ctx.select_keyed(vec![
18597            (
18598                SelectionKey::Index(0),
18599                ParallelOperation::activity("numeric", json!([])),
18600            ),
18601            (
18602                SelectionKey::Name("named".to_string()),
18603                ParallelOperation::timer(Duration::from_secs(1)),
18604            ),
18605        ]));
18606        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18607
18608        assert!(matches!(
18609            selection.as_mut().poll(&mut task_context),
18610            Poll::Pending
18611        ));
18612        let commands = ctx.take_commands().expect("selection commands");
18613        assert_eq!(commands[0]["selection_member_key"], json!(0));
18614        assert_eq!(commands[1]["selection_member_key"], json!("named"));
18615    }
18616
18617    #[test]
18618    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
18619        let history = canonical_selection_history();
18620        assert_persisted_selection_replay(history.clone());
18621
18622        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18623            .join("tests/fixtures/durable_selection_runtime_history.json");
18624        let output =
18625            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
18626                .args([
18627                    "--exact",
18628                    "tests::selection_fresh_process_entrypoint",
18629                    "--nocapture",
18630                ])
18631                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
18632                .output()
18633                .expect("run fresh selection replay process");
18634
18635        assert!(
18636            output.status.success(),
18637            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
18638            String::from_utf8_lossy(&output.stdout),
18639            String::from_utf8_lossy(&output.stderr),
18640        );
18641    }
18642
18643    #[test]
18644    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
18645        let mut history = canonical_selection_history();
18646        history.retain(|event| event.event_type != "SelectionResolved");
18647        let ctx = workflow_context(history);
18648        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18649        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18650
18651        assert!(matches!(
18652            selection.as_mut().poll(&mut task_context),
18653            Poll::Pending
18654        ));
18655        assert!(ctx.take_commands().expect("commands").is_empty());
18656        assert!(
18657            ctx.matched_recorded_pending()
18658                .expect("selection pending state"),
18659            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
18660        );
18661    }
18662
18663    #[test]
18664    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
18665        for (terminal_event, predicate_satisfied, timeout_seconds) in [
18666            ("ConditionWaitSatisfied", true, None),
18667            ("ConditionWaitTimedOut", false, Some(0)),
18668        ] {
18669            let member = SelectionMemberMetadata {
18670                key: SelectionKey::Name("condition".to_string()),
18671                index: 0,
18672                base_sequence: 1,
18673                size: 1,
18674                kind: "condition".to_string(),
18675            };
18676            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
18677            let mut payload = json!({
18678                "sequence": 1,
18679                "condition_wait_id": "condition-1",
18680                "condition_wait_occurrence_id": "rust:condition-wait:0",
18681                "condition_key": "ready",
18682                "condition_definition_fingerprint": "sha256:ready-v1",
18683                "parallel_group_path": path,
18684            });
18685            payload
18686                .as_object_mut()
18687                .expect("condition history payload")
18688                .extend(
18689                    serde_json::to_value(&path[0])
18690                        .expect("condition selection metadata")
18691                        .as_object()
18692                        .expect("condition selection metadata object")
18693                        .clone(),
18694                );
18695            if let Some(timeout_seconds) = timeout_seconds {
18696                payload["timeout_seconds"] = json!(timeout_seconds);
18697            }
18698            let history = vec![
18699                history_event("ConditionWaitOpened", payload.clone()),
18700                history_event(terminal_event, payload),
18701            ];
18702            let ctx = workflow_context(history);
18703            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
18704            if timeout_seconds.is_some() {
18705                options = options.timeout(Duration::ZERO);
18706            }
18707            let mut selection = Box::pin(ctx.select_keyed(vec![(
18708                "condition",
18709                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
18710            )]));
18711            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18712
18713            assert!(matches!(
18714                selection.as_mut().poll(&mut task_context),
18715                Poll::Pending
18716            ));
18717            assert!(ctx.take_commands().expect("commands").is_empty());
18718            assert!(
18719                ctx.matched_recorded_pending()
18720                    .expect("condition selection pending state"),
18721                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
18722            );
18723        }
18724    }
18725
18726    #[test]
18727    fn selection_immediate_condition_members_open_a_durable_wait() {
18728        for predicate_satisfied in [true, false] {
18729            let ctx = workflow_context(Vec::new());
18730            let mut selection = Box::pin(ctx.select_keyed(vec![(
18731                "condition",
18732                ParallelOperation::condition(
18733                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
18734                    move || Ok(predicate_satisfied),
18735                ),
18736            )]));
18737            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18738
18739            assert!(matches!(
18740                selection.as_mut().poll(&mut task_context),
18741                Poll::Pending
18742            ));
18743            let commands = ctx.take_commands().expect("condition selection command");
18744            assert_eq!(commands.len(), 1);
18745            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
18746            assert_eq!(commands[0]["timeout_seconds"], json!(0));
18747            assert_eq!(
18748                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
18749                json!("select")
18750            );
18751        }
18752    }
18753
18754    #[test]
18755    fn selection_loser_cancellation_is_explicit_and_idempotent() {
18756        let history = vec![
18757            selection_activity_event("ActivityScheduled", 0, "slow", None),
18758            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18759            selection_winner_marker(),
18760        ];
18761        let ctx = workflow_context(history.clone());
18762        let mut call = Box::pin(keyed_activity_selection(&ctx));
18763        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18764        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18765            panic!("winner must replay");
18766        };
18767        let slow = selected
18768            .handle(&SelectionKey::Name("slow".to_string()))
18769            .expect("slow handle")
18770            .clone();
18771        let mut cancel = Box::pin(slow.cancel());
18772        assert!(matches!(
18773            cancel.as_mut().poll(&mut task_context),
18774            Poll::Pending
18775        ));
18776        assert!(matches!(
18777            cancel.as_mut().poll(&mut task_context),
18778            Poll::Pending
18779        ));
18780        let commands = ctx.take_commands().expect("cancel command");
18781        assert_eq!(commands.len(), 1);
18782        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
18783        assert_eq!(commands[0]["member_key"], json!("slow"));
18784
18785        let mut cancelled_history = history;
18786        cancelled_history.push(history_event(
18787            "SelectionOperationCancelled",
18788            json!({
18789                "selection_group_id": "select-calls:1:2",
18790                "member_key": "slow",
18791                "member_index": 0,
18792                "member_base_sequence": 1,
18793                "member_size": 1,
18794                "operation_kind": "activity",
18795                "operation_identity": "activity-slow",
18796                "cancelled_at": "2026-08-27T00:00:00Z",
18797            }),
18798        ));
18799        let replayed = workflow_context(cancelled_history);
18800        let mut call = Box::pin(keyed_activity_selection(&replayed));
18801        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
18802            panic!("winner must replay after cancellation");
18803        };
18804        let slow = selected
18805            .handle(&SelectionKey::Name("slow".to_string()))
18806            .expect("slow handle")
18807            .clone();
18808        let mut cancel = Box::pin(slow.cancel());
18809        assert!(matches!(
18810            cancel.as_mut().poll(&mut task_context),
18811            Poll::Ready(Ok(()))
18812        ));
18813        assert!(replayed.take_commands().expect("commands").is_empty());
18814    }
18815
18816    #[test]
18817    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
18818        let base_history = vec![
18819            selection_activity_event("ActivityScheduled", 0, "slow", None),
18820            selection_activity_event("ActivityScheduled", 1, "fast", None),
18821            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18822            selection_winner_marker(),
18823        ];
18824        for (field, corrupt) in [
18825            ("member_key", json!("fast")),
18826            ("member_index", json!(1)),
18827            ("member_base_sequence", json!(3)),
18828            ("member_size", json!(2)),
18829            ("operation_kind", json!("timer")),
18830            ("operation_identity", json!("forged")),
18831        ] {
18832            let mut cancellation = json!({
18833                "selection_group_id": "select-calls:1:2",
18834                "member_key": "slow",
18835                "member_index": 0,
18836                "member_base_sequence": 1,
18837                "member_size": 1,
18838                "operation_kind": "activity",
18839                "operation_identity": "activity-slow",
18840            });
18841            cancellation[field] = corrupt;
18842            let mut history = base_history.clone();
18843            history.push(history_event("SelectionOperationCancelled", cancellation));
18844            let ctx = workflow_context(history);
18845            let mut selection = Box::pin(keyed_activity_selection(&ctx));
18846            let mut task_context = TaskContext::from_waker(noop_waker_ref());
18847
18848            assert!(matches!(
18849                selection.as_mut().poll(&mut task_context),
18850                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18851            ));
18852        }
18853    }
18854
18855    #[test]
18856    fn selection_child_identity_prefers_the_durable_run_id() {
18857        let ctx = workflow_context(vec![history_event(
18858            "ChildWorkflowScheduled",
18859            json!({
18860                "sequence": 1,
18861                "child_workflow_type": "child",
18862                "child_workflow_instance_id": "child-instance",
18863                "child_workflow_run_id": "child-run",
18864            }),
18865        )]);
18866        let state = ctx.state.lock().expect("workflow state");
18867
18868        assert_eq!(
18869            selection_operation_identity(&state, "child", 1, 1),
18870            "child-run"
18871        );
18872    }
18873
18874    #[test]
18875    fn selection_activity_identity_requires_canonical_execution_id() {
18876        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
18877        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
18878        let mut fast_completed =
18879            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
18880        for event in [&mut fast_open, &mut fast_completed] {
18881            event
18882                .payload
18883                .as_object_mut()
18884                .expect("activity payload")
18885                .remove("activity_execution_id");
18886            event.payload["activity_id"] = json!("forged-activity-id");
18887        }
18888        let mut marker = selection_winner_marker();
18889        marker.payload["operation_identity"] = json!("forged-activity-id");
18890        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
18891        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18892        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18893
18894        assert!(matches!(
18895            selection.as_mut().poll(&mut task_context),
18896            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
18897        ));
18898    }
18899
18900    #[test]
18901    fn selection_completion_before_cancellation_remains_awaitable() {
18902        let history = vec![
18903            selection_activity_event("ActivityScheduled", 0, "slow", None),
18904            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
18905            selection_winner_marker(),
18906            selection_activity_event(
18907                "ActivityCompleted",
18908                0,
18909                "slow",
18910                Some(json!("completed-first")),
18911            ),
18912        ];
18913        let ctx = workflow_context(history);
18914        let mut selection = Box::pin(keyed_activity_selection(&ctx));
18915        let mut task_context = TaskContext::from_waker(noop_waker_ref());
18916        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
18917            panic!("winner must replay");
18918        };
18919        let slow = selected
18920            .handle(&SelectionKey::Name("slow".to_string()))
18921            .expect("slow handle")
18922            .clone();
18923        let mut cancel = Box::pin(slow.cancel());
18924        assert!(matches!(
18925            cancel.as_mut().poll(&mut task_context),
18926            Poll::Ready(Ok(()))
18927        ));
18928        let mut await_slow = Box::pin(slow.await_result());
18929        assert!(matches!(
18930            await_slow.as_mut().poll(&mut task_context),
18931            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
18932        ));
18933        let commands = ctx.take_commands().expect("commands");
18934        assert!(commands.is_empty());
18935    }
18936
18937    #[test]
18938    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
18939        let nested_member = SelectionMemberMetadata {
18940            key: SelectionKey::Name("nested".to_string()),
18941            index: 0,
18942            base_sequence: 1,
18943            size: 2,
18944            kind: "group".to_string(),
18945        };
18946        let deadline_member = SelectionMemberMetadata {
18947            key: SelectionKey::Name("deadline".to_string()),
18948            index: 1,
18949            base_sequence: 3,
18950            size: 1,
18951            kind: "timer".to_string(),
18952        };
18953        let nested_paths = [
18954            vec![
18955                selection_group_entry(1, 3, 0, "mixed", &nested_member),
18956                parallel_group_entry(1, 2, 0, "activity"),
18957            ],
18958            vec![
18959                selection_group_entry(1, 3, 1, "mixed", &nested_member),
18960                parallel_group_entry(1, 2, 1, "activity"),
18961            ],
18962        ];
18963        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
18964        let mut timer_fired = parallel_history_event(
18965            "TimerFired",
18966            3,
18967            "timer_id",
18968            "timer-3",
18969            deadline_path.clone(),
18970            None,
18971        );
18972        timer_fired.payload["delay_seconds"] = json!(0);
18973        timer_fired
18974            .raw
18975            .insert("id".to_string(), json!("timer-fired"));
18976        let mut timer_scheduled = parallel_history_event(
18977            "TimerScheduled",
18978            3,
18979            "timer_id",
18980            "timer-3",
18981            deadline_path,
18982            None,
18983        );
18984        timer_scheduled.payload["delay_seconds"] = json!(0);
18985        let history = vec![
18986            parallel_history_event(
18987                "ActivityScheduled",
18988                1,
18989                "activity_type",
18990                "nested-first",
18991                nested_paths[0].clone(),
18992                None,
18993            ),
18994            parallel_history_event(
18995                "ActivityScheduled",
18996                2,
18997                "activity_type",
18998                "nested-second",
18999                nested_paths[1].clone(),
19000                None,
19001            ),
19002            timer_scheduled,
19003            timer_fired,
19004            history_event(
19005                "SelectionResolved",
19006                json!({
19007                    "selection_group_id": "select-calls:1:3",
19008                    "selection_group_base_sequence": 1,
19009                    "selection_group_size": 3,
19010                    "member_key": "deadline",
19011                    "member_index": 1,
19012                    "member_base_sequence": 3,
19013                    "member_size": 1,
19014                    "operation_kind": "timer",
19015                    "operation_identity": "timer-3",
19016                    "outcome": "completed",
19017                    "resolution_event_id": "timer-fired",
19018                    "resolution_event_type": "TimerFired",
19019                }),
19020            ),
19021            parallel_history_event(
19022                "ActivityFailed",
19023                2,
19024                "activity_type",
19025                "nested-second",
19026                nested_paths[1].clone(),
19027                None,
19028            ),
19029        ];
19030        let ctx = workflow_context(history);
19031        let mut selection = Box::pin(ctx.select_keyed(vec![
19032            (
19033                "nested",
19034                ParallelOperation::group(vec![
19035                    ParallelOperation::activity("nested-first", json!([])),
19036                    ParallelOperation::activity("nested-second", json!([])),
19037                ]),
19038            ),
19039            ("deadline", ParallelOperation::timer(Duration::ZERO)),
19040        ]));
19041        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19042        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19043            panic!("deadline winner must replay");
19044        };
19045        let nested = selected
19046            .handle(&SelectionKey::Name("nested".to_string()))
19047            .expect("nested handle")
19048            .clone();
19049        let mut cancel = Box::pin(nested.cancel());
19050        assert!(matches!(
19051            cancel.as_mut().poll(&mut task_context),
19052            Poll::Ready(Ok(()))
19053        ));
19054        let mut await_nested = Box::pin(nested.await_result());
19055
19056        assert!(matches!(
19057            await_nested.as_mut().poll(&mut task_context),
19058            Poll::Ready(Err(Error::ActivityFailed(_)))
19059        ));
19060        assert!(ctx.take_commands().expect("commands").is_empty());
19061    }
19062
19063    #[test]
19064    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
19065        let ctx = workflow_context(Vec::new());
19066        let mut call = Box::pin(ctx.select(vec![
19067            ParallelOperation::child_workflow(
19068                "child",
19069                ChildWorkflowOptions::new("children"),
19070                json!([]),
19071            ),
19072            ParallelOperation::timer(Duration::from_secs(30)),
19073            ParallelOperation::signal("approval"),
19074            ParallelOperation::condition(
19075                ConditionWaitOptions::new("ready", "sha256:ready"),
19076                || Ok(false),
19077            ),
19078            ParallelOperation::group(vec![
19079                ParallelOperation::activity("nested-one", json!([])),
19080                ParallelOperation::activity("nested-two", json!([])),
19081            ]),
19082        ]));
19083        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19084        assert!(matches!(
19085            call.as_mut().poll(&mut task_context),
19086            Poll::Pending
19087        ));
19088        let commands = ctx.take_commands().expect("selection commands");
19089        assert_eq!(
19090            commands
19091                .iter()
19092                .map(|command| command["type"].as_str().unwrap_or_default())
19093                .collect::<Vec<_>>(),
19094            [
19095                "start_child_workflow",
19096                "start_timer",
19097                "open_signal_wait",
19098                "open_condition_wait",
19099                "schedule_activity",
19100                "schedule_activity",
19101            ]
19102        );
19103        assert!(commands.iter().all(|command| {
19104            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
19105        }));
19106        assert_eq!(
19107            commands[4]["parallel_group_path"].as_array().map(Vec::len),
19108            Some(2)
19109        );
19110        assert_eq!(
19111            commands[4]["parallel_group_path"][0]["selection_member_kind"],
19112            json!("group")
19113        );
19114        assert_eq!(
19115            commands[5]["parallel_group_path"][0]["selection_member_kind"],
19116            json!("group")
19117        );
19118
19119        let one_leaf_ctx = workflow_context(Vec::new());
19120        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
19121            ParallelOperation::activity("nested-only", json!([])),
19122        ])]));
19123        assert!(matches!(
19124            one_leaf.as_mut().poll(&mut task_context),
19125            Poll::Pending
19126        ));
19127        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
19128        assert_eq!(one_leaf_commands.len(), 1);
19129        assert_eq!(
19130            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
19131            json!("group")
19132        );
19133        assert_eq!(
19134            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
19135            json!(1)
19136        );
19137    }
19138
19139    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
19140        let mut saga = ctx.saga();
19141        let outcome = async {
19142            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19143            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19144            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
19145            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
19146            ctx.activity("trip.charge", json!([])).await?;
19147            Ok(json!({"status": "booked"}))
19148        }
19149        .await;
19150        saga.finish(outcome).await
19151    }
19152
19153    fn saga_activity(
19154        event_type: &str,
19155        sequence: u64,
19156        activity_type: &str,
19157        result: Option<Value>,
19158    ) -> HistoryEvent {
19159        let mut payload = json!({
19160            "sequence": sequence,
19161            "activity_type": activity_type,
19162            "message": format!("{activity_type} failed"),
19163            "exception_type": "PlannedFailure",
19164            "non_retryable": true,
19165        });
19166        if let Some(result) = result {
19167            payload["result"] = fixture_envelope(result);
19168        }
19169        history_event(event_type, payload)
19170    }
19171
19172    #[test]
19173    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
19174        let completed_hotel_compensation = saga_activity(
19175            "ActivityCompleted",
19176            4,
19177            "trip.cancel-hotel",
19178            Some(Value::Null),
19179        );
19180        let history = vec![
19181            saga_activity(
19182                "ActivityCompleted",
19183                1,
19184                "trip.reserve-flight",
19185                Some(json!("flight-1")),
19186            ),
19187            saga_activity(
19188                "ActivityCompleted",
19189                2,
19190                "trip.reserve-hotel",
19191                Some(json!("hotel-1")),
19192            ),
19193            saga_activity("ActivityFailed", 3, "trip.charge", None),
19194            completed_hotel_compensation.clone(),
19195            completed_hotel_compensation,
19196        ];
19197
19198        for _restart in 0..2 {
19199            let ctx = workflow_context(history.clone());
19200            let mut future = Box::pin(trip_saga(ctx.clone()));
19201            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19202            assert!(matches!(
19203                future.as_mut().poll(&mut task_context),
19204                Poll::Pending
19205            ));
19206            let commands = ctx.take_commands().expect("compensation command");
19207            assert_eq!(commands.len(), 1);
19208            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19209        }
19210    }
19211
19212    #[test]
19213    fn saga_compensation_failure_preserves_both_typed_failures() {
19214        let history = vec![
19215            saga_activity(
19216                "ActivityCompleted",
19217                1,
19218                "trip.reserve-flight",
19219                Some(json!("flight-1")),
19220            ),
19221            saga_activity(
19222                "ActivityCompleted",
19223                2,
19224                "trip.reserve-hotel",
19225                Some(json!("hotel-1")),
19226            ),
19227            saga_activity("ActivityFailed", 3, "trip.charge", None),
19228            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
19229        ];
19230        let ctx = workflow_context(history);
19231        let mut future = Box::pin(trip_saga(ctx));
19232        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19233        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
19234            future.as_mut().poll(&mut task_context)
19235        else {
19236            panic!("compensation failure must remain structured");
19237        };
19238        assert!(matches!(
19239            *failure.initiating_failure,
19240            Error::ActivityFailed(_)
19241        ));
19242        assert!(matches!(
19243            *failure.compensation_failure,
19244            Error::ActivityFailed(_)
19245        ));
19246        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
19247        assert_eq!(failure.compensation_registration_order, 2);
19248    }
19249
19250    #[test]
19251    fn saga_compensates_cooperative_cancellation() {
19252        let ctx = workflow_context(vec![saga_activity(
19253            "ActivityCompleted",
19254            1,
19255            "trip.reserve-flight",
19256            Some(json!("flight-1")),
19257        )]);
19258        ctx.state.lock().expect("state").cancel_requested = true;
19259        let run = {
19260            let ctx = ctx.clone();
19261            async move {
19262                let mut saga = ctx.saga();
19263                let outcome = async {
19264                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
19265                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
19266                    ctx.throw_if_cancellation_requested()?;
19267                    Ok(json!("unexpected"))
19268                }
19269                .await;
19270                saga.finish(outcome).await
19271            }
19272        };
19273        let mut future = Box::pin(run);
19274        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19275        assert!(matches!(
19276            future.as_mut().poll(&mut task_context),
19277            Poll::Pending
19278        ));
19279        let commands = ctx.take_commands().expect("cancellation compensation");
19280        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
19281    }
19282
19283    fn workflow_task(
19284        workflow_type: &str,
19285        history_events: Vec<HistoryEvent>,
19286        payload_codec: &str,
19287    ) -> WorkflowTask {
19288        WorkflowTask {
19289            task_id: format!("wft-{workflow_type}"),
19290            workflow_command_id: None,
19291            workflow_id: Some(format!("wf-{workflow_type}")),
19292            run_id: Some(format!("run-{workflow_type}")),
19293            workflow_type: workflow_type.to_string(),
19294            cancel_requested: false,
19295            payload_codec: payload_codec.to_string(),
19296            arguments: Some(
19297                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
19298            ),
19299            total_history_events: Some(history_events.len() as u64),
19300            history_size_bytes: None,
19301            continue_as_new_recommended: None,
19302            history_budget_pressure: None,
19303            history_events,
19304            next_history_page_token: None,
19305            workflow_task_attempt: 1,
19306            workflow_signal_id: None,
19307            signal_name: None,
19308            signal_arguments: None,
19309            workflow_update_id: None,
19310            update_name: None,
19311            lease_owner: Some("rust-worker".to_string()),
19312        }
19313    }
19314
19315    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19316    struct SideEffectProbe {
19317        request_id: String,
19318        attempt: u32,
19319    }
19320
19321    #[test]
19322    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
19323        let calls = AtomicUsize::new(0);
19324        let ctx = workflow_context(Vec::new());
19325        let value = ctx
19326            .side_effect(|| {
19327                calls.fetch_add(1, Ordering::SeqCst);
19328                SideEffectProbe {
19329                    request_id: "request-42".to_string(),
19330                    attempt: 3,
19331                }
19332            })
19333            .expect("first side effect");
19334        assert_eq!(value.attempt, 3);
19335        assert_eq!(calls.load(Ordering::SeqCst), 1);
19336        let commands = ctx.take_commands().expect("commands");
19337        assert_eq!(commands.len(), 1);
19338        assert_eq!(commands[0]["type"], "record_side_effect");
19339        assert_eq!(
19340            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19341            serde_json::to_value(&value).expect("value")
19342        );
19343
19344        let replay = workflow_context(vec![history_event(
19345            "SideEffectRecorded",
19346            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19347        )]);
19348        let replayed: SideEffectProbe = replay
19349            .side_effect(|| {
19350                calls.fetch_add(1, Ordering::SeqCst);
19351                panic!("committed side-effect callbacks must not run during replay")
19352            })
19353            .expect("replayed side effect");
19354        assert_eq!(replayed, value);
19355        assert_eq!(calls.load(Ordering::SeqCst), 1);
19356        assert!(replay.take_commands().expect("commands").is_empty());
19357        replay.ensure_history_consumed().expect("history consumed");
19358    }
19359
19360    #[test]
19361    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
19362        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19363        let value = ctx
19364            .side_effect(|| SideEffectProbe {
19365                request_id: "avro-request".to_string(),
19366                attempt: 1,
19367            })
19368            .expect("Avro side effect");
19369        let uuid = ctx.uuid_v4().expect("deterministic UUID");
19370        let commands = ctx.take_commands().expect("commands");
19371        assert_eq!(commands.len(), 2);
19372        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
19373        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
19374        assert_eq!(
19375            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
19376            serde_json::to_value(&value).expect("value")
19377        );
19378
19379        let replay = workflow_context_with_codec(
19380            vec![
19381                history_event(
19382                    "SideEffectRecorded",
19383                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19384                ),
19385                history_event(
19386                    "SideEffectRecorded",
19387                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
19388                ),
19389            ],
19390            DEFAULT_CODEC,
19391        );
19392        let replayed: SideEffectProbe = replay
19393            .side_effect(|| panic!("Avro callback must not run"))
19394            .expect("replayed Avro value");
19395        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
19396        assert_eq!(replayed, value);
19397        assert_eq!(replayed_uuid, uuid);
19398        assert!(replay.take_commands().expect("commands").is_empty());
19399    }
19400
19401    #[test]
19402    fn typed_side_effect_replay_preserves_bytes_and_maps() {
19403        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
19404        let value = ctx
19405            .side_effect_avro_value(typed_fidelity_probe)
19406            .expect("typed side effect");
19407        let commands = ctx.take_commands().expect("side-effect command");
19408        assert_eq!(
19409            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
19410                .expect("recorded side effect"),
19411            value
19412        );
19413
19414        let replay = workflow_context_with_codec(
19415            vec![history_event(
19416                "SideEffectRecorded",
19417                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
19418            )],
19419            DEFAULT_CODEC,
19420        );
19421        assert_eq!(
19422            replay
19423                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
19424                .expect("replayed typed side effect"),
19425            value
19426        );
19427    }
19428
19429    #[test]
19430    fn ordered_side_effects_share_the_durable_command_stream() {
19431        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
19432        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
19433        let ctx = workflow_context(vec![
19434            history_event(
19435                "SideEffectRecorded",
19436                json!({"sequence": 1, "result": first}),
19437            ),
19438            history_event(
19439                "SideEffectRecorded",
19440                json!({"sequence": 2, "result": second}),
19441            ),
19442        ]);
19443        let first: String = ctx
19444            .side_effect(|| panic!("first callback must not run"))
19445            .expect("first replay");
19446        let second: i32 = ctx
19447            .side_effect(|| panic!("second callback must not run"))
19448            .expect("second replay");
19449        assert_eq!(first, "first");
19450        assert_eq!(second, 29);
19451        ctx.ensure_history_consumed().expect("ordered history");
19452
19453        let reordered = workflow_context(vec![history_event(
19454            "VersionMarkerRecorded",
19455            json!({
19456                "sequence": 1,
19457                "change_id": "before-side-effect",
19458                "version": 1,
19459                "min_supported": 1,
19460                "max_supported": 1,
19461            }),
19462        )]);
19463        let error = reordered
19464            .side_effect(|| "new".to_string())
19465            .expect_err("command reordering must fail");
19466        assert!(matches!(
19467            error,
19468            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19469                if reason == "recorded_command_mismatch"
19470        ));
19471    }
19472
19473    #[test]
19474    fn legacy_patch_preserves_pending_and_completed_activity_history() {
19475        for completed in [false, true] {
19476            let mut history = vec![history_event(
19477                "ActivityScheduled",
19478                json!({"sequence": 1, "activity_type": "old"}),
19479            )];
19480            if completed {
19481                history.push(history_event(
19482                    "ActivityCompleted",
19483                    json!({
19484                        "sequence": 1,
19485                        "activity_type": "old",
19486                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
19487                    }),
19488                ));
19489            }
19490            for _cold_replay in 0..2 {
19491                let ctx = workflow_context(history.clone());
19492                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
19493                assert!(!ctx.patched("added-step").expect("same frozen decision"));
19494                ctx.deprecate_patch("added-step")
19495                    .expect("retained boundary");
19496                let mut activity = Box::pin(ctx.activity("old", json!([])));
19497                let mut context = TaskContext::from_waker(noop_waker_ref());
19498                match activity.as_mut().poll(&mut context) {
19499                    Poll::Ready(result) => {
19500                        assert!(completed);
19501                        assert_eq!(result.expect("recorded result"), json!(41));
19502                        ctx.ensure_history_consumed().expect("old command retained");
19503                    }
19504                    Poll::Pending => assert!(!completed),
19505                }
19506                assert!(ctx.take_commands().expect("commands").is_empty());
19507            }
19508        }
19509    }
19510
19511    #[test]
19512    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
19513        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
19514        assert!(!ctx.patched("added-step").expect("legacy completed run"));
19515        ctx.deprecate_patch("added-step")
19516            .expect("same legacy decision");
19517        assert!(ctx.take_commands().expect("commands").is_empty());
19518        ctx.ensure_history_consumed().expect("completed history");
19519    }
19520
19521    #[test]
19522    fn legacy_patch_rejects_a_range_without_the_original_branch() {
19523        let ctx = workflow_context(vec![history_event(
19524            "ActivityScheduled",
19525            json!({"sequence": 1, "activity_type": "old"}),
19526        )]);
19527        let error = ctx
19528            .get_version("added-step", 0, 1)
19529            .expect_err("legacy is unsupported");
19530        assert!(matches!(
19531            error,
19532            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19533                if reason == "version_marker_incompatible_range"
19534        ));
19535        assert!(!ctx
19536            .patched("supported-step")
19537            .expect("failed check did not consume history"));
19538        assert!(ctx.take_commands().expect("commands").is_empty());
19539    }
19540
19541    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
19542        let mut event = history_event(
19543            "VersionMarkerRecorded",
19544            json!({
19545                "sequence": sequence,
19546                "change_id": "retained-patch",
19547                "version": version,
19548                "min_supported": -1,
19549                "max_supported": 1,
19550            }),
19551        );
19552        event.raw.insert("timestamp".into(), json!(time));
19553        event
19554    }
19555
19556    #[test]
19557    fn retained_patch_markers_preserve_each_original_boundary() {
19558        for completed in [false, true] {
19559            let mut history = vec![
19560                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19561                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19562                history_event(
19563                    "ActivityScheduled",
19564                    json!({"sequence": 3, "activity_type": "old"}),
19565                ),
19566            ];
19567            if completed {
19568                history.push(history_event(
19569                    "ActivityCompleted",
19570                    json!({
19571                        "sequence": 3,
19572                        "activity_type": "old",
19573                        "result": fixture_envelope(json!(41)),
19574                    }),
19575                ));
19576            }
19577            for _cold_replay in 0..2 {
19578                let ctx = workflow_context(history.clone());
19579                assert!(ctx.patched("retained-patch").unwrap());
19580                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19581                assert!(ctx.patched("retained-patch").unwrap());
19582                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19583                ctx.deprecate_patch("retained-patch").unwrap();
19584                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
19585                let mut activity = Box::pin(ctx.activity("old", json!([])));
19586                let mut context = TaskContext::from_waker(noop_waker_ref());
19587                match activity.as_mut().poll(&mut context) {
19588                    Poll::Ready(result) => {
19589                        assert!(completed);
19590                        assert_eq!(result.unwrap(), json!(41));
19591                        ctx.ensure_history_consumed().unwrap();
19592                    }
19593                    Poll::Pending => assert!(!completed),
19594                }
19595                assert!(ctx.take_commands().unwrap().is_empty());
19596                let state = ctx.state.lock().unwrap();
19597                for (actual, original) in state.history_events.iter().zip(&history) {
19598                    assert_eq!(actual.payload, original.payload);
19599                    assert_eq!(actual.raw, original.raw);
19600                }
19601            }
19602        }
19603    }
19604
19605    #[test]
19606    fn retained_patch_aliases_do_not_skip_intervening_operations() {
19607        let ctx = workflow_context(vec![
19608            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19609            history_event(
19610                "SideEffectRecorded",
19611                json!({
19612                    "sequence": 2, "result": fixture_envelope(json!("between")),
19613                }),
19614            ),
19615            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
19616            history_event(
19617                "VersionMarkerRecorded",
19618                json!({
19619                    "sequence": 4, "change_id": "other-patch", "version": 1,
19620                    "min_supported": -1, "max_supported": 1,
19621                }),
19622            ),
19623        ]);
19624        assert!(ctx.patched("retained-patch").unwrap());
19625        assert!(ctx.patched("retained-patch").unwrap());
19626        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19627        assert_eq!(
19628            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19629            "between"
19630        );
19631        ctx.deprecate_patch("retained-patch").unwrap();
19632        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19633        ctx.deprecate_patch("retained-patch").unwrap();
19634        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
19635        assert!(ctx.patched("other-patch").unwrap());
19636        ctx.ensure_history_consumed().unwrap();
19637        assert!(ctx.take_commands().unwrap().is_empty());
19638    }
19639
19640    #[test]
19641    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
19642        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19643        alias.payload["max_supported"] = json!(3);
19644        let ctx = workflow_context(vec![
19645            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19646            alias,
19647        ]);
19648        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
19649        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
19650        assert!(matches!(error,
19651            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19652                if reason == "version_marker_incompatible_range"));
19653        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19654        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
19655        ctx.ensure_history_consumed().unwrap();
19656        assert!(ctx.take_commands().unwrap().is_empty());
19657    }
19658
19659    #[test]
19660    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
19661        let ctx = workflow_context(Vec::new());
19662        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
19663        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
19664        assert!(ctx.patched("new-search").expect("patch"));
19665        ctx.deprecate_patch("new-search").expect("deprecate patch");
19666        let commands = ctx.take_commands().expect("commands");
19667        assert_eq!(commands.len(), 2);
19668        assert_eq!(commands[0]["type"], "record_version_marker");
19669        assert_eq!(commands[0]["version"], 2);
19670        assert_eq!(commands[1]["change_id"], "new-search");
19671
19672        let replay = workflow_context(vec![history_event(
19673            "VersionMarkerRecorded",
19674            json!({
19675                "sequence": 1,
19676                "change_id": "checkout-v2",
19677                "version": 2,
19678                "min_supported": 1,
19679                "max_supported": 2,
19680            }),
19681        )]);
19682        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
19683        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
19684        assert!(replay.take_commands().expect("commands").is_empty());
19685        replay.ensure_history_consumed().expect("history consumed");
19686    }
19687
19688    #[test]
19689    fn version_markers_reject_incompatible_or_malformed_history() {
19690        let incompatible = workflow_context(vec![history_event(
19691            "VersionMarkerRecorded",
19692            json!({
19693                "sequence": 1,
19694                "change_id": "checkout-v2",
19695                "version": 1,
19696                "min_supported": 1,
19697                "max_supported": 2,
19698            }),
19699        )]);
19700        let error = incompatible
19701            .get_version("checkout-v2", 2, 3)
19702            .expect_err("old version is unsupported");
19703        assert!(matches!(
19704            error,
19705            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19706                if reason == "version_marker_incompatible_range"
19707        ));
19708
19709        for (history, reason) in [
19710            (
19711                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
19712                "side_effect_result_missing",
19713            ),
19714            (
19715                vec![history_event(
19716                    "SideEffectRecorded",
19717                    json!({
19718                        "sequence": 1,
19719                        "result": {"codec": "avro", "blob": "not-base64"},
19720                    }),
19721                )],
19722                "side_effect_payload_incompatible",
19723            ),
19724            (
19725                vec![history_event(
19726                    "SideEffectRecorded",
19727                    json!({"sequence": 1, "result": {"unwrapped": true}}),
19728                )],
19729                "side_effect_payload_malformed",
19730            ),
19731            (
19732                vec![history_event(
19733                    "VersionMarkerRecorded",
19734                    json!({
19735                        "sequence": 1,
19736                        "change_id": "change",
19737                        "version": 1,
19738                        "min_supported": 2,
19739                        "max_supported": 1,
19740                    }),
19741                )],
19742                "version_marker_history_range_invalid",
19743            ),
19744        ] {
19745            let error = WorkflowState::new(
19746                history,
19747                "rust-workers".to_string(),
19748                DEFAULT_CODEC.to_string(),
19749                None,
19750            )
19751            .expect_err("malformed history must fail");
19752            assert!(matches!(
19753                error,
19754                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
19755                    if actual == reason
19756            ));
19757        }
19758    }
19759
19760    #[test]
19761    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
19762        let history = vec![history_event(
19763            "SearchAttributesUpserted",
19764            json!({
19765                "sequence": 1,
19766                "attributes": {"customer_tier": "gold"},
19767                "attribute_types": {"customer_tier": "keyword"},
19768                "merged": {"customer_tier": "gold"}
19769            }),
19770        )];
19771
19772        let matching = workflow_context(history.clone());
19773        matching
19774            .upsert_search_attributes(
19775                SearchAttributeUpdate::new()
19776                    .keyword("customer_tier", "gold")
19777                    .expect("keyword update"),
19778            )
19779            .expect("matching typed update must replay");
19780        matching
19781            .ensure_history_consumed()
19782            .expect("history consumed");
19783
19784        let changed_type = workflow_context(history.clone());
19785        let error = changed_type
19786            .upsert_search_attributes(
19787                SearchAttributeUpdate::new()
19788                    .string("customer_tier", "gold")
19789                    .expect("string update"),
19790            )
19791            .expect_err("same JSON value with a different declaration must be nondeterministic");
19792        let Error::NonDeterministicReplay(failure) = error else {
19793            panic!("typed identity drift must be a replay failure");
19794        };
19795        assert_eq!(failure.reason, "search_attribute_type_mismatch");
19796        assert_eq!(failure.sequence, Some(1));
19797
19798        let changed_value = workflow_context(history);
19799        let error = changed_value
19800            .upsert_search_attributes(
19801                SearchAttributeUpdate::new()
19802                    .keyword("customer_tier", "platinum")
19803                    .expect("keyword update"),
19804            )
19805            .expect_err("changed values must be nondeterministic");
19806        let Error::NonDeterministicReplay(failure) = error else {
19807            panic!("value drift must be a replay failure");
19808        };
19809        assert_eq!(failure.reason, "search_attribute_value_mismatch");
19810    }
19811
19812    #[test]
19813    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
19814        let history = vec![history_event(
19815            "SearchAttributesUpserted",
19816            json!({
19817                "sequence": 1,
19818                "attributes": {"customer_tier": "gold"},
19819                "merged": {"customer_tier": "gold"}
19820            }),
19821        )];
19822
19823        for update in [
19824            SearchAttributeUpdate::new()
19825                .keyword("customer_tier", "gold")
19826                .expect("keyword update"),
19827            SearchAttributeUpdate::new()
19828                .string("customer_tier", "gold")
19829                .expect("string update"),
19830        ] {
19831            let restarted = workflow_context(history.clone());
19832            restarted
19833                .upsert_search_attributes(update)
19834                .expect("legacy history constrains values but has unknown type identity");
19835            restarted
19836                .ensure_history_consumed()
19837                .expect("history consumed");
19838        }
19839    }
19840
19841    #[test]
19842    fn search_attribute_command_emits_canonical_types() {
19843        let ctx = workflow_context(Vec::new());
19844        ctx.upsert_search_attributes(
19845            SearchAttributeUpdate::new()
19846                .keyword("customer_tier", "gold")
19847                .expect("keyword update")
19848                .int("attempts", 3)
19849                .expect("int update")
19850                .delete("obsolete")
19851                .expect("delete update"),
19852        )
19853        .expect("valid search attributes");
19854
19855        assert_eq!(
19856            ctx.take_commands().expect("commands"),
19857            vec![json!({
19858                "type": "upsert_search_attributes",
19859                "attributes": {
19860                    "attempts": 3,
19861                    "customer_tier": "gold",
19862                    "obsolete": null
19863                },
19864                "attribute_types": {
19865                    "attempts": "int",
19866                    "customer_tier": "keyword"
19867                }
19868            })]
19869        );
19870    }
19871
19872    #[test]
19873    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
19874        let duplicate_side_effect = WorkflowState::new(
19875            vec![
19876                history_event(
19877                    "SideEffectRecorded",
19878                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
19879                ),
19880                history_event(
19881                    "SideEffectRecorded",
19882                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
19883                ),
19884            ],
19885            "rust-workers".to_string(),
19886            DEFAULT_CODEC.to_string(),
19887            None,
19888        )
19889        .expect_err("duplicate side effect");
19890        assert!(matches!(
19891            duplicate_side_effect,
19892            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19893                if reason == "duplicate_side_effect_record"
19894        ));
19895
19896        let marker = |sequence, version| {
19897            history_event(
19898                "VersionMarkerRecorded",
19899                json!({
19900                    "sequence": sequence,
19901                    "change_id": "same-change",
19902                    "version": version,
19903                    "min_supported": -1,
19904                    "max_supported": 1,
19905                }),
19906            )
19907        };
19908        let duplicate_marker = WorkflowState::new(
19909            vec![marker(1, 1), marker(3, -1)],
19910            "rust-workers".to_string(),
19911            DEFAULT_CODEC.to_string(),
19912            None,
19913        )
19914        .expect_err("conflicting marker");
19915        assert!(matches!(
19916            duplicate_marker,
19917            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19918                if reason == "version_marker_conflict"
19919        ));
19920    }
19921
19922    #[test]
19923    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
19924        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
19925        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
19926        invalid_alias.payload["max_supported"] = json!(0);
19927        for (history, expected_reason) in [
19928            (
19929                vec![marker.clone(), marker.clone()],
19930                "duplicate_version_marker_record",
19931            ),
19932            (
19933                vec![marker, invalid_alias],
19934                "version_marker_history_range_invalid",
19935            ),
19936        ] {
19937            let error =
19938                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
19939                    .expect_err("invalid historical alias");
19940            assert!(matches!(error,
19941                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
19942                    if reason == expected_reason));
19943        }
19944    }
19945
19946    #[test]
19947    fn retained_patch_aliases_require_the_original_call_boundary() {
19948        let ctx = workflow_context(vec![
19949            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
19950            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19951        ]);
19952        assert!(ctx.patched("retained-patch").unwrap());
19953        assert!(ctx.ensure_history_consumed().is_err());
19954        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19955        ctx.deprecate_patch("retained-patch").unwrap();
19956        ctx.ensure_history_consumed().unwrap();
19957        assert!(ctx.take_commands().unwrap().is_empty());
19958    }
19959
19960    #[test]
19961    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
19962        let ctx = workflow_context(vec![
19963            history_event(
19964                "SideEffectRecorded",
19965                json!({
19966                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
19967                }),
19968            ),
19969            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
19970        ]);
19971        assert!(!ctx.patched("retained-patch").unwrap());
19972        assert_eq!(
19973            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
19974            "old-operation"
19975        );
19976        let error = ctx.patched("retained-patch").unwrap_err();
19977        assert!(matches!(error,
19978            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
19979                if reason == "version_marker_conflict"));
19980        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
19981        assert!(ctx.take_commands().unwrap().is_empty());
19982    }
19983
19984    #[test]
19985    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
19986        let mut state = WorkflowState::new(
19987            Vec::new(),
19988            "rust-workers".to_string(),
19989            DEFAULT_CODEC.to_string(),
19990            None,
19991        )
19992        .expect("workflow state");
19993        state.workflow_command_identity = "command-7".to_string();
19994        let context = WorkflowContext {
19995            state: Arc::new(Mutex::new(state)),
19996            cancellation_scope_id: "root".into(),
19997        };
19998        let item =
19999            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
20000
20001        context
20002            .append_workflow_stream("output", &[item], Some(10))
20003            .expect("append command");
20004        context
20005            .error_workflow_stream("output", "producer failed", None)
20006            .expect("error command");
20007        let commands = context.take_commands().expect("commands");
20008
20009        assert_eq!(commands[0]["type"], "record_side_effect");
20010        assert_eq!(
20011            commands[0]["workflow_stream"]["command_identity"],
20012            "command-7"
20013        );
20014        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
20015        assert_eq!(
20016            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20017            "dw-stream:command-7:0:0"
20018        );
20019        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
20020
20021        let recorded = history_event(
20022            "SideEffectRecorded",
20023            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
20024        );
20025        let mut replay_state = WorkflowState::new(
20026            vec![recorded],
20027            "rust-workers".to_string(),
20028            DEFAULT_CODEC.to_string(),
20029            None,
20030        )
20031        .expect("replay state");
20032        replay_state.workflow_command_identity = "command-7".to_string();
20033        let replay_context = WorkflowContext {
20034            state: Arc::new(Mutex::new(replay_state)),
20035            cancellation_scope_id: "root".into(),
20036        };
20037        replay_context
20038            .append_workflow_stream(
20039                "output",
20040                &[WorkflowStreamAppendItem::from_reference(
20041                    "s3://bucket/item.avro",
20042                )],
20043                Some(10),
20044            )
20045            .expect("replayed append");
20046        assert!(replay_context
20047            .take_commands()
20048            .expect("replayed commands")
20049            .is_empty());
20050    }
20051
20052    #[test]
20053    fn workflow_stream_authoring_requires_server_durable_command_identity() {
20054        let context = workflow_context(Vec::new());
20055        let error = context
20056            .append_workflow_stream(
20057                "output",
20058                &[WorkflowStreamAppendItem::from_reference(
20059                    "s3://bucket/item.avro",
20060                )],
20061                None,
20062            )
20063            .expect_err("stream append without durable command identity must fail closed");
20064
20065        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
20066        assert!(context.take_commands().expect("commands").is_empty());
20067    }
20068
20069    #[test]
20070    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
20071        let client = Client::builder("http://localhost:8080").build().unwrap();
20072        let mut worker = Worker::new(client, "rust-workers");
20073        worker.register_workflow("streams.worker", |ctx, _| async move {
20074            ctx.append_workflow_stream(
20075                "output",
20076                &[WorkflowStreamAppendItem::new(json!("hello"))?],
20077                None,
20078            )?;
20079            ctx.close_workflow_stream("output", None)?;
20080            Ok(json!("done"))
20081        });
20082        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
20083            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20084            task.workflow_command_id = command_id.clone();
20085            let expected_identity = command_id
20086                .as_deref()
20087                .filter(|id| !id.is_empty())
20088                .unwrap_or(&task.task_id)
20089                .to_string();
20090            let commands = worker
20091                .execute_workflow_task(task)
20092                .expect("ordinary worker stream output");
20093            assert_eq!(commands.len(), 3);
20094            assert_eq!(
20095                commands[0]["workflow_stream"]["command_identity"],
20096                expected_identity
20097            );
20098            assert_eq!(
20099                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
20100                format!("dw-stream:{expected_identity}:0:0")
20101            );
20102            assert_eq!(
20103                commands[1]["workflow_stream"]["command_identity"],
20104                expected_identity
20105            );
20106            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
20107            let history = commands[..2]
20108                .iter()
20109                .enumerate()
20110                .map(|(index, command)| {
20111                    history_event(
20112                        "SideEffectRecorded",
20113                        json!({"sequence":index + 1,"result":command["result"]}),
20114                    )
20115                })
20116                .collect();
20117            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
20118            replay.task_id = "replacement-task".to_string();
20119            let replayed = worker
20120                .execute_workflow_task(replay)
20121                .expect("replacement worker consumes recorded stream effects");
20122            assert_eq!(replayed.len(), 1);
20123            assert_eq!(replayed[0]["type"], "complete_workflow");
20124        }
20125        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
20126        missing.task_id.clear();
20127        assert!(matches!(
20128            worker.execute_workflow_task(missing),
20129            Err(Error::MissingWorkflowCommandIdentity)
20130        ));
20131    }
20132
20133    #[test]
20134    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
20135        fn worker(calls: Arc<AtomicUsize>) -> Worker {
20136            let client = Client::new("http://127.0.0.1:8080").expect("client");
20137            let mut worker = Worker::new(client, "rust-workers");
20138            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
20139                let calls = Arc::clone(&calls);
20140                async move {
20141                    let captured = ctx.side_effect(|| {
20142                        calls.fetch_add(1, Ordering::SeqCst);
20143                        "captured-once".to_string()
20144                    })?;
20145                    let version = ctx.get_version("cold-restart", 1, 2)?;
20146                    Ok(json!({"captured": captured, "version": version}))
20147                }
20148            });
20149            worker
20150        }
20151
20152        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
20153            WorkflowTask {
20154                task_id: "wft-side-effect-version".to_string(),
20155                workflow_command_id: None,
20156                workflow_id: Some("wf-side-effect-version".to_string()),
20157                run_id: Some("run-side-effect-version".to_string()),
20158                workflow_type: "rust.side-effect-version".to_string(),
20159                cancel_requested: false,
20160                payload_codec: DEFAULT_CODEC.to_string(),
20161                arguments: Some(
20162                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
20163                ),
20164                history_events,
20165                total_history_events: None,
20166                history_size_bytes: None,
20167                continue_as_new_recommended: None,
20168                history_budget_pressure: None,
20169                next_history_page_token: None,
20170                workflow_task_attempt: 1,
20171                workflow_signal_id: None,
20172                signal_name: None,
20173                signal_arguments: None,
20174                workflow_update_id: None,
20175                update_name: None,
20176                lease_owner: Some("rust-worker".to_string()),
20177            }
20178        }
20179
20180        let calls = Arc::new(AtomicUsize::new(0));
20181        let initial = worker(Arc::clone(&calls))
20182            .execute_workflow_task(task(Vec::new()))
20183            .expect("initial execution");
20184        assert_eq!(
20185            initial
20186                .iter()
20187                .map(|command| &command["type"])
20188                .collect::<Vec<_>>(),
20189            vec![
20190                "record_side_effect",
20191                "record_version_marker",
20192                "complete_workflow"
20193            ]
20194        );
20195        assert_eq!(calls.load(Ordering::SeqCst), 1);
20196
20197        let restarted = worker(Arc::clone(&calls));
20198        let replayed = restarted
20199            .execute_workflow_task(task(vec![
20200                history_event(
20201                    "SideEffectRecorded",
20202                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
20203                ),
20204                history_event(
20205                    "VersionMarkerRecorded",
20206                    json!({
20207                        "sequence": 2,
20208                        "change_id": "cold-restart",
20209                        "version": 2,
20210                        "min_supported": 1,
20211                        "max_supported": 2,
20212                    }),
20213                ),
20214            ]))
20215            .expect("cold replay");
20216        assert_eq!(replayed.len(), 1);
20217        assert_eq!(replayed[0]["type"], "complete_workflow");
20218        assert_eq!(calls.load(Ordering::SeqCst), 1);
20219    }
20220
20221    #[test]
20222    fn side_effect_replay_rejects_changed_rust_value_type() {
20223        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
20224        let ctx = workflow_context(vec![history_event(
20225            "SideEffectRecorded",
20226            json!({"sequence": 1, "result": result}),
20227        )]);
20228        let error = ctx
20229            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
20230            .expect_err("changed type must fail replay");
20231        assert!(matches!(
20232            error,
20233            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20234                if reason == "side_effect_type_mismatch"
20235        ));
20236    }
20237
20238    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
20239        vec![
20240            history_event(
20241                "ActivityScheduled",
20242                json!({
20243                    "sequence": 1,
20244                    "activity_type": "flaky",
20245                    "activity_execution_id": "act-1",
20246                    "activity": {
20247                        "id": "act-1",
20248                        "sequence": 1,
20249                        "type": "flaky",
20250                        "queue": "critical-activities",
20251                        "execution_mode": null,
20252                        "retry_policy": {
20253                            "snapshot_version": 1,
20254                            "max_attempts": 3,
20255                            "backoff_seconds": [2, 4],
20256                            "start_to_close_timeout": 30,
20257                            "schedule_to_start_timeout": 5,
20258                            "schedule_to_close_timeout": 90,
20259                            "heartbeat_timeout": 10,
20260                            "non_retryable_error_types": ["PermanentError"]
20261                        }
20262                    }
20263                }),
20264            ),
20265            history_event(
20266                "ActivityStarted",
20267                json!({
20268                    "sequence": 1,
20269                    "activity_type": "flaky",
20270                    "activity_execution_id": "act-1",
20271                    "activity_attempt_id": "attempt-1",
20272                    "attempt_number": 1
20273                }),
20274            ),
20275            history_event(
20276                "ActivityRetryScheduled",
20277                json!({
20278                    "sequence": 1,
20279                    "activity_type": "flaky",
20280                    "activity_execution_id": "act-1",
20281                    "activity_attempt_id": "attempt-1",
20282                    "attempt_number": 1,
20283                    "retry_after_attempt": 1,
20284                    "retry_backoff_seconds": 2,
20285                    "failure_category": "activity",
20286                    "exception_type": "TransientError"
20287                }),
20288            ),
20289            history_event(
20290                "ActivityStarted",
20291                json!({
20292                    "sequence": 1,
20293                    "activity_type": "flaky",
20294                    "activity_execution_id": "act-1",
20295                    "activity_attempt_id": "attempt-2",
20296                    "attempt_number": 2
20297                }),
20298            ),
20299            history_event(
20300                "ActivityCompleted",
20301                json!({
20302                    "sequence": 1,
20303                    "activity_type": "flaky",
20304                    "activity_execution_id": "act-1",
20305                    "activity_attempt_id": "attempt-2",
20306                    "attempt_number": 2,
20307                    "payload_codec": DEFAULT_CODEC,
20308                    "result": fixture_envelope(json!({"status":"recovered"}))
20309                }),
20310            ),
20311        ]
20312    }
20313
20314    fn retry_activity_options() -> ActivityOptions {
20315        ActivityOptions::new()
20316            .task_queue("critical-activities")
20317            .retry_policy(
20318                ActivityRetryPolicy::new(3)
20319                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
20320                    .non_retryable_error_type("PermanentError"),
20321            )
20322            .start_to_close_timeout(Duration::from_secs(30))
20323            .schedule_to_start_timeout(Duration::from_secs(5))
20324            .schedule_to_close_timeout(Duration::from_secs(90))
20325            .heartbeat_timeout(Duration::from_secs(10))
20326    }
20327
20328    #[test]
20329    fn fixed_avro_value_round_trips_json_values() {
20330        let value = json!({"greeting": "hello", "count": 3, "ok": true});
20331        let envelope = PayloadEnvelope::avro(&value).expect("encode");
20332        assert_eq!(envelope.codec, DEFAULT_CODEC);
20333        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
20334    }
20335
20336    #[tokio::test]
20337    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
20338        let client = Client::new("http://127.0.0.1:8080").expect("client");
20339        let mut worker = Worker::new(client, "rust-workers");
20340        worker.register_typed_workflow(
20341            "typed.contract.workflow",
20342            |_ctx, input: TypedContract| async move { Ok(input) },
20343        );
20344        worker.register_typed_activity(
20345            "typed.contract.activity",
20346            |_ctx, input: TypedContract| async move { Ok(input) },
20347        );
20348
20349        let expected = typed_contract();
20350        let arguments = AvroValue::Array(vec![
20351            AvroValue::from_serialize(&expected).expect("typed request")
20352        ]);
20353        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
20354        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
20355        workflow.arguments = Some(envelope.clone());
20356        let commands = worker
20357            .execute_workflow_task(workflow)
20358            .expect("typed workflow task");
20359        let workflow_result: TypedContract =
20360            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20361                .expect("workflow result envelope")
20362                .deserialize()
20363                .expect("workflow result type");
20364        assert_eq!(workflow_result, expected);
20365
20366        let activity = ActivityTask {
20367            task_id: "typed-contract-activity".to_string(),
20368            activity_attempt_id: Some("typed-contract-attempt".to_string()),
20369            attempt_id: None,
20370            activity_type: "typed.contract.activity".to_string(),
20371            payload_codec: DEFAULT_CODEC.to_string(),
20372            arguments: Some(envelope),
20373            attempt_number: 1,
20374            lease_owner: Some("rust-worker".to_string()),
20375        };
20376        let activity_result: TypedContract = worker
20377            .execute_activity_task(activity)
20378            .await
20379            .expect("typed activity task")
20380            .deserialize()
20381            .expect("activity result type");
20382        assert_eq!(activity_result, expected);
20383    }
20384
20385    #[tokio::test]
20386    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
20387        let client = Client::new("http://127.0.0.1:8080").expect("client");
20388        let mut worker = Worker::new(client, "rust-workers");
20389        worker.register_typed_workflow(
20390            "typed.shape.workflow",
20391            |_ctx, input: TypedContract| async move { Ok(input) },
20392        );
20393        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
20394            Ok(f64::NAN)
20395        });
20396
20397        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
20398        workflow.arguments = Some(
20399            encode_typed_envelope(
20400                &AvroValue::Array(vec![
20401                    AvroValue::String("first".to_string()),
20402                    AvroValue::String("second".to_string()),
20403                ]),
20404                DEFAULT_CODEC,
20405            )
20406            .expect("malformed typed arguments"),
20407        );
20408        let commands = worker
20409            .execute_workflow_task(workflow)
20410            .expect("shape mismatch becomes a workflow failure");
20411        let message = commands[0]["message"].as_str().expect("failure message");
20412        assert!(message.contains("workflow handler \"typed.shape.workflow\" input type"));
20413        assert!(message.contains(type_name::<TypedContract>()));
20414        assert!(message.contains("task carried 2 arguments"));
20415
20416        let activity = ActivityTask {
20417            task_id: "typed-unsupported-activity".to_string(),
20418            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
20419            attempt_id: None,
20420            activity_type: "typed.unsupported.activity".to_string(),
20421            payload_codec: DEFAULT_CODEC.to_string(),
20422            arguments: Some(
20423                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20424                    .expect("unit arguments"),
20425            ),
20426            attempt_number: 1,
20427            lease_owner: Some("rust-worker".to_string()),
20428        };
20429        let Error::HandlerType {
20430            handler_kind,
20431            handler_name,
20432            value_kind,
20433            rust_type,
20434            message,
20435        } = worker
20436            .execute_activity_task(activity)
20437            .await
20438            .expect_err("non-finite handler output must fail")
20439        else {
20440            panic!("expected contextual handler type failure");
20441        };
20442        assert_eq!(handler_kind, HandlerKind::Activity);
20443        assert_eq!(handler_name, "typed.unsupported.activity");
20444        assert_eq!(value_kind, HandlerValueKind::Result);
20445        assert_eq!(rust_type, type_name::<f64>());
20446        assert!(message.contains("non_finite_float"));
20447    }
20448
20449    #[tokio::test]
20450    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
20451        #[derive(Clone, Default)]
20452        struct State {
20453            observed: Option<TypedContract>,
20454        }
20455
20456        let client = Client::new("http://127.0.0.1:8080").expect("client");
20457        let mut worker = Worker::new(client, "rust-workers");
20458        worker.register_typed_replayed_workflow(
20459            "typed.contract.replayed",
20460            State::default,
20461            |ctx, input: TypedContract, state| async move {
20462                let result: TypedContract =
20463                    ctx.activity_typed("typed.contract.activity", input).await?;
20464                state.update(|current| current.observed = Some(result.clone()))?;
20465                Ok(result)
20466            },
20467        );
20468        worker.register_replayed_query::<State, _, _>(
20469            "typed.contract.replayed",
20470            "observed",
20471            |_ctx, state, _args| async move {
20472                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
20473            },
20474        );
20475
20476        let expected = typed_contract();
20477        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
20478        let workflow_arguments =
20479            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
20480                .expect("workflow arguments");
20481        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
20482        let task = QueryTask {
20483            query_task_id: "typed-replay-query".to_string(),
20484            query_task_attempt: 1,
20485            lease_owner: Some("rust-worker".to_string()),
20486            workflow_id: Some("typed-replay".to_string()),
20487            run_id: Some("typed-replay-run".to_string()),
20488            workflow_type: "typed.contract.replayed".to_string(),
20489            query_name: "observed".to_string(),
20490            payload_codec: DEFAULT_CODEC.to_string(),
20491            workflow_arguments: Some(workflow_arguments),
20492            query_arguments: Some(
20493                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20494                    .expect("query arguments"),
20495            ),
20496            history_events: vec![
20497                history_event(
20498                    "ActivityScheduled",
20499                    json!({
20500                        "sequence": 1,
20501                        "activity_type": "typed.contract.activity"
20502                    }),
20503                ),
20504                history_event(
20505                    "ActivityCompleted",
20506                    json!({
20507                        "sequence": 1,
20508                        "activity_type": "typed.contract.activity",
20509                        "payload_codec": DEFAULT_CODEC,
20510                        "result": result
20511                    }),
20512                ),
20513            ],
20514            history_export: None,
20515            run_status: Some("completed".to_string()),
20516        };
20517
20518        assert_eq!(
20519            worker
20520                .execute_query_task(task)
20521                .await
20522                .expect("typed replay query")
20523                .deserialize::<i64>()
20524                .expect("query result"),
20525            expected.signed
20526        );
20527    }
20528
20529    #[tokio::test]
20530    async fn update_context_preserves_workflow_input_and_committed_signals() {
20531        let client = Client::new("http://127.0.0.1:8080").expect("client");
20532        let mut worker = Worker::new(client, "rust-workers");
20533        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20534        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
20535        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
20536        let expected_input = workflow_input.clone();
20537        let expected_signals = signal_arguments.clone();
20538        let handler = move |context: QueryContext, arguments: AvroValue| {
20539            let expected_input = expected_input.clone();
20540            let expected_signals = expected_signals.clone();
20541            async move {
20542                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
20543                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
20544                assert_eq!(context.workflow_input_avro_value(), &expected_input);
20545                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
20546                assert_eq!(
20547                    context.signals_avro_value("changed"),
20548                    vec![expected_signals.clone()]
20549                );
20550                assert_eq!(
20551                    context.signals("changed"),
20552                    vec![expected_signals
20553                        .into_iter()
20554                        .map(AvroValue::into_json)
20555                        .collect::<Result<Vec<_>>>()?]
20556                );
20557                assert_eq!(
20558                    context.signal_events()[0].id.as_deref(),
20559                    Some("signal-original")
20560                );
20561                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
20562                Ok(arguments)
20563            }
20564        };
20565        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
20566        worker.register_update_avro_value("snapshot", "inspect", handler);
20567        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
20568        let update_envelope =
20569            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
20570        let mut task = workflow_task(
20571            "snapshot",
20572            vec![
20573                history_event(
20574                    "SignalReceived",
20575                    json!({
20576                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
20577                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
20578                    }),
20579                ),
20580                history_event(
20581                    "UpdateAccepted",
20582                    json!({
20583                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
20584                    }),
20585                ),
20586            ],
20587            DEFAULT_CODEC,
20588        );
20589        task.arguments =
20590            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
20591        task.workflow_update_id = Some("update-original".into());
20592        task.update_name = Some("inspect".into());
20593        let query = QueryTask {
20594            query_task_id: "query-snapshot".into(),
20595            query_task_attempt: 1,
20596            lease_owner: None,
20597            workflow_id: task.workflow_id.clone(),
20598            run_id: task.run_id.clone(),
20599            workflow_type: task.workflow_type.clone(),
20600            query_name: "inspect".into(),
20601            payload_codec: DEFAULT_CODEC.into(),
20602            workflow_arguments: task.arguments.clone(),
20603            query_arguments: Some(update_envelope),
20604            history_events: task.history_events.clone(),
20605            history_export: None,
20606            run_status: Some("running".into()),
20607        };
20608        assert_eq!(
20609            worker
20610                .execute_query_task(query)
20611                .await
20612                .expect("query snapshot"),
20613            update_arguments
20614        );
20615        for _ in 0..2 {
20616            let commands = worker
20617                .execute_workflow_task(task.clone())
20618                .expect("cold update snapshot");
20619            assert_eq!(commands[0]["type"], "complete_update");
20620            assert_eq!(commands[0]["update_id"], "update-original");
20621            assert_eq!(
20622                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20623                    .expect("update result"),
20624                update_arguments
20625            );
20626        }
20627    }
20628
20629    #[test]
20630    fn committed_signal_snapshot_counts_identities_once() {
20631        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
20632        let received = history_event(
20633            "SignalReceived",
20634            json!({
20635                "signal_id": "signal-first", "workflow_command_id": "command-first",
20636                "signal_name": "changed", "arguments": arguments.clone(),
20637            }),
20638        );
20639        let applied = history_event(
20640            "SignalApplied",
20641            json!({
20642                "signal_id": "signal-first", "workflow_command_id": "command-first",
20643                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
20644            }),
20645        );
20646        let distinct = history_event(
20647            "SignalReceived",
20648            json!({
20649                "signal_id": "signal-second", "workflow_command_id": "command-second",
20650                "signal_name": "changed", "arguments": arguments,
20651            }),
20652        );
20653        let history = vec![received.clone(), applied.clone(), distinct];
20654        let signals =
20655            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
20656        assert_eq!(signals.len(), 2);
20657        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20658        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
20659        assert_eq!(signals[0].workflow_sequence, Some(1));
20660        assert_eq!(signals[0].arguments, signals[1].arguments);
20661        let mut command_only = received.clone();
20662        command_only
20663            .payload
20664            .as_object_mut()
20665            .expect("payload")
20666            .remove("signal_id");
20667        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
20668            .expect("command identity");
20669        assert_eq!(signals.len(), 1);
20670        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
20671        let mut conflicting = applied;
20672        conflicting.payload["value"] =
20673            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
20674        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
20675    }
20676
20677    #[test]
20678    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
20679        for arguments in [
20680            vec![],
20681            vec![AvroValue::Array(vec![
20682                AvroValue::Long(1),
20683                AvroValue::Long(2),
20684            ])],
20685            vec![AvroValue::Bytes(vec![0, 255])],
20686            vec![AvroValue::Null],
20687            vec![AvroValue::Boolean(false)],
20688            vec![
20689                AvroValue::Long(1),
20690                AvroValue::Array(vec![AvroValue::Long(2)]),
20691            ],
20692        ] {
20693            let applied = match arguments.as_slice() {
20694                [] => AvroValue::Boolean(true),
20695                [value] => value.clone(),
20696                values => AvroValue::Array(values.to_vec()),
20697            };
20698            for applied in [applied, AvroValue::Array(arguments.clone())] {
20699                let events = vec![
20700                    history_event(
20701                        "SignalReceived",
20702                        json!({
20703                            "signal_id": "original", "signal_name": "changed",
20704                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
20705                        }),
20706                    ),
20707                    history_event(
20708                        "SignalApplied",
20709                        json!({
20710                            "signal_id": "original", "signal_name": "changed",
20711                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
20712                        }),
20713                    ),
20714                ];
20715                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
20716                    .expect("canonical signal snapshot");
20717                assert_eq!(signals.len(), 1);
20718                assert_eq!(signals[0].avro_arguments, arguments);
20719            }
20720        }
20721    }
20722
20723    #[tokio::test]
20724    async fn update_context_rejects_malformed_snapshot_before_handler() {
20725        let client = Client::new("http://127.0.0.1:8080").expect("client");
20726        let mut worker = Worker::new(client, "rust-workers");
20727        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
20728        let calls = Arc::new(AtomicUsize::new(0));
20729        let observed = Arc::clone(&calls);
20730        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
20731            observed.fetch_add(1, Ordering::SeqCst);
20732            async { Ok(Value::Null) }
20733        });
20734        let mut task = workflow_task(
20735            "snapshot",
20736            vec![history_event(
20737                "UpdateAccepted",
20738                json!({
20739                    "update_id": "update-original", "update_name": "inspect",
20740                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
20741                }),
20742            )],
20743            DEFAULT_CODEC,
20744        );
20745        task.workflow_update_id = Some("update-original".into());
20746        task.update_name = Some("inspect".into());
20747        let mut bad_input = task.clone();
20748        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
20749        assert!(worker.execute_workflow_task(bad_input).is_err());
20750        task.history_events.insert(0, history_event("SignalReceived", json!({
20751            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
20752        })));
20753        assert!(worker.execute_workflow_task(task).is_err());
20754        assert_eq!(calls.load(Ordering::SeqCst), 0);
20755    }
20756
20757    #[tokio::test]
20758    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
20759        let client = Client::new("http://127.0.0.1:8080").expect("client");
20760        let mut worker = Worker::new(client, "rust-workers");
20761        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
20762        worker
20763            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
20764        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
20765            Ok(input)
20766        });
20767        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
20768            Ok(input)
20769        });
20770        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
20771            Ok(AvroValue::Array(
20772                ctx.wait_signal_avro_value("changed").await?,
20773            ))
20774        });
20775
20776        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
20777        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
20778
20779        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
20780        workflow.arguments = Some(envelope.clone());
20781        let commands = worker
20782            .execute_workflow_task(workflow)
20783            .expect("typed workflow task");
20784        assert_eq!(commands[0]["type"], "complete_workflow");
20785        assert_eq!(
20786            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20787                .expect("typed workflow result"),
20788            arguments
20789        );
20790
20791        let activity = ActivityTask {
20792            task_id: "activity-typed".to_string(),
20793            activity_attempt_id: Some("attempt-typed".to_string()),
20794            attempt_id: None,
20795            activity_type: "typed.activity".to_string(),
20796            payload_codec: DEFAULT_CODEC.to_string(),
20797            arguments: Some(envelope.clone()),
20798            attempt_number: 1,
20799            lease_owner: Some("rust-worker".to_string()),
20800        };
20801        assert_eq!(
20802            worker
20803                .execute_activity_task(activity)
20804                .await
20805                .expect("typed activity result"),
20806            arguments
20807        );
20808
20809        let query = QueryTask {
20810            query_task_id: "query-typed".to_string(),
20811            query_task_attempt: 1,
20812            lease_owner: Some("rust-worker".to_string()),
20813            workflow_id: Some("typed-1".to_string()),
20814            run_id: Some("run-typed".to_string()),
20815            workflow_type: "typed.echo".to_string(),
20816            query_name: "inspect".to_string(),
20817            payload_codec: DEFAULT_CODEC.to_string(),
20818            workflow_arguments: Some(
20819                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
20820                    .expect("workflow input"),
20821            ),
20822            query_arguments: Some(envelope.clone()),
20823            history_events: Vec::new(),
20824            history_export: None,
20825            run_status: Some("running".to_string()),
20826        };
20827        assert_eq!(
20828            worker
20829                .execute_query_task(query)
20830                .await
20831                .expect("typed query result"),
20832            arguments
20833        );
20834
20835        let mut update = workflow_task(
20836            "typed.echo",
20837            vec![history_event(
20838                "UpdateAccepted",
20839                json!({
20840                    "update_id": "update-typed",
20841                    "update_name": "replace",
20842                    "arguments": envelope.clone(),
20843                }),
20844            )],
20845            DEFAULT_CODEC,
20846        );
20847        update.workflow_update_id = Some("update-typed".to_string());
20848        update.update_name = Some("replace".to_string());
20849        let commands = worker
20850            .execute_workflow_task(update)
20851            .expect("typed update task");
20852        assert_eq!(commands[0]["type"], "complete_update");
20853        assert_eq!(
20854            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20855                .expect("typed update result"),
20856            arguments
20857        );
20858
20859        let mut signal = workflow_task(
20860            "typed.signal",
20861            vec![history_event(
20862                "SignalReceived",
20863                json!({
20864                    "signal_id": "signal-typed",
20865                    "signal_name": "changed",
20866                    "arguments": envelope.clone(),
20867                }),
20868            )],
20869            DEFAULT_CODEC,
20870        );
20871        signal.workflow_signal_id = Some("signal-typed".to_string());
20872        signal.signal_name = Some("changed".to_string());
20873        signal.signal_arguments = Some(envelope);
20874        let commands = worker
20875            .execute_workflow_task(signal)
20876            .expect("typed signal resume");
20877        assert_eq!(
20878            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20879                .expect("typed signal result"),
20880            arguments
20881        );
20882    }
20883
20884    #[tokio::test]
20885    async fn typed_helpers_never_parse_json_inspection_projection() {
20886        let collision_values = projection_collision_probe();
20887        let expected = AvroValue::Array(collision_values.clone());
20888        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
20889
20890        let activity_context = workflow_context_with_codec(
20891            vec![history_event(
20892                "ActivityCompleted",
20893                json!({
20894                    "sequence": 1,
20895                    "activity_type": "collision.activity",
20896                    "payload_codec": DEFAULT_CODEC,
20897                    "result": envelope.clone(),
20898                }),
20899            )],
20900            DEFAULT_CODEC,
20901        );
20902        assert_eq!(
20903            activity_context
20904                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
20905                .await
20906                .expect("typed activity collision result"),
20907            expected
20908        );
20909
20910        let signal_context = workflow_context_with_codec(
20911            vec![
20912                history_event(
20913                    "SignalWaitOpened",
20914                    json!({"sequence": 1, "signal_name": "collision"}),
20915                ),
20916                history_event(
20917                    "SignalApplied",
20918                    json!({
20919                        "sequence": 1,
20920                        "signal_name": "collision",
20921                        "payload_codec": DEFAULT_CODEC,
20922                        "value": envelope.clone(),
20923                    }),
20924                ),
20925            ],
20926            DEFAULT_CODEC,
20927        );
20928        assert_eq!(
20929            signal_context
20930                .wait_signal_avro_value("collision")
20931                .await
20932                .expect("typed signal collision arguments"),
20933            collision_values
20934        );
20935
20936        let child_context = workflow_context_with_codec(
20937            vec![
20938                history_event(
20939                    "ChildWorkflowScheduled",
20940                    json!({
20941                        "sequence": 1,
20942                        "child_workflow_instance_id": "collision-child",
20943                        "child_workflow_run_id": "collision-run",
20944                        "child_workflow_type": "collision.child",
20945                    }),
20946                ),
20947                history_event(
20948                    "ChildRunCompleted",
20949                    json!({
20950                        "sequence": 1,
20951                        "child_workflow_instance_id": "collision-child",
20952                        "child_workflow_run_id": "collision-run",
20953                        "child_workflow_type": "collision.child",
20954                        "payload_codec": DEFAULT_CODEC,
20955                        "result": envelope,
20956                    }),
20957                ),
20958            ],
20959            DEFAULT_CODEC,
20960        );
20961        let child = child_context
20962            .start_child_workflow_avro_value(
20963                "collision.child",
20964                ChildWorkflowOptions::new("collision-workers"),
20965                AvroValue::Array(Vec::new()),
20966            )
20967            .await
20968            .expect("typed child collision result");
20969        assert_eq!(child.result, expected);
20970    }
20971
20972    #[tokio::test]
20973    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
20974        let client = Client::new("http://127.0.0.1:8080").expect("client");
20975        let mut worker = Worker::new(client, "rust-workers");
20976        worker.register_replayed_workflow_avro_value(
20977            "typed.replayed",
20978            || (),
20979            |_ctx, input, _state| async move { Ok(input) },
20980        );
20981        worker.register_replayed_query_avro_value::<(), _, _>(
20982            "typed.replayed",
20983            "inspect",
20984            |ctx, _state, args| async move {
20985                let mut signals = ctx.signals_avro_value("collision");
20986                let signal = signals
20987                    .pop()
20988                    .map(AvroValue::Array)
20989                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
20990                Ok(AvroValue::Array(vec![
20991                    ctx.workflow_input_avro_value().clone(),
20992                    signal,
20993                    args,
20994                ]))
20995            },
20996        );
20997        let arguments = AvroValue::Array(projection_collision_probe());
20998        let signal_arguments =
20999            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
21000        let task = QueryTask {
21001            query_task_id: "query-typed-replay".to_string(),
21002            query_task_attempt: 1,
21003            lease_owner: Some("rust-worker".to_string()),
21004            workflow_id: Some("typed-replay".to_string()),
21005            run_id: Some("run-typed-replay".to_string()),
21006            workflow_type: "typed.replayed".to_string(),
21007            query_name: "inspect".to_string(),
21008            payload_codec: DEFAULT_CODEC.to_string(),
21009            workflow_arguments: Some(
21010                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
21011            ),
21012            query_arguments: Some(
21013                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
21014            ),
21015            history_events: vec![history_event(
21016                "SignalReceived",
21017                json!({
21018                    "signal_id": "collision-signal",
21019                    "signal_name": "collision",
21020                    "workflow_sequence": 1,
21021                    "payload_codec": DEFAULT_CODEC,
21022                    "arguments": signal_arguments,
21023                }),
21024            )],
21025            history_export: None,
21026            run_status: Some("completed".to_string()),
21027        };
21028
21029        assert_eq!(
21030            worker
21031                .execute_query_task(task)
21032                .await
21033                .expect("typed replay query"),
21034            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
21035        );
21036    }
21037
21038    #[test]
21039    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
21040        let value = BTreeMap::from([(1_i32, "integer key")]);
21041        let error = PayloadEnvelope::avro(&value)
21042            .expect_err("integer map keys must fail")
21043            .to_string();
21044
21045        assert!(error.contains("invalid_map_key"));
21046    }
21047
21048    #[test]
21049    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
21050        let envelope = PayloadEnvelope {
21051            codec: "json".to_string(),
21052            blob: r#"{"greeting":"hello"}"#.to_string(),
21053        };
21054
21055        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
21056        let diagnostic = error.to_string();
21057        assert!(diagnostic.contains("unsupported_payload_codec"));
21058        assert!(diagnostic.contains("codec=\"avro\""));
21059        assert!(diagnostic.contains("HTTP document transport"));
21060    }
21061
21062    #[test]
21063    fn untagged_json_payload_value_fails_closed() {
21064        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
21065            .expect_err("untagged JSON payload values must fail");
21066        let diagnostic = error.to_string();
21067        assert!(diagnostic.contains("unsupported_payload_codec"));
21068        assert!(diagnostic.contains("untagged durable payload"));
21069        assert!(diagnostic.contains("HTTP document transport"));
21070    }
21071
21072    #[test]
21073    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
21074        let envelope = PayloadEnvelope {
21075            codec: DEFAULT_CODEC.to_string(),
21076            blob: BASE64.encode([0x01]),
21077        };
21078
21079        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
21080        assert!(error.to_string().contains("invalid_payload_framing"));
21081    }
21082
21083    #[tokio::test]
21084    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
21085        let server = MockWorkerServer::start();
21086        let client = Client::builder(server.base_url())
21087            .timeout(Duration::from_secs(2))
21088            .build()
21089            .expect("client");
21090        let invalid_commands = [
21091            json!({
21092                "type": "complete_workflow",
21093                "result": {"codec": "json", "blob": null}
21094            }),
21095            json!({
21096                "type": "schedule_activity",
21097                "arguments": {"codec": "yaml", "blob": "ignored"}
21098            }),
21099            json!({
21100                "type": "start_child_workflow",
21101                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
21102            }),
21103            json!({"type": "continue_as_new", "arguments": []}),
21104            json!({"type": "complete_update"}),
21105            json!({"type": "record_side_effect", "result": null}),
21106            json!({
21107                "type": "start_service_operation",
21108                "payload_codec": DEFAULT_CODEC,
21109                "request_payload": "raw-avro-bytes"
21110            }),
21111        ];
21112
21113        for command in invalid_commands {
21114            let error = client
21115                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
21116                .await
21117                .expect_err("invalid durable payload must fail locally");
21118            let diagnostic = error.to_string();
21119            assert!(
21120                diagnostic.contains("unsupported_payload_codec")
21121                    || diagnostic.contains("invalid_payload_envelope")
21122                    || diagnostic.contains("untagged durable payload"),
21123                "unexpected validation diagnostic: {diagnostic}"
21124            );
21125        }
21126
21127        assert_eq!(
21128            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
21129            0,
21130            "invalid command payloads must not reach HTTP transport"
21131        );
21132    }
21133
21134    #[test]
21135    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
21136        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
21137        let commands = [
21138            json!({"type": "complete_workflow", "result": envelope.clone()}),
21139            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
21140            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
21141            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
21142            json!({"type": "complete_update", "result": envelope.clone()}),
21143            json!({"type": "record_side_effect", "result": envelope.clone()}),
21144            json!({
21145                "type": "start_service_operation",
21146                "payload_codec": DEFAULT_CODEC,
21147                "request_payload": envelope.clone()
21148            }),
21149            json!({
21150                "type": "complete_workflow",
21151                "result": envelope,
21152                "metadata": {
21153                    "codec": "json",
21154                    "payload_codec": "customer-codec",
21155                    "result": {"codec": "yaml", "blob": null}
21156                }
21157            }),
21158        ];
21159
21160        validate_workflow_task_commands(&commands)
21161            .expect("customer metadata must not become a protocol codec declaration");
21162    }
21163
21164    #[test]
21165    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
21166        assert_eq!(
21167            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
21168            AvroValue::Array(Vec::new())
21169        );
21170        assert_eq!(
21171            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
21172            AvroValue::Array(Vec::new())
21173        );
21174
21175        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21176        signal.signal_name = Some("empty-signal".to_string());
21177        signal.signal_arguments = None;
21178        let decoded = decode_resume_signal(&signal)
21179            .expect("valid Avro signal")
21180            .expect("named signal resumes the workflow");
21181        assert!(decoded.arguments.is_empty());
21182    }
21183
21184    #[tokio::test]
21185    async fn malformed_task_level_codecs_become_pre_handler_failures() {
21186        let client = Client::new("http://127.0.0.1:8080").expect("client");
21187        let mut worker = Worker::new(client, "rust-workers");
21188        let handler_calls = Arc::new(AtomicUsize::new(0));
21189
21190        let calls = Arc::clone(&handler_calls);
21191        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21192            calls.fetch_add(1, Ordering::SeqCst);
21193            async move { Ok(Value::Null) }
21194        });
21195        let calls = Arc::clone(&handler_calls);
21196        worker.register_activity("codec.activity", move |_ctx, _args| {
21197            calls.fetch_add(1, Ordering::SeqCst);
21198            async move { Ok(Value::Null) }
21199        });
21200        let calls = Arc::clone(&handler_calls);
21201        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21202            calls.fetch_add(1, Ordering::SeqCst);
21203            async move { Ok(Value::Null) }
21204        });
21205
21206        let mut failures = Vec::new();
21207        for codec_case in [
21208            InvalidTaskPayloadCodec::Missing,
21209            InvalidTaskPayloadCodec::Null,
21210            InvalidTaskPayloadCodec::NonString,
21211        ] {
21212            let mut workflow = json!({
21213                "task_id": format!("workflow-{}", codec_case.label()),
21214                "workflow_type": "codec.workflow"
21215            });
21216            codec_case.apply(&mut workflow);
21217            match serde_json::from_value::<WorkflowTask>(workflow) {
21218                Ok(task) => match worker.execute_workflow_task(task) {
21219                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21220                    outcome => failures.push(format!(
21221                        "workflow {} codec returned {outcome:?}",
21222                        codec_case.label()
21223                    )),
21224                },
21225                Err(error) => failures.push(format!(
21226                    "workflow {} codec failed transport deserialization: {error}",
21227                    codec_case.label()
21228                )),
21229            }
21230
21231            let mut activity = json!({
21232                "task_id": format!("activity-{}", codec_case.label()),
21233                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
21234                "activity_type": "codec.activity",
21235                "attempt_number": 1
21236            });
21237            codec_case.apply(&mut activity);
21238            match serde_json::from_value::<ActivityTask>(activity) {
21239                Ok(task) => match worker.execute_activity_task(task).await {
21240                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
21241                    outcome => failures.push(format!(
21242                        "activity {} codec returned {outcome:?}",
21243                        codec_case.label()
21244                    )),
21245                },
21246                Err(error) => failures.push(format!(
21247                    "activity {} codec failed transport deserialization: {error}",
21248                    codec_case.label()
21249                )),
21250            }
21251
21252            let mut query = json!({
21253                "query_task_id": format!("query-{}", codec_case.label()),
21254                "workflow_type": "codec.workflow",
21255                "query_name": "known"
21256            });
21257            codec_case.apply(&mut query);
21258            match serde_json::from_value::<QueryTask>(query) {
21259                Ok(task) => match worker.execute_query_task(task).await {
21260                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
21261                    outcome => failures.push(format!(
21262                        "query {} codec returned {outcome:?}",
21263                        codec_case.label()
21264                    )),
21265                },
21266                Err(error) => failures.push(format!(
21267                    "query {} codec failed transport deserialization: {error}",
21268                    codec_case.label()
21269                )),
21270            }
21271        }
21272
21273        assert!(failures.is_empty(), "{}", failures.join("\n"));
21274        assert_eq!(
21275            handler_calls.load(Ordering::SeqCst),
21276            0,
21277            "invalid task codecs must not invoke a handler"
21278        );
21279    }
21280
21281    #[tokio::test]
21282    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
21283        for codec_case in [
21284            InvalidTaskPayloadCodec::Missing,
21285            InvalidTaskPayloadCodec::Null,
21286            InvalidTaskPayloadCodec::NonString,
21287        ] {
21288            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
21289            let client = Client::builder(server.base_url())
21290                .timeout(Duration::from_secs(2))
21291                .build()
21292                .expect("client");
21293            let mut worker = Worker::new(client, "rust-workers")
21294                .worker_id("codec-worker")
21295                .poll_timeout(Duration::from_millis(10));
21296            let handler_calls = Arc::new(AtomicUsize::new(0));
21297
21298            let calls = Arc::clone(&handler_calls);
21299            worker.register_workflow("codec.workflow", move |_ctx, _args| {
21300                calls.fetch_add(1, Ordering::SeqCst);
21301                async move { Ok(Value::Null) }
21302            });
21303            let calls = Arc::clone(&handler_calls);
21304            worker.register_activity("codec.activity", move |_ctx, _args| {
21305                calls.fetch_add(1, Ordering::SeqCst);
21306                async move { Ok(Value::Null) }
21307            });
21308            let calls = Arc::clone(&handler_calls);
21309            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21310                calls.fetch_add(1, Ordering::SeqCst);
21311                async move { Ok(Value::Null) }
21312            });
21313
21314            assert_eq!(
21315                worker.run_once().await.expect("invalid tasks are settled"),
21316                3,
21317                "all {} codec tasks must be handled",
21318                codec_case.label()
21319            );
21320            assert_eq!(
21321                handler_calls.load(Ordering::SeqCst),
21322                0,
21323                "{} task codecs must fail before every handler",
21324                codec_case.label()
21325            );
21326
21327            for path in [
21328                "/api/worker/workflow-tasks/codec-workflow/fail",
21329                "/api/worker/activity-tasks/codec-activity/fail",
21330                "/api/worker/query-tasks/codec-query/fail",
21331            ] {
21332                let body = server.request_body(path);
21333                assert!(
21334                    body["failure"]["message"]
21335                        .as_str()
21336                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
21337                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
21338                    codec_case.label()
21339                );
21340            }
21341            assert_eq!(
21342                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
21343                    ["reason"],
21344                "query_payload_decode_failed"
21345            );
21346            for path in [
21347                "/api/worker/workflow-tasks/codec-workflow/complete",
21348                "/api/worker/activity-tasks/codec-activity/complete",
21349                "/api/worker/query-tasks/codec-query/complete",
21350            ] {
21351                assert_eq!(
21352                    server.request_count(path),
21353                    0,
21354                    "invalid {} codec task reached {path}",
21355                    codec_case.label()
21356                );
21357            }
21358        }
21359    }
21360
21361    #[tokio::test]
21362    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
21363        let client = Client::new("http://127.0.0.1:8080").expect("client");
21364        let mut worker = Worker::new(client, "rust-workers");
21365        let handler_calls = Arc::new(AtomicUsize::new(0));
21366
21367        let calls = Arc::clone(&handler_calls);
21368        worker.register_workflow("codec.workflow", move |_ctx, _args| {
21369            calls.fetch_add(1, Ordering::SeqCst);
21370            async move { Ok(Value::Null) }
21371        });
21372        let calls = Arc::clone(&handler_calls);
21373        worker.register_activity("codec.activity", move |_ctx, _args| {
21374            calls.fetch_add(1, Ordering::SeqCst);
21375            async move { Ok(Value::Null) }
21376        });
21377        let calls = Arc::clone(&handler_calls);
21378        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
21379            calls.fetch_add(1, Ordering::SeqCst);
21380            async move { Ok(Value::Null) }
21381        });
21382        let calls = Arc::clone(&handler_calls);
21383        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
21384            calls.fetch_add(1, Ordering::SeqCst);
21385            async move { Ok(Value::Null) }
21386        });
21387
21388        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21389        workflow.payload_codec = "json".to_string();
21390        workflow.arguments = None;
21391        let error = worker
21392            .execute_workflow_task(workflow)
21393            .expect_err("task codec must be checked before workflow invocation");
21394        assert!(error.to_string().contains("unsupported_payload_codec"));
21395
21396        let activity = ActivityTask {
21397            task_id: "activity-invalid-codec".to_string(),
21398            activity_attempt_id: None,
21399            attempt_id: None,
21400            activity_type: "codec.activity".to_string(),
21401            payload_codec: "unknown".to_string(),
21402            arguments: None,
21403            attempt_number: 1,
21404            lease_owner: None,
21405        };
21406        let error = worker
21407            .execute_activity_task(activity)
21408            .await
21409            .expect_err("task codec must be checked before activity invocation");
21410        assert!(error.to_string().contains("unsupported_payload_codec"));
21411
21412        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21413        update.workflow_update_id = Some("update-invalid-codec".to_string());
21414        update.update_name = Some("known".to_string());
21415        update.history_events.push(history_event(
21416            "UpdateAccepted",
21417            json!({
21418                "update_id": "update-invalid-codec",
21419                "update_name": "known",
21420                "arguments": {"codec": "json", "blob": null}
21421            }),
21422        ));
21423        let error = worker
21424            .execute_workflow_task(update)
21425            .expect_err("nested update codec must be checked before handler lookup");
21426        assert!(error.to_string().contains("unsupported_payload_codec"));
21427
21428        let query: QueryTask = serde_json::from_value(json!({
21429            "query_task_id": "query-invalid-codec",
21430            "workflow_type": "codec.workflow",
21431            "query_name": "known",
21432            "payload_codec": DEFAULT_CODEC,
21433            "workflow_arguments": null,
21434            "query_arguments": null,
21435            "history_export": {
21436                "payloads": {"codec": DEFAULT_CODEC},
21437                "signals": [{
21438                    "name": "empty",
21439                    "payload_codec": "json",
21440                    "arguments": null
21441                }]
21442            }
21443        }))
21444        .expect("query task");
21445        let failure = worker
21446            .execute_query_task(query)
21447            .await
21448            .expect_err("exported signal codec must be checked before query invocation");
21449        assert_eq!(failure.reason, "query_payload_decode_failed");
21450        assert!(failure.message.contains("unsupported_payload_codec"));
21451
21452        let exported_history: QueryTask = serde_json::from_value(json!({
21453            "query_task_id": "query-invalid-history-codec",
21454            "workflow_type": "codec.workflow",
21455            "query_name": "known",
21456            "payload_codec": DEFAULT_CODEC,
21457            "history_export": {
21458                "payloads": {"codec": DEFAULT_CODEC},
21459                "history_events": [{
21460                    "type": "ActivityCompleted",
21461                    "payload": {"payload_codec": "unknown", "result": null}
21462                }]
21463            }
21464        }))
21465        .expect("query task");
21466        let failure = worker
21467            .execute_query_task(exported_history)
21468            .await
21469            .expect_err("exported history codec must be checked before query invocation");
21470        assert_eq!(failure.reason, "query_payload_decode_failed");
21471        assert!(failure.message.contains("unsupported_payload_codec"));
21472        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
21473
21474        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
21475        unknown_workflow.arguments = None;
21476        unknown_workflow.history_events.push(history_event(
21477            "SignalReceived",
21478            json!({
21479                "signal_name": "empty",
21480                "payload_codec": "json",
21481                "arguments": null
21482            }),
21483        ));
21484        let error = worker
21485            .execute_workflow_task(unknown_workflow)
21486            .expect_err("history codec must precede unknown workflow outcome");
21487        assert!(error.to_string().contains("unsupported_payload_codec"));
21488
21489        let unknown_activity = ActivityTask {
21490            task_id: "activity-unknown".to_string(),
21491            activity_attempt_id: None,
21492            attempt_id: None,
21493            activity_type: "missing".to_string(),
21494            payload_codec: "json".to_string(),
21495            arguments: None,
21496            attempt_number: 1,
21497            lease_owner: None,
21498        };
21499        let error = worker
21500            .execute_activity_task(unknown_activity)
21501            .await
21502            .expect_err("codec must precede unknown activity outcome");
21503        assert!(error.to_string().contains("unsupported_payload_codec"));
21504
21505        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
21506        unknown_update.payload_codec = "json".to_string();
21507        unknown_update.arguments = None;
21508        unknown_update.workflow_update_id = Some("update-unknown".to_string());
21509        unknown_update.update_name = Some("missing".to_string());
21510        let error = worker
21511            .execute_workflow_task(unknown_update)
21512            .expect_err("codec must precede fail_update shortcut");
21513        assert!(error.to_string().contains("unsupported_payload_codec"));
21514
21515        let unknown_query: QueryTask = serde_json::from_value(json!({
21516            "query_task_id": "query-unknown",
21517            "workflow_type": "missing",
21518            "query_name": "missing",
21519            "payload_codec": "json",
21520            "workflow_arguments": null,
21521            "query_arguments": null
21522        }))
21523        .expect("query task");
21524        let failure = worker
21525            .execute_query_task(unknown_query)
21526            .await
21527            .expect_err("codec must precede unknown query outcome");
21528        assert_eq!(failure.reason, "query_payload_decode_failed");
21529        assert!(failure.message.contains("unsupported_payload_codec"));
21530    }
21531
21532    #[tokio::test]
21533    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
21534        let client = Client::new("http://127.0.0.1:8080").expect("client");
21535        let worker = Worker::new(client, "rust-workers");
21536
21537        for event_type in ["SignalReceived", "SignalApplied"] {
21538            for (payload_field, codec) in [
21539                ("value", "json"),
21540                ("input", "unknown"),
21541                ("arguments", "json"),
21542            ] {
21543                let payload = json!({
21544                    "signal_name": "empty",
21545                    payload_field: {"codec": codec, "blob": null}
21546                });
21547                let workflow = workflow_task(
21548                    "missing",
21549                    vec![history_event(event_type, payload.clone())],
21550                    DEFAULT_CODEC,
21551                );
21552                let error = worker
21553                    .execute_workflow_task(workflow)
21554                    .expect_err("signal payload codec must precede unknown workflow outcome");
21555                assert!(
21556                    error.to_string().contains("unsupported_payload_codec"),
21557                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
21558                );
21559
21560                let query: QueryTask = serde_json::from_value(json!({
21561                    "query_task_id": format!("query-{event_type}-{payload_field}"),
21562                    "workflow_type": "missing",
21563                    "query_name": "missing",
21564                    "payload_codec": DEFAULT_CODEC,
21565                    "workflow_arguments": null,
21566                    "query_arguments": null,
21567                    "history_events": [{
21568                        "event_type": event_type,
21569                        "payload": payload
21570                    }]
21571                }))
21572                .expect("query task");
21573                let failure = worker
21574                    .execute_query_task(query)
21575                    .await
21576                    .expect_err("signal payload codec must precede unknown query outcome");
21577                assert_eq!(
21578                    failure.reason, "query_payload_decode_failed",
21579                    "{event_type}.{payload_field} returned an unrelated query outcome"
21580                );
21581                assert!(
21582                    failure.message.contains("unsupported_payload_codec"),
21583                    "{event_type}.{payload_field} returned an unrelated query error: {}",
21584                    failure.message
21585                );
21586            }
21587        }
21588    }
21589
21590    #[test]
21591    fn workflow_context_schedules_activity_until_completion_is_in_history() {
21592        let ctx = WorkflowContext {
21593            cancellation_scope_id: "root".into(),
21594            state: Arc::new(Mutex::new(
21595                WorkflowState::new_with_identity(
21596                    Vec::new(),
21597                    Some("wf-parent".to_string()),
21598                    Some("run-parent".to_string()),
21599                    "rust-workers".to_string(),
21600                    DEFAULT_CODEC.to_string(),
21601                    None,
21602                )
21603                .expect("workflow state"),
21604            )),
21605        };
21606
21607        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
21608        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21609        assert!(matches!(
21610            call.as_mut().poll(&mut task_context),
21611            Poll::Pending
21612        ));
21613
21614        let commands = ctx.take_commands().expect("commands");
21615        assert_eq!(commands[0]["type"], "schedule_activity");
21616        assert_eq!(commands[0]["activity_type"], "hello.activity");
21617    }
21618
21619    #[test]
21620    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
21621        let ctx = workflow_context(Vec::new());
21622        let options = ActivityOptions::new()
21623            .task_queue("payments")
21624            .retry_policy(
21625                ActivityRetryPolicy::new(4)
21626                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
21627                    .non_retryable_error_type("ValidationError"),
21628            )
21629            .start_to_close_timeout(Duration::from_secs(120))
21630            .schedule_to_start_timeout(Duration::from_secs(10))
21631            .schedule_to_close_timeout(Duration::from_secs(300))
21632            .heartbeat_timeout(Duration::from_secs(15));
21633        let mut call = Box::pin(ctx.activity_with_options(
21634            "charge-card",
21635            options,
21636            json!([{"order_id": "o-1"}]),
21637        ));
21638        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21639
21640        assert!(matches!(
21641            call.as_mut().poll(&mut task_context),
21642            Poll::Pending
21643        ));
21644        assert!(matches!(
21645            call.as_mut().poll(&mut task_context),
21646            Poll::Pending
21647        ));
21648
21649        let commands = ctx.take_commands().expect("activity command");
21650        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
21651        assert_eq!(commands[0]["queue"], "payments");
21652        assert_eq!(
21653            commands[0]["retry_policy"],
21654            json!({
21655                "max_attempts": 4,
21656                "backoff_seconds": [1, 3, 9],
21657                "non_retryable_error_types": ["ValidationError"],
21658            })
21659        );
21660        assert_eq!(commands[0]["start_to_close_timeout"], 120);
21661        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
21662        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
21663        assert_eq!(commands[0]["heartbeat_timeout"], 15);
21664    }
21665
21666    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
21667        vec![
21668            history_event(
21669                "ActivityScheduled",
21670                json!({"sequence":1,"activity_type":"render",
21671                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
21672            ),
21673            history_event(
21674                "ActivityCompleted",
21675                json!({"sequence":1,"activity_type":"render",
21676                "payload_codec":DEFAULT_CODEC,
21677                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
21678            ),
21679        ]
21680    }
21681
21682    #[test]
21683    fn worker_session_activity_routes_to_session_queue_once() {
21684        let ctx = workflow_context(Vec::new());
21685        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21686        let mut call = Box::pin(
21687            ctx.activity("render", json!([]))
21688                .in_worker_session(session.clone()),
21689        );
21690        let mut cx = TaskContext::from_waker(noop_waker_ref());
21691        assert!(call.as_mut().poll(&mut cx).is_pending());
21692        assert!(call.as_mut().poll(&mut cx).is_pending());
21693        let commands = ctx.take_commands().unwrap();
21694        assert_eq!(commands.len(), 1);
21695        assert_eq!(commands[0]["queue"], "gpu-workers");
21696        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
21697    }
21698
21699    #[tokio::test]
21700    async fn worker_session_cold_replay_uses_recorded_avro_result() {
21701        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21702        for _replacement in 0..2 {
21703            let ctx = workflow_context(completed_worker_session_history(&session));
21704            let result: i64 = ctx
21705                .activity("render", json!([]))
21706                .in_worker_session(session.clone())
21707                .typed()
21708                .await
21709                .unwrap();
21710            assert_eq!(result, 42);
21711            assert!(ctx.take_commands().unwrap().is_empty());
21712        }
21713    }
21714
21715    #[test]
21716    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
21717        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21718        for changed in [
21719            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
21720            Some(original.clone().ttl_seconds(60)),
21721            Some(original.clone().requirements(["gpu:l4"])),
21722            None,
21723        ] {
21724            let ctx = workflow_context(completed_worker_session_history(&original));
21725            let mut call = ctx.activity_with_options(
21726                "render",
21727                ActivityOptions::new().task_queue("gpu-workers"),
21728                json!([]),
21729            );
21730            if let Some(changed) = changed {
21731                call = call.in_worker_session(changed);
21732            }
21733            let mut call = Box::pin(call);
21734            let mut cx = TaskContext::from_waker(noop_waker_ref());
21735            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
21736                call.as_mut().poll(&mut cx)
21737            else {
21738                panic!("changed session must fail replay");
21739            };
21740            assert_eq!(failure.reason, "activity_worker_session_mismatch");
21741            assert!(ctx.take_commands().unwrap().is_empty());
21742        }
21743    }
21744
21745    #[test]
21746    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
21747        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
21748        let ctx = workflow_context(Vec::new());
21749        let mut local = Box::pin(
21750            ctx.local_activity("render", json!([]))
21751                .in_worker_session(session.clone()),
21752        );
21753        let mut cx = TaskContext::from_waker(noop_waker_ref());
21754        assert!(matches!(
21755            local.as_mut().poll(&mut cx),
21756            Poll::Ready(Err(Error::WorkerLoop(_)))
21757        ));
21758        assert!(ctx.take_commands().unwrap().is_empty());
21759        let mut remote = Box::pin(
21760            ctx.activity_with_options(
21761                "render",
21762                ActivityOptions::new().task_queue("other"),
21763                json!([]),
21764            )
21765            .in_worker_session(session),
21766        );
21767        assert!(matches!(
21768            remote.as_mut().poll(&mut cx),
21769            Poll::Ready(Err(Error::WorkerLoop(_)))
21770        ));
21771        assert!(ctx.take_commands().unwrap().is_empty());
21772    }
21773
21774    #[test]
21775    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
21776        let ctx = workflow_context(Vec::new());
21777        let options = ActivityOptions::new().retry_policy(
21778            ActivityRetryPolicy::new(3)
21779                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
21780        );
21781        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21782        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21783
21784        assert!(matches!(
21785            call.as_mut().poll(&mut task_context),
21786            Poll::Pending
21787        ));
21788        assert_eq!(
21789            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
21790            json!([1, 2])
21791        );
21792    }
21793
21794    #[test]
21795    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
21796        let cases = [
21797            (
21798                ActivityOptions::new().task_queue("  "),
21799                ActivityOptionsErrorKind::EmptyTaskQueue,
21800            ),
21801            (
21802                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
21803                ActivityOptionsErrorKind::EmptyRetryPolicy,
21804            ),
21805            (
21806                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
21807                ActivityOptionsErrorKind::InvalidMaxAttempts,
21808            ),
21809            (
21810                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
21811                    max_attempts: None,
21812                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
21813                    non_retryable_error_types: Vec::new(),
21814                }),
21815                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
21816            ),
21817            (
21818                ActivityOptions::new().retry_policy(
21819                    ActivityRetryPolicy::new(2)
21820                        .backoff_intervals([Duration::from_secs(1), Duration::from_secs(2)]),
21821                ),
21822                ActivityOptionsErrorKind::TooManyBackoffIntervals,
21823            ),
21824            (
21825                ActivityOptions::new().retry_policy(
21826                    ActivityRetryPolicy::new(2).exponential_backoff(
21827                        Duration::from_secs(1),
21828                        0,
21829                        None,
21830                    ),
21831                ),
21832                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
21833            ),
21834            (
21835                ActivityOptions::new()
21836                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
21837                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
21838            ),
21839            (
21840                ActivityOptions::new().retry_policy(
21841                    ActivityRetryPolicy::new(10_002).exponential_backoff(
21842                        Duration::from_secs(1),
21843                        1,
21844                        None,
21845                    ),
21846                ),
21847                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
21848            ),
21849            (
21850                ActivityOptions::new().retry_policy(
21851                    ActivityRetryPolicy::new(2)
21852                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
21853                ),
21854                ActivityOptionsErrorKind::BackoffOverflow,
21855            ),
21856        ];
21857
21858        for (options, expected_kind) in cases {
21859            let ctx = workflow_context(Vec::new());
21860            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
21861            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21862            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
21863                call.as_mut().poll(&mut task_context)
21864            else {
21865                panic!("expected typed activity validation error");
21866            };
21867            assert_eq!(error.kind, expected_kind);
21868            assert!(ctx.take_commands().expect("commands").is_empty());
21869        }
21870    }
21871
21872    #[test]
21873    fn activity_options_validate_positive_and_ordered_timeouts() {
21874        let zero_timeout_cases = [
21875            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
21876            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
21877            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
21878            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
21879        ];
21880        for options in zero_timeout_cases {
21881            assert_eq!(
21882                options.validate().expect_err("zero timeout").kind,
21883                ActivityOptionsErrorKind::TimeoutNotPositive
21884            );
21885        }
21886
21887        let ordering_cases = [
21888            ActivityOptions::new()
21889                .heartbeat_timeout(Duration::from_secs(11))
21890                .start_to_close_timeout(Duration::from_secs(10)),
21891            ActivityOptions::new()
21892                .start_to_close_timeout(Duration::from_secs(31))
21893                .schedule_to_close_timeout(Duration::from_secs(30)),
21894            ActivityOptions::new()
21895                .schedule_to_start_timeout(Duration::from_secs(31))
21896                .schedule_to_close_timeout(Duration::from_secs(30)),
21897        ];
21898        for options in ordering_cases {
21899            assert_eq!(
21900                options.validate().expect_err("timeout order").kind,
21901                ActivityOptionsErrorKind::TimeoutOrder
21902            );
21903        }
21904
21905        assert_eq!(
21906            ActivityOptions::new()
21907                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
21908                .validate()
21909                .expect_err("protocol integer overflow")
21910                .kind,
21911            ActivityOptionsErrorKind::TimeoutOverflow
21912        );
21913    }
21914
21915    #[test]
21916    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
21917        let ctx = workflow_context(completed_retry_activity_history());
21918        let mut call =
21919            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21920        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21921
21922        assert!(matches!(
21923            call.as_mut().poll(&mut task_context),
21924            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21925        ));
21926        assert!(ctx.take_commands().expect("commands").is_empty());
21927        ctx.ensure_history_consumed().expect("history consumed");
21928    }
21929
21930    #[test]
21931    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
21932        let mut options = retry_activity_options();
21933        options
21934            .retry_policy
21935            .as_mut()
21936            .expect("retry policy")
21937            .non_retryable_error_types
21938            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
21939
21940        let new_ctx = workflow_context(Vec::new());
21941        let mut new_call =
21942            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
21943        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21944        assert!(matches!(
21945            new_call.as_mut().poll(&mut task_context),
21946            Poll::Pending
21947        ));
21948        let commands = new_ctx.take_commands().expect("commands");
21949        assert_eq!(commands.len(), 1);
21950        assert_eq!(
21951            commands[0]["retry_policy"]["non_retryable_error_types"],
21952            json!(["PermanentError"])
21953        );
21954
21955        let replay_ctx = workflow_context(completed_retry_activity_history());
21956        let mut replay_call =
21957            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
21958        assert!(matches!(
21959            replay_call.as_mut().poll(&mut task_context),
21960            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
21961        ));
21962        assert!(replay_ctx.take_commands().expect("commands").is_empty());
21963        replay_ctx
21964            .ensure_history_consumed()
21965            .expect("history consumed");
21966    }
21967
21968    #[test]
21969    fn replayed_intermediate_retry_remains_pending_across_restarts() {
21970        let history = completed_retry_activity_history()
21971            .into_iter()
21972            .take(3)
21973            .collect::<Vec<_>>();
21974
21975        for _restart in 0..2 {
21976            let ctx = workflow_context(history.clone());
21977            let mut call =
21978                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
21979            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21980            assert!(matches!(
21981                call.as_mut().poll(&mut task_context),
21982                Poll::Pending
21983            ));
21984            assert!(ctx.take_commands().expect("commands").is_empty());
21985        }
21986    }
21987
21988    #[test]
21989    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
21990        let mut changed_queue = retry_activity_options();
21991        changed_queue.task_queue = Some("different-queue".to_string());
21992
21993        let mut changed_max_attempts = retry_activity_options();
21994        let retry_policy = changed_max_attempts
21995            .retry_policy
21996            .as_mut()
21997            .expect("retry policy");
21998        retry_policy.max_attempts = Some(4);
21999
22000        let mut changed_backoff = retry_activity_options();
22001        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
22002        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
22003            Duration::from_secs(3),
22004            Duration::from_secs(4),
22005        ]));
22006
22007        let mut changed_non_retryable_types = retry_activity_options();
22008        let retry_policy = changed_non_retryable_types
22009            .retry_policy
22010            .as_mut()
22011            .expect("retry policy");
22012        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
22013
22014        let mut changed_start_to_close = retry_activity_options();
22015        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
22016        let mut changed_schedule_to_start = retry_activity_options();
22017        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
22018        let mut changed_schedule_to_close = retry_activity_options();
22019        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
22020        let mut changed_heartbeat = retry_activity_options();
22021        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
22022
22023        let cases = [
22024            (changed_queue, "activity_task_queue_mismatch"),
22025            (changed_max_attempts, "activity_retry_policy_mismatch"),
22026            (changed_backoff, "activity_retry_policy_mismatch"),
22027            (
22028                changed_non_retryable_types,
22029                "activity_retry_policy_mismatch",
22030            ),
22031            (changed_start_to_close, "activity_retry_policy_mismatch"),
22032            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
22033            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
22034            (changed_heartbeat, "activity_retry_policy_mismatch"),
22035        ];
22036
22037        for (options, expected_reason) in cases {
22038            let ctx = workflow_context(completed_retry_activity_history());
22039            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
22040            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22041            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22042                call.as_mut().poll(&mut task_context)
22043            else {
22044                panic!("changed activity options must fail replay");
22045            };
22046            assert_eq!(failure.reason, expected_reason);
22047            assert_eq!(failure.sequence, Some(1));
22048            assert!(ctx.take_commands().expect("commands").is_empty());
22049        }
22050    }
22051
22052    #[test]
22053    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
22054        let cases = [
22055            (
22056                "execution_mode",
22057                json!("local"),
22058                "activity_execution_mode_mismatch",
22059            ),
22060            (
22061                "snapshot_version",
22062                json!(2),
22063                "activity_retry_policy_mismatch",
22064            ),
22065        ];
22066
22067        for (field, value, expected_reason) in cases {
22068            let mut history = completed_retry_activity_history();
22069            let activity = history[0].payload["activity"]
22070                .as_object_mut()
22071                .expect("activity snapshot");
22072            if field == "execution_mode" {
22073                activity.insert(field.to_string(), value);
22074            } else {
22075                activity["retry_policy"]
22076                    .as_object_mut()
22077                    .expect("retry snapshot")
22078                    .insert(field.to_string(), value);
22079            }
22080
22081            let ctx = workflow_context(history);
22082            let mut call =
22083                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22084            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22085            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22086                call.as_mut().poll(&mut task_context)
22087            else {
22088                panic!("changed {field} must fail replay");
22089            };
22090            assert_eq!(failure.reason, expected_reason);
22091            assert_eq!(failure.sequence, Some(1));
22092            assert!(ctx.take_commands().expect("commands").is_empty());
22093        }
22094    }
22095
22096    #[test]
22097    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
22098        for (nested, field, value, terminal_only) in [
22099            (false, "execution_mode", json!("local"), false),
22100            (false, "local_activity", json!(true), false),
22101            (true, "local_activity", json!(true), false),
22102            (false, "local_activity", json!(true), true),
22103        ] {
22104            let mut history = completed_retry_activity_history();
22105            history[0]
22106                .payload
22107                .as_object_mut()
22108                .unwrap()
22109                .remove("activity");
22110            let event = if terminal_only {
22111                history.last_mut().unwrap()
22112            } else {
22113                &mut history[0]
22114            };
22115            if nested {
22116                event.payload["activity"] = json!({(field): value});
22117            } else {
22118                event.payload[field] = value;
22119            }
22120            let ctx = workflow_context(history);
22121            let mut call =
22122                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22123            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22124            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22125                call.as_mut().poll(&mut task_context)
22126            else {
22127                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
22128            };
22129            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
22130            assert_eq!(failure.sequence, Some(1));
22131            assert!(ctx.take_commands().expect("commands").is_empty());
22132        }
22133    }
22134
22135    #[test]
22136    fn activity_history_rejects_conflicting_local_execution_markers() {
22137        let mut history = completed_retry_activity_history();
22138        history.last_mut().unwrap().payload["local_activity"] = json!(true);
22139        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
22140            .expect_err("remote schedule cannot become a local completion");
22141        assert!(
22142            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
22143            if reason == "activity_execution_mode_conflict")
22144        );
22145    }
22146
22147    #[test]
22148    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
22149        let mut history = completed_retry_activity_history();
22150        let activity = history[0].payload["activity"]
22151            .as_object_mut()
22152            .expect("activity snapshot");
22153        activity.remove("execution_mode");
22154        activity.remove("retry_policy");
22155
22156        let mut current = retry_activity_options();
22157        current.start_to_close_timeout = Some(Duration::from_secs(45));
22158        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
22159        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
22160        current.heartbeat_timeout = Some(Duration::from_secs(12));
22161
22162        let ctx = workflow_context(history);
22163        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
22164        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22165        assert!(matches!(
22166            call.as_mut().poll(&mut task_context),
22167            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
22168        ));
22169        assert!(ctx.take_commands().expect("commands").is_empty());
22170        ctx.ensure_history_consumed().expect("history consumed");
22171    }
22172
22173    #[test]
22174    fn terminal_activity_failed_after_start_returns_typed_failure() {
22175        let history = vec![
22176            history_event(
22177                "ActivityScheduled",
22178                json!({
22179                    "sequence": 1,
22180                    "activity_type": "flaky",
22181                    "activity_execution_id": "act-terminal",
22182                    "activity": {
22183                        "id": "act-terminal",
22184                        "sequence": 1,
22185                        "type": "flaky",
22186                        "queue": "critical-activities",
22187                        "retry_policy": {
22188                            "snapshot_version": 1,
22189                            "max_attempts": 3,
22190                            "backoff_seconds": [2, 4],
22191                            "non_retryable_error_types": ["PermanentError"]
22192                        }
22193                    }
22194                }),
22195            ),
22196            history_event(
22197                "ActivityStarted",
22198                json!({
22199                    "sequence": 1,
22200                    "activity_type": "flaky",
22201                    "activity_execution_id": "act-terminal",
22202                    "activity_attempt_id": "attempt-1",
22203                    "attempt_number": 1
22204                }),
22205            ),
22206            history_event(
22207                "ActivityFailed",
22208                json!({
22209                    "sequence": 1,
22210                    "activity_type": "flaky",
22211                    "activity_execution_id": "act-terminal",
22212                    "activity_attempt_id": "attempt-1",
22213                    "attempt_number": 1,
22214                    "failure_id": "failure-terminal",
22215                    "failure_category": "activity",
22216                    "exception_type": "PermanentError",
22217                    "message": "cannot retry",
22218                    "non_retryable": true
22219                }),
22220            ),
22221        ];
22222        let ctx = workflow_context(history);
22223        let mut call =
22224            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
22225        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22226
22227        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22228            call.as_mut().poll(&mut task_context)
22229        else {
22230            panic!("terminal ActivityFailed must settle the activity future");
22231        };
22232        assert_eq!(failure.kind, ActivityFailureKind::Failed);
22233        assert_eq!(
22234            failure.activity_execution_id.as_deref(),
22235            Some("act-terminal")
22236        );
22237        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
22238        assert!(failure.non_retryable);
22239        assert!(ctx.take_commands().expect("commands").is_empty());
22240        ctx.ensure_history_consumed().expect("history consumed");
22241    }
22242
22243    #[test]
22244    fn activity_terminal_events_return_machine_readable_failures() {
22245        let cases = [
22246            (
22247                "ActivityFailed",
22248                json!({
22249                    "sequence": 1,
22250                    "activity_type": "charge-card",
22251                    "activity_execution_id": "act-1",
22252                    "activity_attempt_id": "attempt-2",
22253                    "attempt_number": 2,
22254                    "failure_id": "failure-1",
22255                    "failure_category": "activity",
22256                    "exception_type": "PaymentDeclined",
22257                    "exception_class": "payments.PaymentDeclined",
22258                    "message": "card declined",
22259                    "non_retryable": true
22260                }),
22261                ActivityFailureKind::Failed,
22262                "activity",
22263            ),
22264            (
22265                "ActivityCancelled",
22266                json!({
22267                    "sequence": 1,
22268                    "activity_type": "charge-card",
22269                    "activity_execution_id": "act-1",
22270                    "activity_attempt_id": "attempt-1"
22271                }),
22272                ActivityFailureKind::Cancelled,
22273                "cancelled",
22274            ),
22275        ];
22276
22277        for (event_type, payload, expected_kind, expected_reason) in cases {
22278            let ctx = workflow_context(vec![history_event(event_type, payload)]);
22279            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
22280            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22281            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22282                call.as_mut().poll(&mut task_context)
22283            else {
22284                panic!("expected terminal activity failure");
22285            };
22286            assert_eq!(failure.kind, expected_kind);
22287            assert_eq!(failure.reason, expected_reason);
22288            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
22289            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
22290        }
22291    }
22292
22293    #[test]
22294    fn every_activity_timeout_class_is_typed() {
22295        for timeout_kind in [
22296            "start_to_close",
22297            "schedule_to_start",
22298            "schedule_to_close",
22299            "heartbeat",
22300        ] {
22301            let ctx = workflow_context(vec![history_event(
22302                "ActivityTimedOut",
22303                json!({
22304                    "sequence": 1,
22305                    "activity_type": "slow",
22306                    "activity_execution_id": "act-timeout",
22307                    "activity_attempt_id": "attempt-timeout",
22308                    "failure_category": "timeout",
22309                    "timeout_kind": timeout_kind,
22310                    "message": "deadline expired"
22311                }),
22312            )]);
22313            let mut call = Box::pin(ctx.activity("slow", json!([])));
22314            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22315            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
22316                call.as_mut().poll(&mut task_context)
22317            else {
22318                panic!("expected timeout failure");
22319            };
22320            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
22321            assert_eq!(failure.reason, timeout_kind);
22322            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
22323            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
22324        }
22325    }
22326
22327    #[test]
22328    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
22329        let ctx = workflow_context(Vec::new());
22330        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
22331        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22332
22333        assert!(matches!(
22334            sleep.as_mut().poll(&mut task_context),
22335            Poll::Pending
22336        ));
22337        assert!(matches!(
22338            sleep.as_mut().poll(&mut task_context),
22339            Poll::Pending
22340        ));
22341
22342        let commands = ctx.take_commands().expect("timer command");
22343        assert_eq!(
22344            commands,
22345            vec![json!({
22346                "type": "start_timer",
22347                "delay_seconds": 2,
22348            })]
22349        );
22350    }
22351
22352    #[test]
22353    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
22354        let history = vec![
22355            history_event(
22356                "TimerScheduled",
22357                json!({
22358                    "sequence": 1,
22359                    "timer_id": "timer-1",
22360                    "delay_seconds": 5,
22361                    "fire_at": "2026-07-11T12:00:05Z",
22362                }),
22363            ),
22364            history_event(
22365                "TimerFired",
22366                json!({
22367                    "sequence": 1,
22368                    "timer_id": "timer-1",
22369                    "delay_seconds": 5,
22370                    "fire_at": "2026-07-11T12:00:05Z",
22371                    "fired_at": "2026-07-11T12:00:05Z",
22372                }),
22373            ),
22374        ];
22375
22376        for _restart in 0..2 {
22377            let ctx = workflow_context(history.clone());
22378            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
22379            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22380            assert!(matches!(
22381                sleep.as_mut().poll(&mut task_context),
22382                Poll::Ready(Ok(()))
22383            ));
22384            assert!(ctx.take_commands().expect("commands").is_empty());
22385            ctx.ensure_history_consumed().expect("history consumed");
22386        }
22387    }
22388
22389    #[test]
22390    fn workflow_sleep_rejects_changed_delay_during_replay() {
22391        let ctx = workflow_context(vec![
22392            history_event(
22393                "TimerScheduled",
22394                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22395            ),
22396            history_event(
22397                "TimerFired",
22398                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
22399            ),
22400        ]);
22401        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
22402        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22403
22404        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
22405            sleep.as_mut().poll(&mut task_context)
22406        else {
22407            panic!("changed timer delay must be rejected");
22408        };
22409        assert_eq!(failure.reason, "timer_delay_mismatch");
22410        assert_eq!(failure.sequence, Some(1));
22411    }
22412
22413    #[test]
22414    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
22415        let ctx = workflow_context(Vec::new());
22416        let mut wait = Box::pin(
22417            ctx.wait_condition(
22418                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
22419                    .timeout(Duration::from_millis(60_001)),
22420                || Ok(false),
22421            ),
22422        );
22423        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22424
22425        assert!(matches!(
22426            wait.as_mut().poll(&mut task_context),
22427            Poll::Pending
22428        ));
22429        assert!(matches!(
22430            wait.as_mut().poll(&mut task_context),
22431            Poll::Pending
22432        ));
22433        assert_eq!(
22434            ctx.take_commands().expect("condition command"),
22435            vec![json!({
22436                "type": "open_condition_wait",
22437                "condition_wait_occurrence_id": "rust:condition-wait:0",
22438                "condition_key": "approval.ready",
22439                "condition_definition_fingerprint": "sha256:approval-v1",
22440                "timeout_seconds": 61,
22441            })]
22442        );
22443    }
22444
22445    #[test]
22446    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
22447        let ctx = workflow_context(Vec::new());
22448        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
22449        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22450        assert!(matches!(
22451            satisfied.as_mut().poll(&mut task_context),
22452            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22453        ));
22454
22455        let mut timed_out = Box::pin(wait_condition!(
22456            ctx,
22457            "no-wait",
22458            timeout: Duration::ZERO,
22459            || Ok(false),
22460        ));
22461        assert!(matches!(
22462            timed_out.as_mut().poll(&mut task_context),
22463            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22464        ));
22465        assert!(ctx.take_commands().expect("commands").is_empty());
22466    }
22467
22468    #[test]
22469    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
22470        let signal_history = vec![
22471            history_event(
22472                "ConditionWaitOpened",
22473                json!({
22474                    "sequence": 4,
22475                    "condition_wait_id": "condition:4",
22476                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22477                    "condition_key": "approval",
22478                    "condition_definition_fingerprint": "sha256:approval-v1",
22479                    "timeout_seconds": 30,
22480                }),
22481            ),
22482            history_event(
22483                "SignalReceived",
22484                json!({
22485                    "workflow_sequence": 4,
22486                    "signal_name": "approve",
22487                    "arguments": fixture_envelope(json!(["Ada"])),
22488                }),
22489            ),
22490        ];
22491        for _worker_before_or_after_restart in 0..2 {
22492            let ctx = workflow_context(signal_history.clone());
22493            let predicate_ctx = ctx.clone();
22494            let mut wait = Box::pin(
22495                ctx.wait_condition(
22496                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
22497                        .timeout(Duration::from_secs(30)),
22498                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
22499                ),
22500            );
22501            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22502            assert!(matches!(
22503                wait.as_mut().poll(&mut task_context),
22504                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22505            ));
22506            assert!(ctx.take_commands().expect("commands").is_empty());
22507            ctx.ensure_history_consumed().expect("condition consumed");
22508        }
22509
22510        let update_history = vec![
22511            history_event(
22512                "ConditionWaitOpened",
22513                json!({
22514                    "sequence": 7,
22515                    "condition_wait_id": "condition:7",
22516                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22517                    "condition_key": "update-approval",
22518                    "condition_definition_fingerprint": "sha256:update-approval-v1",
22519                }),
22520            ),
22521            history_event(
22522                "UpdateApplied",
22523                json!({
22524                    "sequence": 7,
22525                    "update_id": "update-1",
22526                    "update_name": "approve",
22527                    "arguments": fixture_envelope(json!([true])),
22528                }),
22529            ),
22530        ];
22531        let ctx = workflow_context(update_history);
22532        let predicate_ctx = ctx.clone();
22533        let mut wait = Box::pin(ctx.wait_condition(
22534            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
22535            move || {
22536                Ok(predicate_ctx
22537                    .updates("approve")?
22538                    .first()
22539                    .and_then(|arguments| arguments.first())
22540                    .and_then(Value::as_bool)
22541                    == Some(true))
22542            },
22543        ));
22544        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22545        assert!(matches!(
22546            wait.as_mut().poll(&mut task_context),
22547            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22548        ));
22549        assert!(ctx.take_commands().expect("commands").is_empty());
22550        ctx.ensure_history_consumed().expect("condition consumed");
22551    }
22552
22553    #[test]
22554    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
22555        let open_history = vec![
22556            history_event(
22557                "ConditionWaitOpened",
22558                json!({
22559                    "sequence": 3,
22560                    "condition_wait_id": "condition:3",
22561                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22562                    "condition_key": "two-votes",
22563                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22564                    "timeout_seconds": 120,
22565                }),
22566            ),
22567            history_event(
22568                "SignalReceived",
22569                json!({
22570                    "workflow_sequence": 3,
22571                    "signal_name": "vote",
22572                    "arguments": fixture_envelope(json!(["first"])),
22573                }),
22574            ),
22575        ];
22576        for _worker_before_or_after_restart in 0..2 {
22577            let ctx = workflow_context(open_history.clone());
22578            let predicate_ctx = ctx.clone();
22579            let mut wait = Box::pin(
22580                ctx.wait_condition(
22581                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22582                        .timeout(Duration::from_secs(120)),
22583                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
22584                ),
22585            );
22586            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22587            assert!(matches!(
22588                wait.as_mut().poll(&mut task_context),
22589                Poll::Pending
22590            ));
22591            assert_eq!(
22592                ctx.take_commands().expect("reopened condition"),
22593                vec![json!({
22594                    "type": "open_condition_wait",
22595                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22596                    "condition_key": "two-votes",
22597                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22598                    "timeout_seconds": 120,
22599                })]
22600            );
22601        }
22602
22603        let satisfied_ctx = workflow_context(vec![
22604            history_event(
22605                "ConditionWaitOpened",
22606                json!({
22607                    "sequence": 5,
22608                    "condition_wait_id": "condition:5",
22609                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22610                    "condition_key": "approval",
22611                    "condition_definition_fingerprint": "sha256:approval-v1",
22612                }),
22613            ),
22614            history_event(
22615                "ConditionWaitSatisfied",
22616                json!({
22617                    "sequence": 5,
22618                    "condition_wait_id": "condition:5",
22619                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22620                    "condition_key": "approval",
22621                    "condition_definition_fingerprint": "sha256:approval-v1",
22622                }),
22623            ),
22624        ]);
22625        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
22626            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
22627            || Ok(false),
22628        ));
22629        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22630        assert!(matches!(
22631            satisfied.as_mut().poll(&mut task_context),
22632            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22633        ));
22634
22635        let timed_out_ctx = workflow_context(vec![
22636            history_event(
22637                "ConditionWaitOpened",
22638                json!({
22639                    "sequence": 8,
22640                    "condition_wait_id": "condition:8",
22641                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22642                    "condition_key": "approval-timeout",
22643                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
22644                    "timeout_seconds": 5,
22645                }),
22646            ),
22647            history_event(
22648                "TimerScheduled",
22649                json!({
22650                    "sequence": 9,
22651                    "timer_id": "condition-timer:9",
22652                    "timer_kind": "condition_timeout",
22653                    "condition_wait_id": "condition:8",
22654                    "delay_seconds": 5,
22655                }),
22656            ),
22657            history_event(
22658                "TimerFired",
22659                json!({
22660                    "sequence": 9,
22661                    "timer_id": "condition-timer:9",
22662                    "timer_kind": "condition_timeout",
22663                    "condition_wait_id": "condition:8",
22664                    "delay_seconds": 5,
22665                }),
22666            ),
22667        ]);
22668        let mut timed_out = Box::pin(
22669            timed_out_ctx.wait_condition(
22670                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
22671                    .timeout(Duration::from_secs(5)),
22672                || Ok(true),
22673            ),
22674        );
22675        assert!(matches!(
22676            timed_out.as_mut().poll(&mut task_context),
22677            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
22678        ));
22679    }
22680
22681    #[test]
22682    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
22683        let ctx = workflow_context(reopened_selection_condition_history());
22684        {
22685            let state = ctx.state.lock().unwrap();
22686            assert!(matches!(
22687                selection_member_recorded_command(&state, 2),
22688                Some(RecordedCommand::ConditionWait {
22689                    sequence: 3,
22690                    result: None,
22691                    ..
22692                })
22693            ));
22694        }
22695        let mut selected = Box::pin(ctx.select_keyed(vec![
22696            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22697            (
22698                "votes",
22699                ParallelOperation::condition(
22700                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
22701                    || Ok(true),
22702                ),
22703            ),
22704        ]));
22705        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22706        assert!(selected.as_mut().poll(&mut task_context).is_pending());
22707        assert!(
22708            ctx.take_commands().unwrap().is_empty(),
22709            "true predicate must not reopen the recorded wait"
22710        );
22711        ctx.ensure_history_consumed()
22712            .expect("physical reopens are consumed while canonical selection is pending");
22713    }
22714
22715    #[test]
22716    fn reopened_selection_condition_replays_its_latest_physical_winner() {
22717        for (terminal_type, acknowledge_timeout) in [
22718            ("ConditionWaitSatisfied", false),
22719            ("ConditionWaitTimedOut", false),
22720            ("TimerFired", false),
22721            ("TimerFired", true),
22722        ] {
22723            let mut history = reopened_selection_condition_history();
22724            let original_identity = history[1].payload["condition_wait_id"].clone();
22725            let uses_timer = terminal_type == "TimerFired";
22726            let mut resolution_payload = history[3].payload.clone();
22727            if uses_timer {
22728                for event in &mut history[1..] {
22729                    event.payload["timeout_seconds"] = json!(3);
22730                }
22731                resolution_payload = history[3].payload.clone();
22732                resolution_payload["timer_kind"] = json!("condition_timeout");
22733                resolution_payload["timer_id"] = json!("condition-timeout-3");
22734                resolution_payload["delay_seconds"] = json!(3);
22735                history.push(history_event("TimerScheduled", resolution_payload.clone()));
22736            }
22737            let mut resolution = history_event(terminal_type, resolution_payload.clone());
22738            resolution
22739                .raw
22740                .insert("id".into(), json!("latest-condition-resolution"));
22741            history.push(resolution);
22742            history.push(history_event(
22743                "SelectionResolved",
22744                json!({
22745                    "selection_group_id": "select-calls:1:2",
22746                    "selection_group_base_sequence": 1,
22747                    "selection_group_size": 2,
22748                    "member_key": "votes",
22749                    "member_index": 1,
22750                    "member_base_sequence": 2,
22751                    "member_size": 1,
22752                    "operation_kind": "condition",
22753                    "operation_identity": original_identity,
22754                    "outcome": "completed",
22755                    "resolution_event_id": "latest-condition-resolution",
22756                    "resolution_event_type": terminal_type,
22757                }),
22758            ));
22759            if acknowledge_timeout {
22760                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
22761            }
22762            let ctx = workflow_context(history);
22763            let mut selected = Box::pin(ctx.select_keyed(vec![
22764                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
22765                (
22766                    "votes",
22767                    ParallelOperation::condition(
22768                        if uses_timer {
22769                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22770                                .timeout(Duration::from_secs(3))
22771                        } else {
22772                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
22773                        },
22774                        || Ok(true),
22775                    ),
22776                ),
22777            ]));
22778            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22779            match selected.as_mut().poll(&mut task_context) {
22780                Poll::Ready(Ok(result)) => {
22781                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
22782                    let expected = if terminal_type == "ConditionWaitSatisfied" {
22783                        ConditionWaitResult::Satisfied
22784                    } else {
22785                        ConditionWaitResult::TimedOut
22786                    };
22787                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
22788                }
22789                other => panic!("latest physical winner must replay: {other:?}"),
22790            }
22791            assert!(ctx.take_commands().unwrap().is_empty());
22792            ctx.ensure_history_consumed()
22793                .expect("winner history consumed");
22794        }
22795    }
22796
22797    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
22798        let fixture: Value = serde_json::from_str(include_str!(
22799            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
22800        ))
22801        .expect("grouped condition fixture");
22802        fixture["history"]
22803            .as_array()
22804            .unwrap()
22805            .iter()
22806            .map(|event| {
22807                let mut payload = event["payload"].clone();
22808                let index = payload["parallel_group_index"].as_u64().unwrap();
22809                payload["parallel_group_id"] = json!("select-calls:1:2");
22810                payload["parallel_group_mode"] = json!("select");
22811                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
22812                payload["selection_member_index"] = json!(index);
22813                payload["selection_member_base_sequence"] = json!(index + 1);
22814                payload["selection_member_size"] = json!(1);
22815                payload["selection_member_kind"] =
22816                    json!(if index == 0 { "timer" } else { "condition" });
22817                history_event(event["event_type"].as_str().unwrap(), payload)
22818            })
22819            .collect()
22820    }
22821
22822    #[test]
22823    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
22824        let fixture: Value = serde_json::from_str(include_str!(
22825            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
22826        ))
22827        .expect("grouped condition fixture");
22828        let original = fixture["history"].as_array().expect("fixture history");
22829        let decode = |events: &[Value]| {
22830            let history = events
22831                .iter()
22832                .map(|event| {
22833                    history_event(
22834                        event["event_type"].as_str().unwrap(),
22835                        event["payload"].clone(),
22836                    )
22837                })
22838                .collect::<Vec<_>>();
22839            recorded_commands(
22840                &history,
22841                DEFAULT_CODEC,
22842                WorkflowIdentity {
22843                    workflow_id: None,
22844                    run_id: None,
22845                },
22846            )
22847        };
22848        assert!(decode(original).is_ok());
22849        for field in [
22850            "condition_wait_occurrence_id",
22851            "condition_key",
22852            "condition_definition_fingerprint",
22853            "timeout_seconds",
22854            "parallel_group_id",
22855            "parallel_group_size",
22856            "parallel_group_index",
22857        ] {
22858            let mut changed = original.clone();
22859            changed[3]["payload"][field] = match field {
22860                "timeout_seconds" | "parallel_group_size" => json!(30),
22861                "parallel_group_index" => json!(0),
22862                _ => json!("changed"),
22863            };
22864            assert!(
22865                decode(&changed).is_err(),
22866                "reopen must reject changed {field}"
22867            );
22868        }
22869        let mut unsettled = original.clone();
22870        unsettled.remove(2);
22871        assert!(
22872            decode(&unsettled).is_err(),
22873            "physical predecessor must be resolved"
22874        );
22875        let mut timed_out = original.clone();
22876        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
22877        assert!(decode(&timed_out).is_err(), "timeout is terminal");
22878        let mut late_resolution = original.clone();
22879        late_resolution.swap(2, 3);
22880        assert!(
22881            decode(&late_resolution).is_err(),
22882            "later history cannot authorize a reopen"
22883        );
22884    }
22885
22886    #[test]
22887    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
22888        let history = vec![
22889            history_event(
22890                "ConditionWaitOpened",
22891                json!({
22892                    "sequence": 3,
22893                    "condition_wait_id": "condition:3",
22894                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22895                    "condition_key": "two-votes",
22896                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22897                }),
22898            ),
22899            history_event(
22900                "SignalReceived",
22901                json!({
22902                    "workflow_sequence": 3,
22903                    "signal_name": "vote",
22904                    "arguments": fixture_envelope(json!(["first"])),
22905                }),
22906            ),
22907            history_event(
22908                "ConditionWaitSatisfied",
22909                json!({
22910                    "sequence": 3,
22911                    "condition_wait_id": "condition:3",
22912                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22913                    "condition_key": "two-votes",
22914                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22915                }),
22916            ),
22917            history_event(
22918                "ConditionWaitOpened",
22919                json!({
22920                    "sequence": 5,
22921                    "condition_wait_id": "condition:5",
22922                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22923                    "condition_key": "two-votes",
22924                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22925                }),
22926            ),
22927            history_event(
22928                "SignalReceived",
22929                json!({
22930                    "workflow_sequence": 5,
22931                    "signal_name": "vote",
22932                    "arguments": fixture_envelope(json!(["second"])),
22933                }),
22934            ),
22935            history_event(
22936                "ConditionWaitSatisfied",
22937                json!({
22938                    "sequence": 5,
22939                    "condition_wait_id": "condition:5",
22940                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22941                    "condition_key": "two-votes",
22942                    "condition_definition_fingerprint": "sha256:two-votes-v1",
22943                }),
22944            ),
22945        ];
22946        for _cold_worker_or_restart in 0..2 {
22947            let ctx = workflow_context(history.clone());
22948            let predicate_ctx = ctx.clone();
22949            let mut wait = Box::pin(ctx.wait_condition(
22950                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
22951                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
22952            ));
22953            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22954
22955            assert!(matches!(
22956                wait.as_mut().poll(&mut task_context),
22957                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
22958            ));
22959            assert!(ctx.take_commands().expect("commands").is_empty());
22960            ctx.ensure_history_consumed()
22961                .expect("every physical wait-open is consumed");
22962        }
22963    }
22964
22965    #[test]
22966    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
22967        let history = vec![
22968            history_event(
22969                "ConditionWaitOpened",
22970                json!({
22971                    "sequence": 3,
22972                    "condition_wait_id": "condition:3",
22973                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22974                    "condition_key": "approved",
22975                    "condition_definition_fingerprint": "sha256:approved-v1",
22976                }),
22977            ),
22978            history_event(
22979                "UpdateApplied",
22980                json!({
22981                    "sequence": 3,
22982                    "update_id": "update-1",
22983                    "update_name": "approve",
22984                    "arguments": fixture_envelope(json!([false])),
22985                }),
22986            ),
22987            history_event(
22988                "ConditionWaitOpened",
22989                json!({
22990                    "sequence": 5,
22991                    "condition_wait_id": "condition:5",
22992                    "condition_wait_occurrence_id": "rust:condition-wait:0",
22993                    "condition_key": "approved",
22994                    "condition_definition_fingerprint": "sha256:approved-v1",
22995                }),
22996            ),
22997            history_event(
22998                "UpdateApplied",
22999                json!({
23000                    "sequence": 5,
23001                    "update_id": "update-2",
23002                    "update_name": "approve",
23003                    "arguments": fixture_envelope(json!([true])),
23004                }),
23005            ),
23006        ];
23007
23008        for _cold_worker_or_restart in 0..2 {
23009            let ctx = workflow_context(history.clone());
23010            let predicate_ctx = ctx.clone();
23011            let mut wait = Box::pin(ctx.wait_condition(
23012                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
23013                move || {
23014                    Ok(predicate_ctx
23015                        .updates("approve")?
23016                        .last()
23017                        .and_then(|arguments| arguments.first())
23018                        .and_then(Value::as_bool)
23019                        == Some(true))
23020                },
23021            ));
23022            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23023
23024            assert!(matches!(
23025                wait.as_mut().poll(&mut task_context),
23026                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23027            ));
23028            assert!(ctx.take_commands().expect("commands").is_empty());
23029            ctx.ensure_history_consumed()
23030                .expect("every update-driven reopen is consumed");
23031        }
23032    }
23033
23034    #[test]
23035    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
23036        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
23037            ("shared", "sha256:first", "shared", "sha256:second"),
23038            ("first", "sha256:shared", "second", "sha256:shared"),
23039            ("shared", "sha256:shared", "shared", "sha256:shared"),
23040            ("first", "sha256:first", "second", "sha256:second"),
23041        ] {
23042            let history = vec![
23043                history_event(
23044                    "ConditionWaitOpened",
23045                    json!({
23046                        "sequence": 3,
23047                        "condition_wait_id": "condition:3",
23048                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23049                        "condition_key": first_key,
23050                        "condition_definition_fingerprint": first_fingerprint,
23051                    }),
23052                ),
23053                history_event(
23054                    "ConditionWaitSatisfied",
23055                    json!({
23056                        "sequence": 3,
23057                        "condition_wait_id": "condition:3",
23058                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23059                        "condition_key": first_key,
23060                        "condition_definition_fingerprint": first_fingerprint,
23061                    }),
23062                ),
23063                history_event(
23064                    "ConditionWaitOpened",
23065                    json!({
23066                        "sequence": 4,
23067                        "condition_wait_id": "condition:4",
23068                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23069                        "condition_key": second_key,
23070                        "condition_definition_fingerprint": second_fingerprint,
23071                    }),
23072                ),
23073                history_event(
23074                    "ConditionWaitSatisfied",
23075                    json!({
23076                        "sequence": 4,
23077                        "condition_wait_id": "condition:4",
23078                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23079                        "condition_key": second_key,
23080                        "condition_definition_fingerprint": second_fingerprint,
23081                    }),
23082                ),
23083            ];
23084            for _cold_worker_or_restart in 0..2 {
23085                let ctx = workflow_context(history.clone());
23086                let mut task_context = TaskContext::from_waker(noop_waker_ref());
23087                let mut first = Box::pin(ctx.wait_condition(
23088                    ConditionWaitOptions::new(first_key, first_fingerprint),
23089                    || Ok(false),
23090                ));
23091                assert!(matches!(
23092                    first.as_mut().poll(&mut task_context),
23093                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23094                ));
23095
23096                let mut second = Box::pin(ctx.wait_condition(
23097                    ConditionWaitOptions::new(second_key, second_fingerprint),
23098                    || Ok(false),
23099                ));
23100                assert!(matches!(
23101                    second.as_mut().poll(&mut task_context),
23102                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23103                ));
23104                assert!(ctx.take_commands().expect("commands").is_empty());
23105                ctx.ensure_history_consumed()
23106                    .expect("each authored wait consumes one occurrence");
23107            }
23108        }
23109    }
23110
23111    #[test]
23112    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
23113        fn worker() -> Worker {
23114            let client = Client::new("http://127.0.0.1:8080").expect("client");
23115            let mut worker = Worker::new(client, "rust-workers");
23116            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
23117                let mut outcomes = Vec::new();
23118                for _ in 0..2 {
23119                    outcomes.push(
23120                        ctx.wait_condition(
23121                            ConditionWaitOptions::new("shared", "sha256:shared"),
23122                            || Ok(false),
23123                        )
23124                        .await?,
23125                    );
23126                }
23127                Ok(json!(outcomes))
23128            });
23129            worker
23130        }
23131
23132        let task = workflow_task(
23133            "rust.condition-loop",
23134            vec![
23135                history_event(
23136                    "ConditionWaitOpened",
23137                    json!({
23138                        "sequence": 1,
23139                        "condition_wait_id": "condition:1",
23140                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23141                        "condition_key": "shared",
23142                        "condition_definition_fingerprint": "sha256:shared",
23143                    }),
23144                ),
23145                history_event(
23146                    "ConditionWaitSatisfied",
23147                    json!({
23148                        "sequence": 1,
23149                        "condition_wait_id": "condition:1",
23150                        "condition_wait_occurrence_id": "rust:condition-wait:0",
23151                        "condition_key": "shared",
23152                        "condition_definition_fingerprint": "sha256:shared",
23153                    }),
23154                ),
23155                history_event(
23156                    "ConditionWaitOpened",
23157                    json!({
23158                        "sequence": 2,
23159                        "condition_wait_id": "condition:2",
23160                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23161                        "condition_key": "shared",
23162                        "condition_definition_fingerprint": "sha256:shared",
23163                    }),
23164                ),
23165                history_event(
23166                    "ConditionWaitSatisfied",
23167                    json!({
23168                        "sequence": 2,
23169                        "condition_wait_id": "condition:2",
23170                        "condition_wait_occurrence_id": "rust:condition-wait:1",
23171                        "condition_key": "shared",
23172                        "condition_definition_fingerprint": "sha256:shared",
23173                    }),
23174                ),
23175            ],
23176            DEFAULT_CODEC,
23177        );
23178
23179        for _cold_worker_or_restart in 0..2 {
23180            let commands = worker()
23181                .execute_workflow_task(task.clone())
23182                .expect("adjacent loop waits replay deterministically");
23183            assert_eq!(commands.len(), 1);
23184            assert_eq!(commands[0]["type"], "complete_workflow");
23185            assert_eq!(
23186                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
23187                json!(["satisfied", "satisfied"])
23188            );
23189        }
23190    }
23191
23192    #[test]
23193    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
23194        let history = vec![history_event(
23195            "ConditionWaitOpened",
23196            json!({
23197                "sequence": 12,
23198                "condition_wait_id": "condition:12",
23199                "condition_wait_occurrence_id": "rust:condition-wait:0",
23200                "condition_key": "approval",
23201                "condition_definition_fingerprint": "sha256:approval-v1",
23202                "timeout_seconds": 30,
23203            }),
23204        )];
23205        for (options, expected_reason) in [
23206            (
23207                ConditionWaitOptions::new("changed", "sha256:approval-v1")
23208                    .timeout(Duration::from_secs(30)),
23209                "condition_wait_key_mismatch",
23210            ),
23211            (
23212                ConditionWaitOptions::new("approval", "sha256:approval-v2")
23213                    .timeout(Duration::from_secs(30)),
23214                "condition_wait_predicate_mismatch",
23215            ),
23216            (
23217                ConditionWaitOptions::new("approval", "sha256:approval-v1")
23218                    .timeout(Duration::from_secs(29)),
23219                "condition_wait_timeout_mismatch",
23220            ),
23221        ] {
23222            let ctx = workflow_context(history.clone());
23223            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
23224            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23225            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23226                wait.as_mut().poll(&mut task_context)
23227            else {
23228                panic!("changed condition definition must fail replay");
23229            };
23230            assert_eq!(failure.reason, expected_reason);
23231            assert_eq!(failure.sequence, Some(12));
23232        }
23233    }
23234
23235    #[test]
23236    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
23237        let error = WorkflowState::new(
23238            vec![history_event(
23239                "ConditionWaitOpened",
23240                json!({
23241                    "sequence": 12,
23242                    "condition_wait_id": "condition:12",
23243                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23244                    "condition_key": "approval",
23245                }),
23246            )],
23247            "rust-workers".to_string(),
23248            DEFAULT_CODEC.to_string(),
23249            None,
23250        )
23251        .expect_err("condition history without a predicate fingerprint must fail");
23252
23253        assert!(matches!(
23254            error,
23255            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23256                if reason == "condition_wait_predicate_fingerprint_missing"
23257        ));
23258    }
23259
23260    #[test]
23261    fn condition_wait_history_requires_authored_occurrence_identity() {
23262        let error = WorkflowState::new(
23263            vec![history_event(
23264                "ConditionWaitOpened",
23265                json!({
23266                    "sequence": 12,
23267                    "condition_wait_id": "condition:12",
23268                    "condition_key": "approval",
23269                    "condition_definition_fingerprint": "sha256:approval-v1",
23270                }),
23271            )],
23272            "rust-workers".to_string(),
23273            DEFAULT_CODEC.to_string(),
23274            None,
23275        )
23276        .expect_err("condition history without occurrence identity must fail");
23277
23278        assert!(matches!(
23279            error,
23280            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23281                if reason == "condition_wait_occurrence_id_missing"
23282        ));
23283    }
23284
23285    #[test]
23286    fn typed_search_attribute_updates_validate_emit_and_replay() {
23287        let update = SearchAttributeUpdate::new()
23288            .keyword("OrderStatus", " waiting ")
23289            .expect("keyword")
23290            .int("Attempt", 3)
23291            .expect("int")
23292            .bool("Escalated", false)
23293            .expect("bool")
23294            .keyword_list("Regions", ["us-east", "eu-west"])
23295            .expect("list")
23296            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
23297            .expect("datetime")
23298            .delete("LegacyStatus")
23299            .expect("delete");
23300        let ctx = workflow_context(Vec::new());
23301        ctx.upsert_search_attributes(update.clone())
23302            .expect("typed update");
23303        assert_eq!(
23304            ctx.take_commands().expect("search-attribute command"),
23305            vec![json!({
23306                "type": "upsert_search_attributes",
23307                "attributes": {
23308                    "Attempt": 3,
23309                    "Escalated": false,
23310                    "LegacyStatus": null,
23311                    "OrderStatus": "waiting",
23312                    "Regions": ["us-east", "eu-west"],
23313                    "UpdatedAt": "2026-08-22T04:00:00Z",
23314                },
23315                "attribute_types": {
23316                    "Attempt": "int",
23317                    "Escalated": "bool",
23318                    "OrderStatus": "keyword",
23319                    "Regions": "keyword_list",
23320                    "UpdatedAt": "datetime",
23321                },
23322            })]
23323        );
23324
23325        let replay = workflow_context(vec![history_event(
23326            "SearchAttributesUpserted",
23327            json!({
23328                "sequence": 6,
23329                "attributes": {
23330                    "Attempt": 3,
23331                    "Escalated": false,
23332                    "LegacyStatus": null,
23333                    "OrderStatus": "waiting",
23334                    "Regions": ["us-east", "eu-west"],
23335                    "UpdatedAt": "2026-08-22T04:00:00Z",
23336                },
23337                "attribute_types": {
23338                    "Attempt": "int",
23339                    "Escalated": "bool",
23340                    "OrderStatus": "keyword",
23341                    "Regions": "keyword_list",
23342                    "UpdatedAt": "datetime",
23343                },
23344                "merged": {},
23345            }),
23346        )]);
23347        replay
23348            .upsert_search_attributes(update)
23349            .expect("matching update replays");
23350        assert!(replay.take_commands().expect("commands").is_empty());
23351        replay.ensure_history_consumed().expect("history consumed");
23352
23353        let type_drift = workflow_context(vec![history_event(
23354            "SearchAttributesUpserted",
23355            json!({
23356                "sequence": 7,
23357                "attributes": {"OrderStatus": "waiting"},
23358                "attribute_types": {"OrderStatus": "keyword"},
23359                "merged": {"OrderStatus": "waiting"},
23360            }),
23361        )]);
23362        let error = type_drift
23363            .upsert_search_attributes(
23364                SearchAttributeUpdate::new()
23365                    .string("OrderStatus", "waiting")
23366                    .expect("string update"),
23367            )
23368            .expect_err("same JSON value with a changed type must fail replay");
23369        assert!(matches!(
23370            error,
23371            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23372                if reason == "search_attribute_type_mismatch"
23373        ));
23374
23375        let malformed_types = WorkflowState::new(
23376            vec![history_event(
23377                "SearchAttributesUpserted",
23378                json!({
23379                    "sequence": 8,
23380                    "attributes": {"OrderStatus": "waiting"},
23381                    "attribute_types": {"OrderStatus": "unsupported"},
23382                    "merged": {"OrderStatus": "waiting"},
23383                }),
23384            )],
23385            "rust-workers".to_string(),
23386            DEFAULT_CODEC.to_string(),
23387            None,
23388        )
23389        .expect_err("unsupported search-attribute type metadata must fail");
23390        assert!(matches!(
23391            malformed_types,
23392            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23393                if reason == "search_attribute_types_malformed"
23394        ));
23395
23396        assert!(matches!(
23397            SearchAttributeUpdate::new().keyword("bad key", "value"),
23398            Err(SearchAttributeUpdateError::InvalidKey(_))
23399        ));
23400        assert!(matches!(
23401            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
23402            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
23403        ));
23404        assert!(matches!(
23405            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
23406            Err(SearchAttributeUpdateError::ValueTooLong { .. })
23407        ));
23408        assert!(matches!(
23409            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
23410            Err(SearchAttributeUpdateError::InvalidDateTime(_))
23411        ));
23412        assert!(matches!(
23413            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
23414            Err(Error::InvalidSearchAttributeUpdate(
23415                SearchAttributeUpdateError::Empty
23416            ))
23417        ));
23418    }
23419
23420    #[test]
23421    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
23422        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
23423        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
23424
23425        assert!(SearchAttributeUpdate::new()
23426            .string("AsciiDescription", ascii)
23427            .is_ok());
23428        assert!(SearchAttributeUpdate::new()
23429            .string("Utf8Description", utf8)
23430            .is_ok());
23431        assert!(matches!(
23432            SearchAttributeUpdate::new().string(
23433                "TooLongDescription",
23434                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
23435            ),
23436            Err(SearchAttributeUpdateError::ValueTooLong {
23437                kind: "string",
23438                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
23439                ..
23440            })
23441        ));
23442    }
23443
23444    #[test]
23445    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
23446        let lone_fire = WorkflowState::new(
23447            vec![history_event(
23448                "TimerFired",
23449                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23450            )],
23451            "rust-workers".to_string(),
23452            DEFAULT_CODEC.to_string(),
23453            None,
23454        )
23455        .expect_err("TimerFired requires TimerScheduled");
23456        assert!(matches!(
23457            lone_fire,
23458            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23459                if reason == "timer_schedule_missing_or_duplicate"
23460        ));
23461
23462        let wrong_identity = WorkflowState::new(
23463            vec![
23464                history_event(
23465                    "TimerScheduled",
23466                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23467                ),
23468                history_event(
23469                    "TimerFired",
23470                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
23471                ),
23472            ],
23473            "rust-workers".to_string(),
23474            DEFAULT_CODEC.to_string(),
23475            None,
23476        )
23477        .expect_err("fire must match scheduled timer identity");
23478        assert!(matches!(
23479            wrong_identity,
23480            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23481                if reason == "timer_identity_mismatch"
23482        ));
23483
23484        let duplicate_fire = WorkflowState::new(
23485            vec![
23486                history_event(
23487                    "TimerScheduled",
23488                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23489                ),
23490                history_event(
23491                    "TimerFired",
23492                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23493                ),
23494                history_event(
23495                    "TimerFired",
23496                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23497                ),
23498            ],
23499            "rust-workers".to_string(),
23500            DEFAULT_CODEC.to_string(),
23501            None,
23502        )
23503        .expect_err("a durable timer cannot fire twice");
23504        assert!(matches!(
23505            duplicate_fire,
23506            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23507                if reason == "duplicate_timer_fire"
23508        ));
23509
23510        let wrong_fired_delay = WorkflowState::new(
23511            vec![
23512                history_event(
23513                    "TimerScheduled",
23514                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23515                ),
23516                history_event(
23517                    "TimerFired",
23518                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
23519                ),
23520            ],
23521            "rust-workers".to_string(),
23522            DEFAULT_CODEC.to_string(),
23523            None,
23524        )
23525        .expect_err("timer schedule and fire delays must agree");
23526        assert!(matches!(
23527            wrong_fired_delay,
23528            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23529                if reason == "timer_history_delay_mismatch"
23530        ));
23531    }
23532
23533    #[test]
23534    fn replay_rejects_activity_moved_before_recorded_timer() {
23535        let ctx = workflow_context(vec![
23536            history_event(
23537                "TimerScheduled",
23538                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23539            ),
23540            history_event(
23541                "TimerFired",
23542                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23543            ),
23544            history_event(
23545                "ActivityCompleted",
23546                json!({
23547                    "sequence": 2,
23548                    "activity_type": "after-timer",
23549                    "payload_codec": DEFAULT_CODEC,
23550                    "result": fixture_envelope(json!("done")),
23551                }),
23552            ),
23553        ]);
23554        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
23555        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23556
23557        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23558            activity.as_mut().poll(&mut task_context)
23559        else {
23560            panic!("reordered durable command must be rejected");
23561        };
23562        assert_eq!(failure.reason, "recorded_command_mismatch");
23563        assert_eq!(failure.sequence, Some(1));
23564        assert_eq!(failure.expected.as_deref(), Some("timer"));
23565        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
23566    }
23567
23568    #[test]
23569    fn workflow_context_emits_a_typed_named_signal_wait() {
23570        let ctx = workflow_context(Vec::new());
23571        let mut signal = Box::pin(ctx.wait_signal("finish"));
23572        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23573
23574        assert!(matches!(
23575            signal.as_mut().poll(&mut task_context),
23576            Poll::Pending
23577        ));
23578        assert_eq!(
23579            ctx.take_commands().expect("signal-wait command"),
23580            vec![json!({
23581                "type": "open_signal_wait",
23582                "signal_name": "finish",
23583            })]
23584        );
23585    }
23586
23587    #[test]
23588    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
23589        let ctx = workflow_context(Vec::new());
23590        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
23591        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23592
23593        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
23594        else {
23595            panic!("runtime-reserved signal should be rejected");
23596        };
23597        assert!(message.contains("reserved by the workflow runtime"));
23598        assert!(ctx.take_commands().expect("commands").is_empty());
23599    }
23600
23601    #[tokio::test]
23602    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
23603        let client = Client::builder("http://127.0.0.1:9")
23604            .build()
23605            .expect("client");
23606        let error = client
23607            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
23608            .await
23609            .expect_err("runtime-reserved signal should be rejected before transport");
23610
23611        assert!(
23612            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
23613        );
23614    }
23615
23616    #[test]
23617    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
23618        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23619            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23620                value.to_string(),
23621            )]))
23622            .expect("message payload");
23623            json!({
23624                "schema": MESSAGE_STREAM_SCHEMA,
23625                "stream_name": "orders",
23626                "message_id": message_id,
23627                "position": position,
23628                "payload_envelope": payload,
23629            })
23630        }
23631
23632        fn opened(sequence: u64) -> HistoryEvent {
23633            history_event(
23634                "SignalWaitOpened",
23635                json!({
23636                    "sequence": sequence,
23637                    "signal_name": MESSAGE_STREAM_SIGNAL,
23638                }),
23639            )
23640        }
23641
23642        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23643            history_event(
23644                "SignalApplied",
23645                json!({
23646                    "sequence": sequence,
23647                    "signal_name": MESSAGE_STREAM_SIGNAL,
23648                    "value": fixture_envelope(json!([delivery])),
23649                }),
23650            )
23651        }
23652
23653        fn received(delivery: Value) -> HistoryEvent {
23654            history_event(
23655                "SignalReceived",
23656                json!({
23657                    "signal_name": MESSAGE_STREAM_SIGNAL,
23658                    "arguments": fixture_envelope(json!([delivery])),
23659                    "payload_codec": DEFAULT_CODEC,
23660                }),
23661            )
23662        }
23663
23664        let client = Client::new("http://127.0.0.1:8080").expect("client");
23665        let mut worker = Worker::new(client, "rust-workers");
23666        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
23667            let messages = ctx.message_stream("orders")?.receive(2).await?;
23668            Ok(json!(messages
23669                .into_iter()
23670                .map(|message| message.message_id)
23671                .collect::<Vec<_>>()))
23672        });
23673
23674        let first = delivery("message-1", 1, "one");
23675        let second = delivery("message-2", 2, "two");
23676        let batch = worker
23677            .execute_workflow_task_decision(workflow_task(
23678                "rust.message-stream-batch",
23679                vec![
23680                    opened(1),
23681                    received(first.clone()),
23682                    applied(1, first.clone()),
23683                    received(first.clone()),
23684                    received(second),
23685                ],
23686                DEFAULT_CODEC,
23687            ))
23688            .expect("worker task consumes the available batch");
23689
23690        assert_eq!(batch.commands.len(), 1);
23691        assert_eq!(batch.commands[0]["type"], "complete_workflow");
23692        assert_eq!(
23693            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
23694                .expect("workflow result"),
23695            json!(["message-1", "message-2"])
23696        );
23697        assert_eq!(
23698            batch.message_stream_cursors,
23699            vec![json!({"stream_name": "orders", "through_position": 2})]
23700        );
23701        assert!(batch.message_stream_waits.is_empty());
23702
23703        let partial = worker
23704            .execute_workflow_task_decision(workflow_task(
23705                "rust.message-stream-batch",
23706                vec![opened(1), received(first.clone()), applied(1, first)],
23707                DEFAULT_CODEC,
23708            ))
23709            .expect("worker task returns without waiting for a missing second item");
23710        assert_eq!(partial.commands.len(), 1);
23711        assert_eq!(partial.commands[0]["type"], "complete_workflow");
23712        assert_eq!(
23713            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
23714                .expect("workflow result"),
23715            json!(["message-1"])
23716        );
23717        assert_eq!(
23718            partial.message_stream_cursors,
23719            vec![json!({"stream_name": "orders", "through_position": 1})]
23720        );
23721        assert!(partial.message_stream_waits.is_empty());
23722    }
23723
23724    #[test]
23725    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
23726        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23727            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23728                value.to_string(),
23729            )]))
23730            .expect("message payload");
23731            json!({
23732                "schema": MESSAGE_STREAM_SCHEMA,
23733                "stream_name": "orders",
23734                "message_id": message_id,
23735                "position": position,
23736                "payload_envelope": payload,
23737            })
23738        }
23739
23740        fn opened(sequence: u64) -> HistoryEvent {
23741            history_event(
23742                "SignalWaitOpened",
23743                json!({
23744                    "sequence": sequence,
23745                    "signal_name": MESSAGE_STREAM_SIGNAL,
23746                }),
23747            )
23748        }
23749
23750        fn received(delivery: Value) -> HistoryEvent {
23751            history_event(
23752                "SignalReceived",
23753                json!({
23754                    "signal_name": MESSAGE_STREAM_SIGNAL,
23755                    "arguments": fixture_envelope(json!([delivery])),
23756                    "payload_codec": DEFAULT_CODEC,
23757                }),
23758            )
23759        }
23760
23761        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23762            history_event(
23763                "SignalApplied",
23764                json!({
23765                    "sequence": sequence,
23766                    "signal_name": MESSAGE_STREAM_SIGNAL,
23767                    "value": fixture_envelope(json!([delivery])),
23768                }),
23769            )
23770        }
23771
23772        let client = Client::new("http://127.0.0.1:8080").expect("client");
23773        let mut worker = Worker::new(client, "rust-workers");
23774        worker.register_workflow(
23775            "rust.message-stream-partial-batches",
23776            |ctx, _input| async move {
23777                let stream = ctx.message_stream("orders")?;
23778                let first = stream.receive(10).await?;
23779                let second = stream.receive(10).await?;
23780                Ok(json!([
23781                    first
23782                        .into_iter()
23783                        .map(|message| message.message_id)
23784                        .collect::<Vec<_>>(),
23785                    second
23786                        .into_iter()
23787                        .map(|message| message.message_id)
23788                        .collect::<Vec<_>>(),
23789                ]))
23790            },
23791        );
23792
23793        let first = delivery("message-1", 1, "one");
23794        let second = delivery("message-2", 2, "two");
23795        let decision = worker
23796            .execute_workflow_task_decision(workflow_task(
23797                "rust.message-stream-partial-batches",
23798                vec![
23799                    opened(1),
23800                    received(first.clone()),
23801                    applied(1, first),
23802                    opened(2),
23803                    received(second.clone()),
23804                    applied(2, second),
23805                ],
23806                DEFAULT_CODEC,
23807            ))
23808            .expect("cold replay preserves both authored receive boundaries");
23809
23810        assert_eq!(decision.commands.len(), 1);
23811        assert_eq!(decision.commands[0]["type"], "complete_workflow");
23812        assert_eq!(
23813            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
23814                .expect("workflow result"),
23815            json!([["message-1"], ["message-2"]])
23816        );
23817        assert_eq!(
23818            decision.message_stream_cursors,
23819            vec![json!({"stream_name": "orders", "through_position": 2})]
23820        );
23821        assert!(decision.message_stream_waits.is_empty());
23822    }
23823
23824    #[test]
23825    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
23826        let ctx = workflow_context(Vec::new());
23827        let stream = ctx.message_stream("orders").expect("message stream");
23828        let mut receive = Box::pin(stream.receive(10));
23829        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23830
23831        assert!(matches!(
23832            receive.as_mut().poll(&mut task_context),
23833            Poll::Pending
23834        ));
23835        assert_eq!(
23836            ctx.take_commands().expect("message-stream wait command"),
23837            vec![json!({
23838                "type": "open_signal_wait",
23839                "signal_name": MESSAGE_STREAM_SIGNAL,
23840            })]
23841        );
23842        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
23843        assert!(cursors.is_empty());
23844        assert_eq!(
23845            waits,
23846            vec![json!({"stream_name": "orders", "after_position": 0})]
23847        );
23848    }
23849
23850    #[test]
23851    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
23852        let ctx = workflow_context(vec![history_event(
23853            "SignalReceived",
23854            json!({
23855                "signal_name": MESSAGE_STREAM_SIGNAL,
23856                "arguments": fixture_envelope(json!([{
23857                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
23858                    "stream_name": "orders",
23859                    "through_position": 2,
23860                }])),
23861                "payload_codec": DEFAULT_CODEC,
23862            }),
23863        )]);
23864        let stream = ctx.message_stream("orders").expect("message stream");
23865        let mut receive = Box::pin(stream.receive(10));
23866        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23867
23868        assert!(matches!(
23869            receive.as_mut().poll(&mut task_context),
23870            Poll::Pending
23871        ));
23872        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
23873        assert_eq!(
23874            cursors,
23875            vec![json!({"stream_name": "orders", "through_position": 2})]
23876        );
23877        assert_eq!(
23878            waits,
23879            vec![json!({"stream_name": "orders", "after_position": 2})]
23880        );
23881    }
23882
23883    #[test]
23884    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
23885        let mut empty_map = BTreeMap::new();
23886        let mut nested = BTreeMap::new();
23887        nested.insert(
23888            "value".to_string(),
23889            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
23890        );
23891        let values = vec![
23892            AvroValue::Bytes(vec![0, 255]),
23893            AvroValue::Long(1),
23894            AvroValue::Double(1.0),
23895            AvroValue::Array(Vec::new()),
23896            AvroValue::Map(std::mem::take(&mut empty_map)),
23897            AvroValue::Map(nested),
23898        ];
23899        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
23900        let transport = vec![json!({
23901            "schema": MESSAGE_STREAM_SCHEMA,
23902            "stream_name": "orders",
23903            "message_id": "message-1",
23904            "position": 1,
23905            "payload_envelope": payload,
23906        })];
23907
23908        for _ in 0..2 {
23909            let Some(MessageStreamDelivery::Message(message)) =
23910                decode_message_stream_delivery(transport.clone()).expect("delivery")
23911            else {
23912                panic!("message delivery expected");
23913            };
23914            assert_eq!(message.arguments, values);
23915            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
23916            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
23917        }
23918    }
23919
23920    #[test]
23921    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
23922        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
23923            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
23924                value.to_string(),
23925            )]))
23926            .expect("message payload");
23927            json!({
23928                "schema": MESSAGE_STREAM_SCHEMA,
23929                "stream_name": "orders",
23930                "message_id": message_id,
23931                "position": position,
23932                "payload_envelope": payload,
23933            })
23934        }
23935
23936        fn opened(sequence: u64) -> HistoryEvent {
23937            history_event(
23938                "SignalWaitOpened",
23939                json!({
23940                    "sequence": sequence,
23941                    "signal_name": MESSAGE_STREAM_SIGNAL,
23942                }),
23943            )
23944        }
23945
23946        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
23947            history_event(
23948                "SignalApplied",
23949                json!({
23950                    "sequence": sequence,
23951                    "signal_name": MESSAGE_STREAM_SIGNAL,
23952                    "value": fixture_envelope(json!([delivery])),
23953                }),
23954            )
23955        }
23956
23957        fn worker() -> Worker {
23958            let client = Client::new("http://127.0.0.1:8080").expect("client");
23959            let mut worker = Worker::new(client, "rust-workers");
23960            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
23961                let stream = ctx.message_stream("orders")?;
23962                let first = stream.receive_one().await?;
23963                let second = stream.receive_one().await?;
23964                Ok(json!([first.message_id, second.message_id]))
23965            });
23966            worker
23967        }
23968
23969        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
23970            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
23971            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
23972            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
23973            task
23974        }
23975
23976        let waiting = worker()
23977            .execute_workflow_task_decision(workflow_task(
23978                "rust.message-stream",
23979                Vec::new(),
23980                DEFAULT_CODEC,
23981            ))
23982            .expect("first worker opens the stream wait");
23983        assert_eq!(
23984            waiting.commands,
23985            vec![json!({
23986                "type": "open_signal_wait",
23987                "signal_name": MESSAGE_STREAM_SIGNAL,
23988            })]
23989        );
23990        assert!(waiting.message_stream_cursors.is_empty());
23991        assert_eq!(
23992            waiting.message_stream_waits,
23993            vec![json!({"stream_name": "orders", "after_position": 0})]
23994        );
23995
23996        let first_delivery = delivery("message-1", 1, "one");
23997        let first_arrival = worker()
23998            .execute_workflow_task_decision(task_with_resume(
23999                vec![opened(1)],
24000                first_delivery.clone(),
24001            ))
24002            .expect("replacement worker consumes the first arrival");
24003        assert_eq!(
24004            first_arrival.commands,
24005            vec![json!({
24006                "type": "open_signal_wait",
24007                "signal_name": MESSAGE_STREAM_SIGNAL,
24008            })]
24009        );
24010        assert_eq!(
24011            first_arrival.message_stream_cursors,
24012            vec![json!({"stream_name": "orders", "through_position": 1})]
24013        );
24014        assert_eq!(
24015            first_arrival.message_stream_waits,
24016            vec![json!({"stream_name": "orders", "after_position": 1})]
24017        );
24018
24019        let second_delivery = delivery("message-2", 2, "two");
24020        let first_applied = applied(1, first_delivery);
24021        let completed = worker()
24022            .execute_workflow_task_decision(task_with_resume(
24023                vec![opened(1), first_applied.clone(), opened(2)],
24024                second_delivery.clone(),
24025            ))
24026            .expect("next replacement worker consumes the second arrival");
24027        assert_eq!(completed.commands.len(), 1);
24028        assert_eq!(completed.commands[0]["type"], "complete_workflow");
24029        assert_eq!(
24030            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
24031                .expect("workflow result"),
24032            json!(["message-1", "message-2"])
24033        );
24034        assert_eq!(
24035            completed.message_stream_cursors,
24036            vec![json!({"stream_name": "orders", "through_position": 2})]
24037        );
24038        assert!(completed.message_stream_waits.is_empty());
24039
24040        let replay_history = vec![
24041            opened(1),
24042            first_applied,
24043            opened(2),
24044            applied(2, second_delivery),
24045        ];
24046        for _cold_worker_or_restart in 0..2 {
24047            let replayed = worker()
24048                .execute_workflow_task_decision(workflow_task(
24049                    "rust.message-stream",
24050                    replay_history.clone(),
24051                    DEFAULT_CODEC,
24052                ))
24053                .expect("cold worker replays each logical message exactly once");
24054            assert_eq!(replayed.commands.len(), 1);
24055            assert_eq!(
24056                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
24057                    .expect("replayed workflow result"),
24058                json!(["message-1", "message-2"])
24059            );
24060            assert_eq!(
24061                replayed.message_stream_cursors,
24062                vec![json!({"stream_name": "orders", "through_position": 2})]
24063            );
24064            assert!(replayed.message_stream_waits.is_empty());
24065        }
24066    }
24067
24068    #[test]
24069    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
24070        assert!(!worker_protocol_supports_message_streams("1.14"));
24071        assert!(worker_protocol_supports_message_streams("1.15"));
24072        assert!(worker_protocol_supports_message_streams("1.16"));
24073        assert!(worker_protocol_supports_message_streams(
24074            WORKER_PROTOCOL_VERSION
24075        ));
24076        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
24077    }
24078
24079    #[test]
24080    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
24081        let ctx = workflow_context(vec![
24082            history_event(
24083                "ConditionWaitOpened",
24084                json!({
24085                    "sequence": 1,
24086                    "condition_wait_id": "condition:1",
24087                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24088                    "condition_key": "signal:finish",
24089                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24090                }),
24091            ),
24092            history_event(
24093                "ConditionWaitSatisfied",
24094                json!({
24095                    "sequence": 1,
24096                    "condition_wait_id": "condition:1",
24097                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24098                    "condition_key": "signal:finish",
24099                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
24100                }),
24101            ),
24102            history_event(
24103                "SignalReceived",
24104                json!({"signal_name": "finish", "arguments": []}),
24105            ),
24106        ]);
24107        let mut signal = Box::pin(ctx.wait_signal("finish"));
24108        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24109
24110        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24111            signal.as_mut().poll(&mut task_context)
24112        else {
24113            panic!("condition history must not resolve as a typed signal wait");
24114        };
24115        assert_eq!(failure.reason, "recorded_command_mismatch");
24116        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
24117    }
24118
24119    #[test]
24120    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
24121        let signal_then_timer = vec![
24122            history_event(
24123                "SignalWaitOpened",
24124                json!({"sequence": 1, "signal_name": "go"}),
24125            ),
24126            history_event(
24127                "SignalApplied",
24128                json!({
24129                    "sequence": 1,
24130                    "signal_name": "go",
24131                    "value": fixture_envelope(json!(["now"])),
24132                }),
24133            ),
24134            history_event(
24135                "TimerScheduled",
24136                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24137            ),
24138            history_event(
24139                "TimerFired",
24140                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
24141            ),
24142        ];
24143
24144        let ctx = workflow_context(signal_then_timer.clone());
24145        let mut signal = Box::pin(ctx.wait_signal("go"));
24146        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24147        assert!(matches!(
24148            signal.as_mut().poll(&mut task_context),
24149            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
24150        ));
24151        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
24152        assert!(matches!(
24153            timer.as_mut().poll(&mut task_context),
24154            Poll::Ready(Ok(()))
24155        ));
24156        ctx.ensure_history_consumed()
24157            .expect("signal and timer history consumed in order");
24158
24159        let reordered = workflow_context(signal_then_timer);
24160        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
24161        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24162            timer_first.as_mut().poll(&mut task_context)
24163        else {
24164            panic!("timer cannot consume signal-wait-first history");
24165        };
24166        assert_eq!(failure.reason, "recorded_command_mismatch");
24167        assert_eq!(failure.sequence, Some(1));
24168        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
24169
24170        let timer_then_signal = vec![
24171            history_event(
24172                "TimerScheduled",
24173                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24174            ),
24175            history_event(
24176                "TimerFired",
24177                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24178            ),
24179            history_event(
24180                "SignalWaitOpened",
24181                json!({"sequence": 2, "signal_name": "go"}),
24182            ),
24183            history_event(
24184                "SignalApplied",
24185                json!({
24186                    "sequence": 2,
24187                    "signal_name": "go",
24188                    "value": fixture_envelope(json!([])),
24189                }),
24190            ),
24191        ];
24192        let reordered = workflow_context(timer_then_signal);
24193        let mut signal_first = Box::pin(reordered.wait_signal("go"));
24194        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24195            signal_first.as_mut().poll(&mut task_context)
24196        else {
24197            panic!("signal wait cannot consume timer-first history");
24198        };
24199        assert_eq!(failure.reason, "recorded_command_mismatch");
24200        assert_eq!(failure.sequence, Some(1));
24201        assert_eq!(failure.expected.as_deref(), Some("timer"));
24202    }
24203
24204    #[test]
24205    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
24206        let duplicate_timer = WorkflowState::new(
24207            vec![
24208                history_event(
24209                    "TimerScheduled",
24210                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24211                ),
24212                history_event(
24213                    "TimerScheduled",
24214                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24215                ),
24216            ],
24217            "rust-workers".to_string(),
24218            DEFAULT_CODEC.to_string(),
24219            None,
24220        )
24221        .expect_err("one workflow sequence cannot schedule two timers");
24222        assert!(matches!(
24223            duplicate_timer,
24224            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24225                if reason == "timer_schedule_missing_or_duplicate"
24226        ));
24227
24228        let colliding_kinds = WorkflowState::new(
24229            vec![
24230                history_event(
24231                    "TimerScheduled",
24232                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24233                ),
24234                history_event(
24235                    "ActivityCompleted",
24236                    json!({"sequence": 1, "activity_type": "same-sequence"}),
24237                ),
24238            ],
24239            "rust-workers".to_string(),
24240            DEFAULT_CODEC.to_string(),
24241            None,
24242        )
24243        .expect_err("one workflow sequence cannot identify two command kinds");
24244        assert!(matches!(
24245            colliding_kinds,
24246            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24247                if reason == "durable_command_sequence_collision"
24248        ));
24249
24250        let duplicate_signal_wait = WorkflowState::new(
24251            vec![
24252                history_event(
24253                    "SignalWaitOpened",
24254                    json!({"sequence": 1, "signal_name": "go"}),
24255                ),
24256                history_event(
24257                    "SignalWaitOpened",
24258                    json!({"sequence": 1, "signal_name": "go"}),
24259                ),
24260            ],
24261            "rust-workers".to_string(),
24262            DEFAULT_CODEC.to_string(),
24263            None,
24264        )
24265        .expect_err("one workflow sequence cannot open two signal waits");
24266        assert!(matches!(
24267            duplicate_signal_wait,
24268            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24269                if reason == "signal_wait_open_missing_or_duplicate"
24270        ));
24271    }
24272
24273    #[test]
24274    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
24275        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
24276            .expect("side-effect result");
24277        let ctx = workflow_context(vec![history_event(
24278            "SideEffectRecorded",
24279            json!({"sequence": 99, "result": result}),
24280        )]);
24281
24282        let replayed: Value = ctx
24283            .side_effect(|| panic!("recorded side effect must not run"))
24284            .expect("positive global workflow sequence is valid");
24285        assert_eq!(replayed, json!({"captured": true}));
24286        ctx.ensure_history_consumed().expect("history consumed");
24287    }
24288
24289    #[test]
24290    fn workflow_history_rejects_zero_and_descending_command_sequences() {
24291        let result =
24292            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
24293        let zero = WorkflowState::new(
24294            vec![history_event(
24295                "SideEffectRecorded",
24296                json!({"sequence": 0, "result": result.clone()}),
24297            )],
24298            "rust-workers".to_string(),
24299            DEFAULT_CODEC.to_string(),
24300            None,
24301        )
24302        .expect_err("durable command sequences must be positive");
24303        assert!(matches!(
24304            zero,
24305            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24306                if reason == "durable_command_sequence_invalid"
24307        ));
24308
24309        let descending = WorkflowState::new(
24310            vec![
24311                history_event(
24312                    "SideEffectRecorded",
24313                    json!({"sequence": 3, "result": result}),
24314                ),
24315                history_event(
24316                    "VersionMarkerRecorded",
24317                    json!({
24318                        "sequence": 2,
24319                        "change_id": "descending-marker",
24320                        "version": 1,
24321                        "min_supported": 1,
24322                        "max_supported": 1,
24323                    }),
24324                ),
24325            ],
24326            "rust-workers".to_string(),
24327            DEFAULT_CODEC.to_string(),
24328            None,
24329        )
24330        .expect_err("new durable commands must remain strictly ordered");
24331        let Error::NonDeterministicReplay(failure) = descending else {
24332            panic!("expected typed replay failure");
24333        };
24334        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
24335        assert_eq!(failure.sequence, Some(2));
24336        assert_eq!(
24337            failure.expected.as_deref(),
24338            Some("workflow sequence greater than 3")
24339        );
24340        assert_eq!(failure.actual.as_deref(), Some("2"));
24341    }
24342
24343    #[test]
24344    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
24345        fn worker() -> Worker {
24346            let client = Client::new("http://127.0.0.1:8080").expect("client");
24347            let mut worker = Worker::new(client, "rust-workers");
24348            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
24349                ctx.wait_signal("finish").await?;
24350                let marker: String =
24351                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
24352                assert_eq!(marker, "after-finish");
24353                Ok(json!("finished"))
24354            });
24355            worker
24356        }
24357
24358        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
24359            .expect("side-effect result");
24360        let task = workflow_task(
24361            "rust.finish-after-gaps",
24362            vec![
24363                history_event(
24364                    "SignalWaitOpened",
24365                    json!({"sequence": 1, "signal_name": "finish"}),
24366                ),
24367                history_event(
24368                    "SignalReceived",
24369                    json!({
24370                        "signal_id": "increment-3",
24371                        "signal_name": "increment",
24372                        "workflow_sequence": 2,
24373                        "payload_codec": DEFAULT_CODEC,
24374                        "arguments": fixture_envelope(json!([3])),
24375                    }),
24376                ),
24377                history_event(
24378                    "SignalReceived",
24379                    json!({
24380                        "signal_id": "increment-5",
24381                        "signal_name": "increment",
24382                        "workflow_sequence": 3,
24383                        "payload_codec": DEFAULT_CODEC,
24384                        "arguments": fixture_envelope(json!([5])),
24385                    }),
24386                ),
24387                history_event(
24388                    "SignalReceived",
24389                    json!({
24390                        "signal_id": "finish",
24391                        "signal_name": "finish",
24392                        "workflow_sequence": 4,
24393                        "payload_codec": DEFAULT_CODEC,
24394                        "arguments": fixture_envelope(json!([])),
24395                    }),
24396                ),
24397                history_event(
24398                    "SignalApplied",
24399                    json!({
24400                        "sequence": 1,
24401                        "signal_id": "finish",
24402                        "signal_name": "finish",
24403                        "payload_codec": DEFAULT_CODEC,
24404                        "value": fixture_envelope(json!([])),
24405                    }),
24406                ),
24407                history_event(
24408                    "SideEffectRecorded",
24409                    json!({"sequence": 5, "result": marker}),
24410                ),
24411            ],
24412            DEFAULT_CODEC,
24413        );
24414
24415        for _original_or_cold_worker in 0..2 {
24416            let commands = worker()
24417                .execute_workflow_task(task.clone())
24418                .expect("signal gaps preserve deterministic replay");
24419            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
24420            assert_eq!(commands[0]["type"], "complete_workflow");
24421            assert_eq!(
24422                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24423                json!("finished")
24424            );
24425        }
24426    }
24427
24428    #[test]
24429    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
24430        let ctx = workflow_context(Vec::new());
24431        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
24432        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24433        assert!(matches!(
24434            sleep.as_mut().poll(&mut task_context),
24435            Poll::Ready(Err(Error::TimerDurationOverflow))
24436        ));
24437        assert!(ctx.take_commands().expect("commands").is_empty());
24438    }
24439
24440    #[test]
24441    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
24442        let entries = AvroValue::Map(BTreeMap::from([
24443            ("text".to_string(), AvroValue::String("same".to_string())),
24444            (
24445                "nested".to_string(),
24446                AvroValue::Map(BTreeMap::from([
24447                    ("beta".to_string(), AvroValue::Long(2)),
24448                    ("alpha".to_string(), AvroValue::Long(1)),
24449                ])),
24450            ),
24451            ("long".to_string(), AvroValue::Long(7)),
24452            ("double".to_string(), AvroValue::Double(7.0)),
24453            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
24454        ]));
24455        let ctx = workflow_context(Vec::new());
24456        ctx.upsert_memo(entries.clone()).expect("valid memo update");
24457        let commands = ctx.take_commands().expect("commands");
24458
24459        assert_eq!(commands.len(), 1);
24460        assert_eq!(commands[0]["type"], "upsert_memo");
24461        let server_entries = json!({
24462            "codec": "avro",
24463            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
24464        });
24465        assert_eq!(
24466            commands[0]["entries"]
24467                .as_object()
24468                .expect("entries envelope")
24469                .keys()
24470                .collect::<Vec<_>>(),
24471            vec!["blob", "codec"]
24472        );
24473        assert_eq!(commands[0]["entries"], server_entries);
24474        let wire_entries =
24475            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
24476        assert_eq!(wire_entries, entries);
24477
24478        let history = vec![history_event(
24479            "MemoUpserted",
24480            json!({
24481                "sequence": 1,
24482                "entries": server_entries.clone(),
24483                "merged": server_entries,
24484            }),
24485        )];
24486        let replay = workflow_context(history.clone());
24487        replay
24488            .upsert_memo(entries.clone())
24489            .expect("matching replay identity");
24490        assert!(replay.take_commands().expect("replay commands").is_empty());
24491
24492        let changed_types = AvroValue::Map(BTreeMap::from([
24493            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
24494            (
24495                "nested".to_string(),
24496                AvroValue::Map(BTreeMap::from([
24497                    ("alpha".to_string(), AvroValue::Long(1)),
24498                    ("beta".to_string(), AvroValue::Long(2)),
24499                ])),
24500            ),
24501            ("long".to_string(), AvroValue::Double(7.0)),
24502            ("double".to_string(), AvroValue::Long(7)),
24503            ("binary".to_string(), AvroValue::String("same".to_string())),
24504        ]));
24505        let error = workflow_context(history)
24506            .upsert_memo(changed_types)
24507            .expect_err("memo replay identity must preserve Avro value types");
24508        assert!(matches!(
24509            error,
24510            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24511        ));
24512    }
24513
24514    #[test]
24515    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
24516        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
24517            .expect("memo envelope");
24518        let replay = workflow_context(vec![history_event(
24519            "MemoUpserted",
24520            json!({
24521                "sequence": 1,
24522                "entries": original.clone(),
24523                "merged": original
24524            }),
24525        )]);
24526        let error = replay
24527            .upsert_memo(json!({"stage": "changed"}))
24528            .expect_err("changed memo update must fail replay");
24529        assert!(matches!(
24530            error,
24531            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24532        ));
24533
24534        let invalid = workflow_context(Vec::new())
24535            .upsert_memo(
24536                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
24537            )
24538            .expect_err("oversized key");
24539        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
24540    }
24541
24542    #[test]
24543    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
24544        let negative_zero = AvroValue::Map(BTreeMap::from([(
24545            "reading".to_string(),
24546            AvroValue::Double(-0.0),
24547        )]));
24548        let negative_zero_envelope =
24549            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
24550        let history = vec![history_event(
24551            "MemoUpserted",
24552            json!({
24553                "sequence": 1,
24554                "entries": negative_zero_envelope.clone(),
24555                "merged": negative_zero_envelope,
24556            }),
24557        )];
24558
24559        workflow_context(history.clone())
24560            .upsert_memo(negative_zero)
24561            .expect("matching negative-zero history identity");
24562
24563        let error = workflow_context(history)
24564            .upsert_memo(AvroValue::Map(BTreeMap::from([(
24565                "reading".to_string(),
24566                AvroValue::Double(0.0),
24567            )])))
24568            .expect_err("positive zero must not consume negative-zero memo history");
24569        assert!(matches!(
24570            error,
24571            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
24572        ));
24573    }
24574
24575    #[test]
24576    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
24577        let supported = json!({
24578            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
24579            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
24580        });
24581        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
24582        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
24583            "workflow_memo_updates": {"supported": false},
24584            "supported_workflow_task_commands": ["upsert_memo"]
24585        }))));
24586        assert!(commands_use_workflow_memo_updates(&[json!({
24587            "type": "upsert_memo",
24588            "entries": {"stage": "processing"}
24589        })]));
24590    }
24591
24592    #[test]
24593    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
24594        let client = Client::new("http://127.0.0.1:8080").expect("client");
24595        let mut worker = Worker::new(client, "rust-workers");
24596        worker.register_workflow("rust.timer", |ctx, _input| async move {
24597            ctx.sleep(Duration::from_secs(5)).await?;
24598            ctx.activity("after-timer", json!([])).await
24599        });
24600
24601        let task = |history_events| WorkflowTask {
24602            task_id: "wft-rust-timer-1".to_string(),
24603            workflow_command_id: None,
24604            workflow_id: Some("wf-rust-timer".to_string()),
24605            run_id: Some("run-rust-timer".to_string()),
24606            workflow_type: "rust.timer".to_string(),
24607            cancel_requested: false,
24608            payload_codec: DEFAULT_CODEC.to_string(),
24609            arguments: Some(
24610                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
24611            ),
24612            history_events,
24613            total_history_events: None,
24614            history_size_bytes: None,
24615            continue_as_new_recommended: None,
24616            history_budget_pressure: None,
24617            next_history_page_token: None,
24618            workflow_task_attempt: 1,
24619            workflow_signal_id: None,
24620            signal_name: None,
24621            signal_arguments: None,
24622            workflow_update_id: None,
24623            update_name: None,
24624            lease_owner: Some("rust-worker".to_string()),
24625        };
24626
24627        let initial = worker
24628            .execute_workflow_task(task(Vec::new()))
24629            .expect("initial timer task");
24630        assert_eq!(
24631            initial,
24632            vec![json!({"type": "start_timer", "delay_seconds": 5})]
24633        );
24634
24635        let activity_result =
24636            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
24637        let replayed = worker
24638            .execute_workflow_task(task(vec![
24639                history_event(
24640                    "TimerScheduled",
24641                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24642                ),
24643                history_event(
24644                    "TimerFired",
24645                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24646                ),
24647                history_event(
24648                    "ActivityCompleted",
24649                    json!({
24650                        "sequence": 2,
24651                        "activity_type": "after-timer",
24652                        "payload_codec": DEFAULT_CODEC,
24653                        "result": activity_result,
24654                    }),
24655                ),
24656            ]))
24657            .expect("replayed workflow task");
24658        assert_eq!(replayed.len(), 1);
24659        assert_eq!(replayed[0]["type"], "complete_workflow");
24660        assert_eq!(
24661            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
24662            json!("done")
24663        );
24664    }
24665
24666    #[test]
24667    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
24668        let client = Client::new("http://127.0.0.1:8080").expect("client");
24669        let mut worker = Worker::new(client, "rust-workers");
24670        worker.register_workflow("rust.continue", |ctx, _input| async move {
24671            ctx.continue_as_new_with_options(
24672                ContinueAsNewOptions::new()
24673                    .workflow_type("rust.next")
24674                    .task_queue("next-workers"),
24675                json!([2, {"cursor": "next"}]),
24676            )
24677        });
24678
24679        let commands = worker
24680            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
24681            .expect("continue-as-new command");
24682
24683        assert_eq!(commands.len(), 1);
24684        assert_eq!(commands[0]["type"], "continue_as_new");
24685        assert_eq!(commands[0]["workflow_type"], "rust.next");
24686        assert_eq!(commands[0]["queue"], "next-workers");
24687        assert_eq!(
24688            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
24689                .expect("continue-as-new arguments"),
24690            json!([2, {"cursor": "next"}])
24691        );
24692    }
24693
24694    #[test]
24695    fn continue_as_new_preserves_typed_arguments() {
24696        let client = Client::new("http://127.0.0.1:8080").expect("client");
24697        let mut worker = Worker::new(client, "rust-workers");
24698        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
24699            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
24700            unreachable!("continue-as-new returns a control-flow error")
24701        });
24702
24703        let commands = worker
24704            .execute_workflow_task(workflow_task(
24705                "rust.typed-continue",
24706                Vec::new(),
24707                DEFAULT_CODEC,
24708            ))
24709            .expect("typed continue-as-new command");
24710
24711        assert_eq!(commands[0]["type"], "continue_as_new");
24712        assert_eq!(
24713            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
24714                .expect("typed continue arguments"),
24715            AvroValue::Array(vec![typed_fidelity_probe()])
24716        );
24717    }
24718
24719    #[test]
24720    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
24721        let client = Client::new("http://127.0.0.1:8080").expect("client");
24722        let mut worker = Worker::new(client, "rust-workers");
24723        worker.register_workflow("rust.continue", |ctx, _input| async move {
24724            ctx.continue_as_new(json!([2]))
24725        });
24726        let task = workflow_task(
24727            "rust.continue",
24728            vec![history_event(
24729                "WorkflowContinuedAsNew",
24730                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
24731            )],
24732            DEFAULT_CODEC,
24733        );
24734
24735        for _worker_restart_or_redelivery in 0..2 {
24736            let commands = worker
24737                .execute_workflow_task(task.clone())
24738                .expect("recorded transition replays");
24739            assert!(
24740                commands.is_empty(),
24741                "replay must not emit another successor"
24742            );
24743        }
24744    }
24745
24746    #[test]
24747    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
24748        let ctx = workflow_context(Vec::new());
24749        let error = ctx
24750            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
24751            .expect_err("blank queue must be rejected");
24752
24753        let Error::InvalidContinueAsNewOptions(error) = error else {
24754            panic!("expected typed continue-as-new validation error");
24755        };
24756        assert_eq!(error.field, "task_queue");
24757        assert!(ctx.take_commands().expect("commands").is_empty());
24758    }
24759
24760    #[test]
24761    fn workflow_context_exposes_server_history_budget() {
24762        let client = Client::new("http://127.0.0.1:8080").expect("client");
24763        let mut worker = Worker::new(client, "rust-workers");
24764        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
24765            let budget = ctx.history_budget()?;
24766            Ok(json!({
24767                "events": budget.event_count,
24768                "bytes": budget.size_bytes,
24769                "recommended": budget.continue_as_new_recommended,
24770                "pressure": budget.pressure,
24771            }))
24772        });
24773        let task: WorkflowTask = serde_json::from_value(json!({
24774            "task_id": "task-history-budget",
24775            "workflow_type": "rust.history-budget",
24776            "payload_codec": DEFAULT_CODEC,
24777            "history_events": [],
24778            "total_history_events": 480,
24779            "history_size_bytes": 1_048_576,
24780            "continue_as_new_recommended": true,
24781            "history_budget_pressure": "continue_as_new_recommended",
24782        }))
24783        .expect("published workflow task");
24784
24785        let commands = worker
24786            .execute_workflow_task(task)
24787            .expect("history-budget workflow");
24788        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
24789        assert_eq!(result["events"], 480);
24790        assert_eq!(result["bytes"], 1_048_576);
24791        assert_eq!(result["recommended"], true);
24792        assert_eq!(result["pressure"], "continue_as_new_recommended");
24793    }
24794
24795    #[test]
24796    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
24797        let client = Client::new("http://127.0.0.1:8080").expect("client");
24798        let mut worker = Worker::new(client, "rust-workers");
24799        worker.register_workflow("rust.failing", |_ctx, _input| async move {
24800            Err(Error::Codec("rust_conformance_failure".to_string()))
24801        });
24802        let task = WorkflowTask {
24803            task_id: "wft-rust-failing-1".to_string(),
24804            workflow_command_id: None,
24805            workflow_id: Some("wf-rust-failing".to_string()),
24806            run_id: Some("run-rust-failing".to_string()),
24807            workflow_type: "rust.failing".to_string(),
24808            cancel_requested: false,
24809            payload_codec: DEFAULT_CODEC.to_string(),
24810            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
24811            history_events: Vec::new(),
24812            total_history_events: Some(0),
24813            history_size_bytes: None,
24814            continue_as_new_recommended: None,
24815            history_budget_pressure: None,
24816            next_history_page_token: None,
24817            workflow_task_attempt: 1,
24818            workflow_signal_id: None,
24819            signal_name: None,
24820            signal_arguments: None,
24821            workflow_update_id: None,
24822            update_name: None,
24823            lease_owner: Some("rust-worker".to_string()),
24824        };
24825
24826        let commands = worker
24827            .execute_workflow_task(task)
24828            .expect("handler failure becomes a workflow command");
24829
24830        assert_eq!(commands.len(), 1);
24831        assert_eq!(commands[0]["type"], "fail_workflow");
24832        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
24833        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
24834        assert_eq!(commands[0]["non_retryable"], false);
24835        assert_eq!(
24836            commands[0]["message"],
24837            "codec error: rust_conformance_failure"
24838        );
24839        assert_eq!(
24840            commands[0]["exception"]["message"],
24841            "codec error: rust_conformance_failure"
24842        );
24843    }
24844
24845    #[test]
24846    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
24847        let client = Client::new("http://127.0.0.1:8080").expect("client");
24848        let mut worker = Worker::new(client, "rust-workers");
24849        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
24850            let _: String = ctx.side_effect(|| "captured".to_string())?;
24851            Err(Error::WorkerLoop("application failure".to_string()))
24852        });
24853
24854        let commands = worker
24855            .execute_workflow_task(workflow_task(
24856                "rust.failing-after-side-effect",
24857                Vec::new(),
24858                DEFAULT_CODEC,
24859            ))
24860            .expect("ordinary failure remains a workflow decision");
24861
24862        assert_eq!(commands.len(), 2);
24863        assert_eq!(commands[0]["type"], "record_side_effect");
24864        assert_eq!(commands[1]["type"], "fail_workflow");
24865    }
24866
24867    #[test]
24868    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
24869        let client = Client::new("http://127.0.0.1:8080").expect("client");
24870        let mut worker = Worker::new(client, "rust-workers");
24871        worker.register_workflow("rust.redrive", |ctx, _input| async move {
24872            ctx.activity("greet", json!([])).await?;
24873            Ok(Value::Null)
24874        });
24875        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
24876            match ctx.activity("greet", json!([])).await {
24877                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
24878                result => result,
24879            }
24880        });
24881
24882        let failed = history_event(
24883            "ActivityFailed",
24884            json!({
24885                "sequence": 1,
24886                "activity_type": "greet",
24887                "activity_execution_id": "activity-1",
24888                "message": "failed"
24889            }),
24890        );
24891        let commands = worker
24892            .execute_workflow_task(workflow_task(
24893                "rust.redrive",
24894                vec![failed.clone()],
24895                DEFAULT_CODEC,
24896            ))
24897            .expect("recorded failure becomes a workflow command");
24898        assert_eq!(commands[0]["type"], "fail_workflow");
24899        assert_eq!(commands[0]["failed_step_sequence"], 1);
24900        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
24901
24902        let translated = worker
24903            .execute_workflow_task(workflow_task(
24904                "rust.redrive-translated",
24905                vec![failed],
24906                DEFAULT_CODEC,
24907            ))
24908            .expect("translated failure becomes a workflow command");
24909        assert_eq!(translated[0]["type"], "fail_workflow");
24910        assert!(translated[0].get("failed_step_sequence").is_none());
24911        assert!(translated[0].get("failed_activity_execution_id").is_none());
24912
24913        let without_identity = worker
24914            .execute_workflow_task(workflow_task(
24915                "rust.redrive",
24916                vec![history_event(
24917                    "ActivityFailed",
24918                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
24919                )],
24920                DEFAULT_CODEC,
24921            ))
24922            .expect("incomplete identity still fails the workflow");
24923        assert!(without_identity[0].get("failed_step_sequence").is_none());
24924
24925        let timed_out = worker
24926            .execute_workflow_task(workflow_task(
24927                "rust.redrive",
24928                vec![history_event(
24929                    "ActivityTimedOut",
24930                    json!({
24931                        "sequence": 1,
24932                        "activity_type": "greet",
24933                        "activity_execution_id": "activity-timeout",
24934                    }),
24935                )],
24936                DEFAULT_CODEC,
24937            ))
24938            .expect("timeout still fails the workflow");
24939        assert!(timed_out[0].get("failed_step_sequence").is_none());
24940    }
24941
24942    #[test]
24943    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
24944        let client = Client::new("http://127.0.0.1:8080").expect("client");
24945        let mut worker = Worker::new(client, "rust-workers");
24946        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
24947            let first = ctx.activity("first", json!([])).await?;
24948            let second = ctx.activity("second", json!([first.clone()])).await?;
24949            Ok(json!({"first": first, "second": second}))
24950        });
24951        let first = history_event(
24952            "ActivityCompleted",
24953            json!({
24954                "sequence": 1,
24955                "activity_type": "first",
24956                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
24957                "payload_codec": DEFAULT_CODEC,
24958                "reused_from_run_id": "failed-run",
24959                "reused_activity_execution_id": "original-first",
24960            }),
24961        );
24962
24963        let retry = worker
24964            .execute_workflow_task(workflow_task(
24965                "rust.redrive-successor",
24966                vec![first.clone()],
24967                DEFAULT_CODEC,
24968            ))
24969            .expect("reused result replays before failed step");
24970        assert_eq!(retry.len(), 1);
24971        assert_eq!(retry[0]["type"], "schedule_activity");
24972        assert_eq!(retry[0]["activity_type"], "second");
24973        assert_eq!(
24974            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
24975            json!(["recorded"]),
24976        );
24977
24978        let second = history_event(
24979            "ActivityCompleted",
24980            json!({
24981                "sequence": 2,
24982                "activity_type": "second",
24983                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
24984                "payload_codec": DEFAULT_CODEC,
24985            }),
24986        );
24987        let completed = worker
24988            .execute_workflow_task(workflow_task(
24989                "rust.redrive-successor",
24990                vec![first, second],
24991                DEFAULT_CODEC,
24992            ))
24993            .expect("retried step completes the successor");
24994        assert_eq!(completed.len(), 1);
24995        assert_eq!(completed[0]["type"], "complete_workflow");
24996        assert_eq!(
24997            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
24998            json!({"first": "recorded", "second": "retried"}),
24999        );
25000    }
25001
25002    #[test]
25003    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
25004        let client = Client::new("http://127.0.0.1:8080").expect("client");
25005        let mut worker = Worker::new(client, "rust-workers");
25006        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
25007            Err(Error::WorkerLoop("application failure".to_string()))
25008        });
25009        let result =
25010            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
25011
25012        let error = worker
25013            .execute_workflow_task(workflow_task(
25014                "rust.removed-side-effect",
25015                vec![history_event(
25016                    "SideEffectRecorded",
25017                    json!({"sequence": 1, "result": result}),
25018                )],
25019                DEFAULT_CODEC,
25020            ))
25021            .expect_err("removed committed history must not become fail_workflow");
25022
25023        let Error::NonDeterministicReplay(failure) = error else {
25024            panic!("expected typed replay failure");
25025        };
25026        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25027        assert_eq!(failure.sequence, Some(1));
25028        assert_eq!(failure.expected.as_deref(), Some("side effect"));
25029    }
25030
25031    #[test]
25032    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
25033        let client = Client::new("http://127.0.0.1:8080").expect("client");
25034        let mut worker = Worker::new(client, "rust-workers");
25035        worker.register_workflow(
25036            "rust.side-effect-before-marker-error",
25037            |ctx, _input| async move {
25038                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
25039                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
25040                ctx.get_version("restart-safe", 2, 2)?;
25041                Ok(Value::Null)
25042            },
25043        );
25044
25045        let error = worker
25046            .execute_workflow_task(workflow_task(
25047                "rust.side-effect-before-marker-error",
25048                vec![history_event(
25049                    "VersionMarkerRecorded",
25050                    json!({
25051                        "sequence": 1,
25052                        "change_id": "restart-safe",
25053                        "version": 1,
25054                        "min_supported": 1,
25055                        "max_supported": 1,
25056                    }),
25057                )],
25058                DEFAULT_CODEC,
25059            ))
25060            .expect_err("replay error must return no queued workflow commands");
25061
25062        let Error::NonDeterministicReplay(failure) = error else {
25063            panic!("expected typed replay failure");
25064        };
25065        assert_eq!(failure.reason, "version_marker_incompatible_range");
25066        assert_eq!(failure.sequence, Some(1));
25067    }
25068
25069    #[test]
25070    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
25071        let client = Client::new("http://127.0.0.1:8080").expect("client");
25072        let mut worker = Worker::new(client, "rust-workers");
25073        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
25074            ctx.sleep(Duration::from_secs(5)).await?;
25075            Ok(json!({"status": "timer fired"}))
25076        });
25077
25078        let task = WorkflowTask {
25079            task_id: "wft-rust-timer-pending".to_string(),
25080            workflow_command_id: None,
25081            workflow_id: Some("wf-rust-timer".to_string()),
25082            run_id: Some("run-rust-timer".to_string()),
25083            workflow_type: "rust.timer.pending".to_string(),
25084            cancel_requested: false,
25085            payload_codec: DEFAULT_CODEC.to_string(),
25086            arguments: Some(
25087                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25088            ),
25089            history_events: vec![history_event(
25090                "TimerScheduled",
25091                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25092            )],
25093            total_history_events: Some(1),
25094            history_size_bytes: None,
25095            continue_as_new_recommended: None,
25096            history_budget_pressure: None,
25097            next_history_page_token: None,
25098            workflow_task_attempt: 1,
25099            workflow_signal_id: None,
25100            signal_name: None,
25101            signal_arguments: None,
25102            workflow_update_id: None,
25103            update_name: None,
25104            lease_owner: Some("rust-worker".to_string()),
25105        };
25106
25107        for _redelivery_or_restart in 0..2 {
25108            let commands = worker
25109                .execute_workflow_task(task.clone())
25110                .expect("recorded timer remains pending");
25111            assert!(
25112                commands.is_empty(),
25113                "recorded timer must not be rescheduled"
25114            );
25115        }
25116    }
25117
25118    #[test]
25119    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
25120        let client = Client::new("http://127.0.0.1:8080").expect("client");
25121        let mut worker = Worker::new(client, "rust-workers");
25122        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
25123            Ok(json!({"status": "completed"}))
25124        });
25125        let task = WorkflowTask {
25126            task_id: "wft-rust-timer-removed".to_string(),
25127            workflow_command_id: None,
25128            workflow_id: Some("wf-rust-timer".to_string()),
25129            run_id: Some("run-rust-timer".to_string()),
25130            workflow_type: "rust.timer.removed".to_string(),
25131            cancel_requested: false,
25132            payload_codec: DEFAULT_CODEC.to_string(),
25133            arguments: Some(
25134                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25135            ),
25136            history_events: vec![
25137                history_event(
25138                    "TimerScheduled",
25139                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25140                ),
25141                history_event(
25142                    "TimerFired",
25143                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25144                ),
25145            ],
25146            total_history_events: Some(2),
25147            history_size_bytes: None,
25148            continue_as_new_recommended: None,
25149            history_budget_pressure: None,
25150            next_history_page_token: None,
25151            workflow_task_attempt: 1,
25152            workflow_signal_id: None,
25153            signal_name: None,
25154            signal_arguments: None,
25155            workflow_update_id: None,
25156            update_name: None,
25157            lease_owner: Some("rust-worker".to_string()),
25158        };
25159
25160        let Error::NonDeterministicReplay(failure) = worker
25161            .execute_workflow_task(task)
25162            .expect_err("removed timer must fail replay")
25163        else {
25164            panic!("expected typed replay failure");
25165        };
25166        assert_eq!(failure.reason, "recorded_commands_unconsumed");
25167        assert_eq!(failure.sequence, Some(1));
25168    }
25169
25170    #[test]
25171    fn workflow_context_emits_explicit_child_workflow_contract() {
25172        let ctx = WorkflowContext {
25173            cancellation_scope_id: "root".into(),
25174            state: Arc::new(Mutex::new(
25175                WorkflowState::new_with_identity(
25176                    Vec::new(),
25177                    Some("wf-parent".to_string()),
25178                    Some("run-parent".to_string()),
25179                    "parent-workers".to_string(),
25180                    DEFAULT_CODEC.to_string(),
25181                    None,
25182                )
25183                .expect("workflow state"),
25184            )),
25185        };
25186        let options = ChildWorkflowOptions::new("python-workers")
25187            .parent_close_policy(ParentClosePolicy::RequestCancel)
25188            .retry_policy(ChildWorkflowRetryPolicy {
25189                max_attempts: Some(3),
25190                backoff_seconds: vec![1, 5],
25191                non_retryable_error_types: vec!["ValidationError".to_string()],
25192            })
25193            .execution_timeout_seconds(600)
25194            .run_timeout_seconds(120);
25195        let mut call = Box::pin(ctx.start_child_workflow(
25196            "python.fulfil-order",
25197            options,
25198            json!([{"order_id": "order-42"}]),
25199        ));
25200        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25201
25202        assert!(matches!(
25203            call.as_mut().poll(&mut task_context),
25204            Poll::Pending
25205        ));
25206        let commands = ctx.take_commands().expect("commands");
25207        assert_eq!(commands.len(), 1);
25208        let command = &commands[0];
25209        assert_eq!(command["type"], "start_child_workflow");
25210        assert_eq!(command["workflow_type"], "python.fulfil-order");
25211        assert_eq!(command["queue"], "python-workers");
25212        assert_eq!(command["parent_close_policy"], "request_cancel");
25213        assert_eq!(command["retry_policy"]["max_attempts"], 3);
25214        assert_eq!(command["execution_timeout_seconds"], 600);
25215        assert_eq!(command["run_timeout_seconds"], 120);
25216        assert_eq!(
25217            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
25218            json!([{"order_id": "order-42"}])
25219        );
25220    }
25221
25222    fn child_parent_worker() -> Worker {
25223        let client = Client::new("http://127.0.0.1:8080").expect("client");
25224        let mut worker = Worker::new(client, "rust-parent-workers");
25225        worker.register_workflow("rust.parent", |ctx, _input| async move {
25226            let child = ctx
25227                .start_child_workflow(
25228                    "python.child",
25229                    ChildWorkflowOptions::new("python-child-workers")
25230                        .parent_close_policy(ParentClosePolicy::Terminate),
25231                    json!([{"codec_probe": [1, true, "rust"]}]),
25232                )
25233                .await?;
25234            Ok(json!({
25235                "parent_workflow_id": child.parent.workflow_id,
25236                "parent_run_id": child.parent.run_id,
25237                "child_workflow_id": child.child.workflow_id,
25238                "child_run_id": child.child.run_id,
25239                "child_workflow_type": child.child_workflow_type,
25240                "result": child.result,
25241            }))
25242        });
25243        worker
25244    }
25245
25246    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
25247        WorkflowTask {
25248            task_id: "wft-child-parent".to_string(),
25249            workflow_command_id: None,
25250            workflow_id: Some("wf-parent".to_string()),
25251            run_id: Some("run-parent".to_string()),
25252            workflow_type: "rust.parent".to_string(),
25253            cancel_requested: false,
25254            payload_codec: DEFAULT_CODEC.to_string(),
25255            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25256            history_events: vec![
25257                HistoryEvent {
25258                    event_type: "ChildWorkflowScheduled".to_string(),
25259                    payload: json!({
25260                        "sequence": 1,
25261                        "child_call_id": "call-child",
25262                        "child_workflow_instance_id": "wf-child",
25263                        "child_workflow_run_id": "run-child",
25264                        "child_workflow_type": "python.child",
25265                        "parent_close_policy": "terminate",
25266                    }),
25267                    raw: HashMap::new(),
25268                },
25269                HistoryEvent {
25270                    event_type: event_type.to_string(),
25271                    payload,
25272                    raw: HashMap::new(),
25273                },
25274            ],
25275            total_history_events: Some(2),
25276            history_size_bytes: None,
25277            continue_as_new_recommended: None,
25278            history_budget_pressure: None,
25279            next_history_page_token: None,
25280            workflow_task_attempt: 1,
25281            workflow_signal_id: None,
25282            signal_name: None,
25283            signal_arguments: None,
25284            workflow_update_id: None,
25285            update_name: None,
25286            lease_owner: Some("rust-worker".to_string()),
25287        }
25288    }
25289
25290    #[test]
25291    fn committed_child_result_replays_without_starting_a_duplicate() {
25292        let worker = child_parent_worker();
25293        let task = child_parent_task(
25294            "ChildRunCompleted",
25295            json!({
25296                "sequence": 1,
25297                "child_call_id": "call-child",
25298                "child_workflow_instance_id": "wf-child",
25299                "child_workflow_run_id": "run-child",
25300                "child_workflow_type": "python.child",
25301                "payload_codec": DEFAULT_CODEC,
25302                "result": fixture_envelope(json!({"from":"python","ok":true})),
25303            }),
25304        );
25305
25306        for _restart in 0..2 {
25307            let commands = worker
25308                .execute_workflow_task(task.clone())
25309                .expect("replayed parent task");
25310            assert_eq!(commands.len(), 1);
25311            assert_eq!(commands[0]["type"], "complete_workflow");
25312            assert!(!commands
25313                .iter()
25314                .any(|command| command["type"] == "start_child_workflow"));
25315            let output =
25316                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25317            assert_eq!(output["parent_workflow_id"], "wf-parent");
25318            assert_eq!(output["parent_run_id"], "run-parent");
25319            assert_eq!(output["child_workflow_id"], "wf-child");
25320            assert_eq!(output["child_run_id"], "run-child");
25321            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
25322        }
25323    }
25324
25325    #[test]
25326    fn typed_child_arguments_and_results_survive_replay() {
25327        let client = Client::new("http://127.0.0.1:8080").expect("client");
25328        let mut worker = Worker::new(client, "rust-parent-workers");
25329        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
25330            let child = ctx
25331                .start_child_workflow_avro_value(
25332                    "python.typed-child",
25333                    ChildWorkflowOptions::new("python-workers"),
25334                    AvroValue::Array(vec![typed_fidelity_probe()]),
25335                )
25336                .await?;
25337            Ok(child.result)
25338        });
25339
25340        let initial = worker
25341            .execute_workflow_task(workflow_task(
25342                "rust.typed-parent",
25343                Vec::new(),
25344                DEFAULT_CODEC,
25345            ))
25346            .expect("typed child start");
25347        assert_eq!(initial[0]["type"], "start_child_workflow");
25348        assert_eq!(
25349            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
25350                .expect("typed child arguments"),
25351            AvroValue::Array(vec![typed_fidelity_probe()])
25352        );
25353
25354        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
25355            .expect("typed child result");
25356        let task = workflow_task(
25357            "rust.typed-parent",
25358            vec![
25359                history_event(
25360                    "ChildWorkflowScheduled",
25361                    json!({
25362                        "sequence": 1,
25363                        "child_call_id": "call-typed",
25364                        "child_workflow_instance_id": "wf-child",
25365                        "child_workflow_run_id": "run-child",
25366                        "child_workflow_type": "python.typed-child",
25367                    }),
25368                ),
25369                history_event(
25370                    "ChildRunCompleted",
25371                    json!({
25372                        "sequence": 1,
25373                        "child_call_id": "call-typed",
25374                        "child_workflow_instance_id": "wf-child",
25375                        "child_workflow_run_id": "run-child",
25376                        "child_workflow_type": "python.typed-child",
25377                        "payload_codec": DEFAULT_CODEC,
25378                        "result": result,
25379                    }),
25380                ),
25381            ],
25382            DEFAULT_CODEC,
25383        );
25384
25385        let commands = worker
25386            .execute_workflow_task(task)
25387            .expect("typed child replay");
25388        assert_eq!(commands[0]["type"], "complete_workflow");
25389        assert_eq!(
25390            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
25391                .expect("typed parent result"),
25392            typed_fidelity_probe()
25393        );
25394    }
25395
25396    #[test]
25397    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
25398        let worker = child_parent_worker();
25399        let mut task = child_parent_task("unused", Value::Null);
25400        task.history_events.truncate(1);
25401        task.total_history_events = Some(1);
25402
25403        for _redelivery_or_restart in 0..2 {
25404            let commands = worker
25405                .execute_workflow_task(task.clone())
25406                .expect("recorded child remains pending");
25407            assert!(
25408                commands.is_empty(),
25409                "recorded pending child must not be started again"
25410            );
25411        }
25412    }
25413
25414    #[test]
25415    fn child_cancellation_becomes_stable_parent_failure_command() {
25416        let worker = child_parent_worker();
25417        let task = child_parent_task(
25418            "ChildRunCancelled",
25419            json!({
25420                "sequence": 1,
25421                "child_workflow_instance_id": "wf-child",
25422                "child_workflow_run_id": "run-child",
25423                "child_workflow_type": "python.child",
25424                "failure_id": "failure-child",
25425                "failure_category": "cancelled",
25426                "message": "cancelled by parent-close policy",
25427            }),
25428        );
25429
25430        let commands = worker
25431            .execute_workflow_task(task)
25432            .expect("parent settlement");
25433        assert_eq!(commands.len(), 1);
25434        assert_eq!(commands[0]["type"], "fail_workflow");
25435        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
25436        assert_eq!(
25437            commands[0]["exception"]["properties"]["reason"],
25438            "cancelled"
25439        );
25440        assert_eq!(
25441            commands[0]["exception"]["properties"]["child_workflow_run_id"],
25442            "run-child"
25443        );
25444    }
25445
25446    #[test]
25447    fn workflow_can_handle_typed_child_failure() {
25448        let client = Client::new("http://127.0.0.1:8080").expect("client");
25449        let mut worker = Worker::new(client, "rust-parent-workers");
25450        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
25451            match ctx
25452                .start_child_workflow(
25453                    "python.child",
25454                    ChildWorkflowOptions::new("python-child-workers"),
25455                    json!([]),
25456                )
25457                .await
25458            {
25459                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
25460                    "reason": failure.reason,
25461                    "failure_id": failure.failure_id,
25462                    "exception_class": failure.exception_class,
25463                    "child_run_id": failure.child_workflow_run_id,
25464                })),
25465                Err(error) => Err(error),
25466                Ok(_) => Err(Error::WorkerLoop(
25467                    "child unexpectedly succeeded".to_string(),
25468                )),
25469            }
25470        });
25471        let mut task = child_parent_task(
25472            "ChildRunFailed",
25473            json!({
25474                "sequence": 1,
25475                "child_workflow_instance_id": "wf-child",
25476                "child_workflow_run_id": "run-child",
25477                "child_workflow_type": "python.child",
25478                "failure_id": "failure-child",
25479                "failure_category": "child_workflow",
25480                "message": "payment rejected",
25481                "exception": {
25482                    "type": "PaymentRejected",
25483                    "class": "payments.PaymentRejected",
25484                    "message": "payment rejected"
25485                }
25486            }),
25487        );
25488        task.workflow_type = "rust.handled-parent".to_string();
25489        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
25490
25491        let commands = worker.execute_workflow_task(task).expect("handled failure");
25492        assert_eq!(commands[0]["type"], "complete_workflow");
25493        let output =
25494            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
25495        assert_eq!(output["reason"], "child_workflow");
25496        assert_eq!(output["failure_id"], "failure-child");
25497        assert_eq!(output["exception_class"], "payments.PaymentRejected");
25498        assert_eq!(output["child_run_id"], "run-child");
25499    }
25500
25501    #[test]
25502    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
25503        let client = Client::new("http://127.0.0.1:8080").expect("client");
25504        let mut worker = Worker::new(client, "rust-workers");
25505
25506        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
25507            let signal = ctx.wait_signal("start").await?;
25508            let name = signal
25509                .first()
25510                .and_then(|value| value.as_str())
25511                .unwrap_or("world");
25512            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
25513            Ok(json!({
25514                "greeting": greeting,
25515                "language": "rust"
25516            }))
25517        });
25518
25519        let signal_arguments =
25520            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
25521        let task = WorkflowTask {
25522            task_id: "wft-rust-signal-1".to_string(),
25523            workflow_command_id: None,
25524            workflow_id: Some("wf-rust-hello".to_string()),
25525            run_id: Some("run-rust-hello".to_string()),
25526            workflow_type: "rust.hello_workflow".to_string(),
25527            cancel_requested: false,
25528            payload_codec: DEFAULT_CODEC.to_string(),
25529            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25530            history_events: vec![HistoryEvent {
25531                event_type: "SignalReceived".to_string(),
25532                payload: json!({
25533                    "signal_id": "sig-rust-1",
25534                    "signal_name": "start"
25535                }),
25536                raw: HashMap::new(),
25537            }],
25538            total_history_events: Some(1),
25539            history_size_bytes: None,
25540            continue_as_new_recommended: None,
25541            history_budget_pressure: None,
25542            next_history_page_token: None,
25543            workflow_task_attempt: 1,
25544            workflow_signal_id: Some("sig-rust-1".to_string()),
25545            signal_name: Some("start".to_string()),
25546            signal_arguments: Some(signal_arguments),
25547            workflow_update_id: None,
25548            update_name: None,
25549            lease_owner: Some("rust-worker".to_string()),
25550        };
25551
25552        let commands = worker.execute_workflow_task(task).expect("workflow task");
25553
25554        assert_eq!(commands.len(), 1);
25555        assert_eq!(commands[0]["type"], "schedule_activity");
25556        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
25557        assert_eq!(
25558            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
25559            json!(["Rust"])
25560        );
25561    }
25562
25563    #[test]
25564    fn workflow_task_appends_paginated_history_events() {
25565        let mut task = WorkflowTask {
25566            task_id: "wft-rust-pages-1".to_string(),
25567            workflow_command_id: None,
25568            workflow_id: Some("wf-rust-pages".to_string()),
25569            run_id: Some("run-rust-pages".to_string()),
25570            workflow_type: "rust.hello_workflow".to_string(),
25571            cancel_requested: false,
25572            payload_codec: DEFAULT_CODEC.to_string(),
25573            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
25574            history_events: vec![HistoryEvent {
25575                event_type: "WorkflowStarted".to_string(),
25576                payload: json!({}),
25577                raw: HashMap::new(),
25578            }],
25579            total_history_events: Some(3),
25580            history_size_bytes: None,
25581            continue_as_new_recommended: None,
25582            history_budget_pressure: None,
25583            next_history_page_token: Some("MQ==".to_string()),
25584            workflow_task_attempt: 1,
25585            workflow_signal_id: None,
25586            signal_name: None,
25587            signal_arguments: None,
25588            workflow_update_id: None,
25589            update_name: None,
25590            lease_owner: Some("rust-worker".to_string()),
25591        };
25592
25593        task.append_history_page(WorkflowTaskHistoryPage {
25594            history_events: vec![
25595                HistoryEvent {
25596                    event_type: "SignalReceived".to_string(),
25597                    payload: json!({
25598                        "signal_id": "sig-rust-1",
25599                        "signal_name": "start",
25600                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
25601                            .expect("signal arguments")
25602                    }),
25603                    raw: HashMap::new(),
25604                },
25605                HistoryEvent {
25606                    event_type: "MarkerRecorded".to_string(),
25607                    payload: json!({"sequence": 3}),
25608                    raw: HashMap::new(),
25609                },
25610            ],
25611            total_history_events: Some(3),
25612            next_history_page_token: None,
25613        });
25614
25615        assert_eq!(task.history_events.len(), 3);
25616        assert_eq!(task.total_history_events, Some(3));
25617        assert_eq!(task.next_history_page_token, None);
25618
25619        let signal = task
25620            .history_events
25621            .iter()
25622            .find(|event| event.event_type == "SignalReceived")
25623            .expect("signal event");
25624        assert_eq!(
25625            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
25626            vec![AvroValue::String("Rust".to_string())]
25627        );
25628    }
25629
25630    #[tokio::test]
25631    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
25632        let client = Client::new("http://127.0.0.1:8080").expect("client");
25633        let mut worker = Worker::new(client, "rust-workers");
25634        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25635        worker.register_query("counter", "current", |ctx, _args| async move {
25636            let mut count = 0_i64;
25637            for signal in ctx.signal_events() {
25638                let value = signal
25639                    .arguments
25640                    .first()
25641                    .and_then(Value::as_i64)
25642                    .unwrap_or_default();
25643                match signal.name.as_str() {
25644                    "increment" => count += value,
25645                    "set" => count = value,
25646                    _ => {}
25647                }
25648            }
25649            Ok(json!(count))
25650        });
25651
25652        let task = QueryTask {
25653            query_task_id: "query-rust-counter".to_string(),
25654            query_task_attempt: 1,
25655            lease_owner: Some("rust-worker".to_string()),
25656            workflow_id: Some("counter-1".to_string()),
25657            run_id: Some("run-counter-1".to_string()),
25658            workflow_type: "counter".to_string(),
25659            query_name: "current".to_string(),
25660            payload_codec: DEFAULT_CODEC.to_string(),
25661            workflow_arguments: Some(
25662                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
25663            ),
25664            query_arguments: Some(
25665                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
25666            ),
25667            history_events: vec![
25668                HistoryEvent {
25669                    event_type: "SignalReceived".to_string(),
25670                    payload: json!({
25671                        "signal_id": "php-signal-1",
25672                        "signal_name": "increment",
25673                        "workflow_sequence": 1,
25674                        "payload_codec": DEFAULT_CODEC,
25675                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
25676                    }),
25677                    raw: HashMap::new(),
25678                },
25679                HistoryEvent {
25680                    event_type: "SignalReceived".to_string(),
25681                    payload: json!({
25682                        "signal_id": "python-signal-2",
25683                        "signal_name": "increment",
25684                        "workflow_sequence": 2,
25685                        "payload_codec": DEFAULT_CODEC,
25686                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
25687                    }),
25688                    raw: HashMap::new(),
25689                },
25690                HistoryEvent {
25691                    event_type: "SignalReceived".to_string(),
25692                    payload: json!({
25693                        "signal_id": "rust-signal-3",
25694                        "signal_name": "set",
25695                        "workflow_sequence": 3,
25696                        "payload_codec": DEFAULT_CODEC,
25697                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
25698                    }),
25699                    raw: HashMap::new(),
25700                },
25701            ],
25702            history_export: None,
25703            run_status: Some("completed".to_string()),
25704        };
25705
25706        let result = worker.execute_query_task(task).await.expect("query result");
25707        assert_eq!(result.into_json().expect("query projection"), json!(0));
25708    }
25709
25710    #[tokio::test]
25711    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
25712        let worker = replay_counter_worker();
25713        let running_history = json!([
25714            {
25715                "type": "ActivityCompleted",
25716                "payload": {
25717                    "sequence": 1,
25718                    "activity_type": "load-counter",
25719                    "payload_codec": DEFAULT_CODEC,
25720                    "result": fixture_envelope(json!("loaded"))
25721                }
25722            },
25723            {
25724                "type": "SignalWaitOpened",
25725                "payload": {
25726                    "sequence": 3,
25727                    "signal_name": "increment"
25728                }
25729            },
25730            {
25731                "type": "SignalReceived",
25732                "payload": {
25733                    "signal_id": "signal-3",
25734                    "signal_name": "increment",
25735                    "workflow_sequence": 2,
25736                    "payload_codec": DEFAULT_CODEC,
25737                    "arguments": fixture_envelope(json!([3]))
25738                }
25739            },
25740            {
25741                "type": "SignalApplied",
25742                "payload": {
25743                    "sequence": 3,
25744                    "signal_id": "signal-3",
25745                    "signal_name": "increment",
25746                    "payload_codec": DEFAULT_CODEC,
25747                    "value": fixture_envelope(json!([3]))
25748                }
25749            }
25750        ]);
25751
25752        let running = worker
25753            .execute_query_task(replay_counter_query(
25754                "current",
25755                running_history.clone(),
25756                "running",
25757            ))
25758            .await
25759            .expect("running replay query");
25760        assert_eq!(
25761            running.clone().into_json().expect("query projection"),
25762            json!({"loaded": "loaded", "count": 3, "finished": false})
25763        );
25764
25765        let detached = worker
25766            .execute_query_task(replay_counter_query(
25767                "detached-mutation",
25768                running_history.clone(),
25769                "running",
25770            ))
25771            .await
25772            .expect("query mutates only its detached state clone");
25773        assert_eq!(detached.into_json().expect("query projection"), json!(999));
25774        let failed = worker
25775            .execute_query_task(replay_counter_query(
25776                "failed-mutation",
25777                running_history.clone(),
25778                "running",
25779            ))
25780            .await
25781            .expect_err("failed query");
25782        assert_eq!(failed.reason, "query_rejected");
25783        let unchanged = worker
25784            .execute_query_task(replay_counter_query("current", running_history, "running"))
25785            .await
25786            .expect("later query reconstructs unchanged state");
25787        assert_eq!(unchanged, running);
25788
25789        let restarted_worker = replay_counter_worker();
25790        let empty_arguments = fixture_envelope(json!([]));
25791        let loaded_result = fixture_envelope(json!("loaded"));
25792        let signal_three = fixture_blob(json!([3]));
25793        let signal_five = fixture_blob(json!([5]));
25794        let restarted_task: QueryTask = serde_json::from_value(json!({
25795            "query_task_id": "query-after-restart",
25796            "workflow_id": "counter-1",
25797            "run_id": "run-counter-1",
25798            "workflow_type": "replay-counter",
25799            "query_name": "current",
25800            "payload_codec": DEFAULT_CODEC,
25801            "workflow_arguments": empty_arguments.clone(),
25802            "query_arguments": empty_arguments,
25803            "history_events": [],
25804            "history_export": {
25805                "payloads": {"codec": DEFAULT_CODEC},
25806                "history_events": [
25807                    {
25808                        "type": "ActivityCompleted",
25809                        "payload": {
25810                            "sequence": 1,
25811                            "activity_type": "load-counter",
25812                            "payload_codec": DEFAULT_CODEC,
25813                            "result": null
25814                        }
25815                    },
25816                    {
25817                        "type": "SignalWaitOpened",
25818                        "payload": {
25819                            "sequence": 3,
25820                            "signal_name": "increment"
25821                        }
25822                    },
25823                    {
25824                        "type": "SignalReceived",
25825                        "payload": {
25826                            "signal_id": "signal-3",
25827                            "signal_name": "increment",
25828                            "workflow_sequence": 2
25829                        }
25830                    },
25831                    {
25832                        "type": "SignalApplied",
25833                        "payload": {
25834                            "sequence": 3,
25835                            "signal_id": "signal-3",
25836                            "signal_name": "increment"
25837                        }
25838                    },
25839                    {
25840                        "type": "SignalWaitOpened",
25841                        "payload": {
25842                            "sequence": 5,
25843                            "signal_name": "increment"
25844                        }
25845                    },
25846                    {
25847                        "type": "SignalReceived",
25848                        "payload": {
25849                            "signal_id": "signal-5",
25850                            "signal_name": "increment",
25851                            "workflow_sequence": 4
25852                        }
25853                    },
25854                    {
25855                        "type": "SignalApplied",
25856                        "payload": {
25857                            "sequence": 5,
25858                            "signal_id": "signal-5",
25859                            "signal_name": "increment"
25860                        }
25861                    }
25862                ],
25863                "activities": [{
25864                    "sequence": 1,
25865                    "activity_type": "load-counter",
25866                    "payload_codec": DEFAULT_CODEC,
25867                    "result": loaded_result
25868                }],
25869                "signals": [
25870                    {
25871                        "id": "signal-3",
25872                        "name": "increment",
25873                        "workflow_sequence": 2,
25874                        "payload_codec": DEFAULT_CODEC,
25875                        "arguments": signal_three
25876                    },
25877                    {
25878                        "id": "signal-5",
25879                        "name": "increment",
25880                        "workflow_sequence": 4,
25881                        "payload_codec": DEFAULT_CODEC,
25882                        "arguments": signal_five
25883                    }
25884                ]
25885            },
25886            "run_status": "completed"
25887        }))
25888        .expect("cold replay query task");
25889        let completed = restarted_worker
25890            .execute_query_task(restarted_task)
25891            .await
25892            .expect("completed cold replay query");
25893        assert_eq!(
25894            completed.into_json().expect("query projection"),
25895            json!({"loaded": "loaded", "count": 8, "finished": true})
25896        );
25897    }
25898
25899    #[tokio::test]
25900    async fn replayed_query_replay_failures_are_machine_readable() {
25901        let worker = replay_counter_worker();
25902        let task = replay_counter_query(
25903            "current",
25904            json!([{
25905                "type": "ActivityCompleted",
25906                "payload": {
25907                    "sequence": 1,
25908                    "payload_codec": DEFAULT_CODEC,
25909                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
25910                }
25911            }]),
25912            "running",
25913        );
25914        let failure = worker
25915            .execute_query_task(task)
25916            .await
25917            .expect_err("invalid replay history payload");
25918        assert_eq!(failure.reason, "query_payload_decode_failed");
25919        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
25920        assert!(failure.message.contains("invalid_payload_framing"));
25921    }
25922
25923    #[tokio::test]
25924    async fn query_task_restores_compact_history_from_export() {
25925        let client = Client::new("http://127.0.0.1:8080").expect("client");
25926        let mut worker = Worker::new(client, "rust-workers");
25927        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25928        worker.register_query("counter", "current", |ctx, _args| async move {
25929            Ok(json!(ctx.signals("increment")[0][0]))
25930        });
25931        let empty_arguments = fixture_envelope(json!([]));
25932        let exported_signal = fixture_blob(json!([9]));
25933        let task: QueryTask = serde_json::from_value(json!({
25934            "query_task_id": "query-export",
25935            "workflow_type": "counter",
25936            "query_name": "current",
25937            "payload_codec": DEFAULT_CODEC,
25938            "workflow_arguments": empty_arguments.clone(),
25939            "query_arguments": empty_arguments,
25940            "history_events": [],
25941            "history_export": {
25942                "payloads": {"codec": DEFAULT_CODEC},
25943                "history_events": [{
25944                    "type": "SignalReceived",
25945                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
25946                }],
25947                "signals": [{
25948                    "id": "signal-export",
25949                    "name": "increment",
25950                    "status": "applied",
25951                    "workflow_sequence": 1,
25952                    "payload_codec": DEFAULT_CODEC,
25953                    "arguments": exported_signal
25954                }]
25955            }
25956        }))
25957        .expect("query task");
25958
25959        let result = worker.execute_query_task(task).await.expect("query result");
25960        assert_eq!(result.into_json().expect("query projection"), json!(9));
25961    }
25962
25963    #[tokio::test]
25964    async fn query_task_failures_have_stable_reasons() {
25965        let client = Client::new("http://127.0.0.1:8080").expect("client");
25966        let mut worker = Worker::new(client, "rust-workers");
25967        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
25968        worker.register_query(
25969            "counter",
25970            "current",
25971            |_ctx, _args| async move { Ok(json!(0)) },
25972        );
25973
25974        let base_task = QueryTask {
25975            query_task_id: "query-errors".to_string(),
25976            query_task_attempt: 1,
25977            lease_owner: None,
25978            workflow_id: Some("counter-errors".to_string()),
25979            run_id: Some("run-errors".to_string()),
25980            workflow_type: "counter".to_string(),
25981            query_name: "missing".to_string(),
25982            payload_codec: DEFAULT_CODEC.to_string(),
25983            workflow_arguments: Some(fixture_envelope(json!([]))),
25984            query_arguments: Some(fixture_envelope(json!([]))),
25985            history_events: Vec::new(),
25986            history_export: None,
25987            run_status: Some("running".to_string()),
25988        };
25989
25990        let unknown = worker
25991            .execute_query_task(base_task.clone())
25992            .await
25993            .expect_err("unknown query");
25994        assert_eq!(unknown.reason, "rejected_unknown_query");
25995
25996        let mut malformed = base_task;
25997        malformed.query_name = "current".to_string();
25998        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
25999        let malformed = worker
26000            .execute_query_task(malformed)
26001            .await
26002            .expect_err("malformed payload");
26003        assert_eq!(malformed.reason, "query_payload_decode_failed");
26004
26005        let client = Client::new("http://127.0.0.1:8080").expect("client");
26006        let mut unavailable_worker = Worker::new(client, "rust-workers");
26007        unavailable_worker
26008            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
26009        let empty_arguments = fixture_envelope(json!([]));
26010        let unavailable_task: QueryTask = serde_json::from_value(json!({
26011            "query_task_id": "query-unavailable",
26012            "workflow_type": "counter",
26013            "query_name": "current",
26014            "payload_codec": DEFAULT_CODEC,
26015            "workflow_arguments": empty_arguments.clone(),
26016            "query_arguments": empty_arguments
26017        }))
26018        .expect("query task");
26019        let unavailable = unavailable_worker
26020            .execute_query_task(unavailable_task)
26021            .await
26022            .expect_err("query handler unavailable");
26023        assert_eq!(unavailable.reason, "query_handler_unavailable");
26024    }
26025
26026    #[tokio::test]
26027    async fn client_query_decodes_result_and_typed_failure() {
26028        let server = MockWorkerServer::start();
26029        let client = Client::builder(server.base_url())
26030            .timeout(Duration::from_secs(2))
26031            .build()
26032            .expect("client");
26033
26034        let result = client
26035            .query_workflow("counter-1", "current", json!([]))
26036            .await
26037            .expect("query result");
26038        assert_eq!(result, json!({"count": 8}));
26039
26040        let error = client
26041            .query_workflow("counter-1", "missing", json!([]))
26042            .await
26043            .expect_err("unknown query");
26044        let Error::QueryFailed(failure) = error else {
26045            panic!("expected typed query failure");
26046        };
26047        assert_eq!(failure.status, 404);
26048        assert_eq!(failure.reason, "rejected_unknown_query");
26049    }
26050
26051    #[tokio::test]
26052    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
26053        let server = MockWorkerServer::start();
26054        let client = Client::builder(server.base_url())
26055            .timeout(Duration::from_secs(2))
26056            .build()
26057            .expect("client");
26058        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
26059
26060        client
26061            .start_workflow(
26062                "typed.echo",
26063                "rust-workers",
26064                "typed-start",
26065                arguments.clone(),
26066            )
26067            .await
26068            .expect("typed workflow start");
26069        assert_eq!(
26070            decode_wire_avro_value(
26071                &server.request_body("/api/workflows")["input"],
26072                DEFAULT_CODEC,
26073            )
26074            .expect("typed start input"),
26075            arguments
26076        );
26077
26078        client
26079            .signal_workflow("typed-1", "changed", arguments.clone())
26080            .await
26081            .expect("typed signal");
26082        assert_eq!(
26083            decode_wire_avro_value(
26084                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
26085                DEFAULT_CODEC,
26086            )
26087            .expect("typed signal input"),
26088            arguments
26089        );
26090
26091        assert_eq!(
26092            client
26093                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
26094                .await
26095                .expect("typed query"),
26096            typed_fidelity_probe()
26097        );
26098        assert_eq!(
26099            decode_wire_avro_value(
26100                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
26101                DEFAULT_CODEC,
26102            )
26103            .expect("typed query input"),
26104            arguments
26105        );
26106
26107        assert_eq!(
26108            client
26109                .update_workflow_avro_value(
26110                    "typed-1",
26111                    "replace",
26112                    arguments.clone(),
26113                    Some("typed-request"),
26114                )
26115                .await
26116                .expect("typed update"),
26117            typed_fidelity_probe()
26118        );
26119        let update = server.request_body("/api/workflows/typed-1/update/replace");
26120        assert_eq!(update["request_id"], "typed-request");
26121        assert_eq!(
26122            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
26123            arguments
26124        );
26125
26126        let handle = WorkflowHandle {
26127            client: client.clone(),
26128            workflow_id: "typed-1".to_string(),
26129            run_id: Some("run-typed-1".to_string()),
26130            workflow_type: "typed.echo".to_string(),
26131        };
26132        assert_eq!(
26133            handle
26134                .result_avro_value(WorkflowResultOptions::default())
26135                .await
26136                .expect("typed workflow result"),
26137            typed_fidelity_probe()
26138        );
26139
26140        client
26141            .complete_activity_task(
26142                "activity-typed",
26143                "attempt-typed",
26144                "rust-worker",
26145                typed_fidelity_probe(),
26146                DEFAULT_CODEC,
26147            )
26148            .await
26149            .expect("typed activity completion");
26150        assert_eq!(
26151            decode_wire_avro_value(
26152                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
26153                    ["result"],
26154                DEFAULT_CODEC,
26155            )
26156            .expect("typed activity result"),
26157            typed_fidelity_probe()
26158        );
26159        client
26160            .fail_activity_task(
26161                "activity-typed",
26162                "attempt-typed",
26163                "rust-worker",
26164                "typed failure",
26165                true,
26166            )
26167            .await
26168            .expect("activity failure");
26169    }
26170
26171    #[tokio::test]
26172    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
26173        let server = MockWorkerServer::start();
26174        let client = Client::builder(server.base_url())
26175            .timeout(Duration::from_secs(2))
26176            .build()
26177            .expect("client");
26178
26179        let options = WorkflowCommandOptions::new()
26180            .reason("cleanup requested")
26181            .request_id("cancel-17");
26182        let cancelled = client
26183            .cancel_workflow("wf-lifecycle", options)
26184            .await
26185            .expect("instance cancellation");
26186        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
26187        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
26188        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
26189        assert_eq!(
26190            server.request_body("/api/workflows/wf-lifecycle/cancel"),
26191            json!({"reason":"cleanup requested","request_id":"cancel-17"})
26192        );
26193
26194        let terminated = client
26195            .terminate_workflow(
26196                "wf-lifecycle",
26197                WorkflowCommandOptions::new().reason("forced stop"),
26198            )
26199            .await
26200            .expect("instance termination");
26201        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
26202        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
26203
26204        client
26205            .cancel_workflow_run(
26206                "wf-lifecycle",
26207                "run-current",
26208                WorkflowCommandOptions::default(),
26209            )
26210            .await
26211            .expect("selected run cancellation");
26212        client
26213            .terminate_workflow_run(
26214                "wf-lifecycle",
26215                "run-current",
26216                WorkflowCommandOptions::default(),
26217            )
26218            .await
26219            .expect("selected run termination");
26220
26221        for (command, error) in [
26222            (
26223                WorkflowCommandKind::Cancel,
26224                client
26225                    .cancel_workflow_run(
26226                        "wf-lifecycle",
26227                        "run-stale",
26228                        WorkflowCommandOptions::default(),
26229                    )
26230                    .await
26231                    .expect_err("stale cancellation must be rejected"),
26232            ),
26233            (
26234                WorkflowCommandKind::Terminate,
26235                client
26236                    .terminate_workflow_run(
26237                        "wf-lifecycle",
26238                        "run-stale",
26239                        WorkflowCommandOptions::default(),
26240                    )
26241                    .await
26242                    .expect_err("stale termination must be rejected"),
26243            ),
26244        ] {
26245            let Error::WorkflowCommandRejected(rejection) = error else {
26246                panic!("expected typed command rejection");
26247            };
26248            assert_eq!(rejection.command, command);
26249            assert_eq!(rejection.status, 409);
26250            assert_eq!(rejection.reason, "historical_run_command_rejected");
26251            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
26252            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
26253        }
26254    }
26255
26256    #[tokio::test]
26257    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
26258        let server = MockWorkerServer::start();
26259        let client = Client::builder(server.base_url())
26260            .timeout(Duration::from_secs(2))
26261            .build()
26262            .expect("client");
26263
26264        let result = client
26265            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
26266            .await
26267            .expect("redrive accepted");
26268        assert_eq!(result.workflow_id, "wf-lifecycle");
26269        assert_eq!(result.source_run_id, "run-failed");
26270        assert_eq!(result.run_id, "run-successor");
26271        assert_eq!(result.resume_step_sequence, 2);
26272        assert_eq!(
26273            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
26274            json!({"request_id":"retry-1"})
26275        );
26276
26277        let repeated = client
26278            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
26279            .await
26280            .expect("idempotent redrive response accepted");
26281        assert_eq!(repeated.run_id, "run-successor");
26282
26283        let error = client
26284            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
26285            .await
26286            .expect_err("completed run must be rejected");
26287        let Error::Http { status, body } = error else {
26288            panic!("expected HTTP redrive rejection");
26289        };
26290        assert_eq!(status.as_u16(), 409);
26291        assert!(body.contains("run_not_failed"));
26292        assert_eq!(
26293            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
26294            json!({})
26295        );
26296
26297        let handle = WorkflowHandle {
26298            client: client.clone(),
26299            workflow_id: "wf-lifecycle".to_string(),
26300            run_id: Some("run-failed".to_string()),
26301            workflow_type: "test".to_string(),
26302        };
26303        assert_eq!(
26304            handle.redrive(None).await.expect("handle redrive").run_id,
26305            "run-successor"
26306        );
26307        let missing_run = WorkflowHandle {
26308            run_id: None,
26309            ..handle
26310        };
26311        assert!(matches!(
26312            missing_run.redrive(None).await,
26313            Err(Error::Codec(_))
26314        ));
26315    }
26316
26317    #[tokio::test]
26318    async fn workflow_start_options_send_server_enforced_deadlines() {
26319        let server = MockWorkerServer::start();
26320        let client = Client::builder(server.base_url())
26321            .timeout(Duration::from_secs(2))
26322            .build()
26323            .expect("client");
26324
26325        let handle = client
26326            .start_workflow_with_options(
26327                "rust.timeout",
26328                "rust-timeouts",
26329                "wf-start-options",
26330                WorkflowStartOptions::new()
26331                    .execution_timeout_seconds(30)
26332                    .run_timeout_seconds(1),
26333                json!([]),
26334            )
26335            .await
26336            .expect("workflow start");
26337
26338        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
26339        let body = server.request_body("/api/workflows");
26340        assert_eq!(body["execution_timeout_seconds"], 30);
26341        assert_eq!(body["run_timeout_seconds"], 1);
26342
26343        let invalid = client
26344            .start_workflow_with_options(
26345                "rust.timeout",
26346                "rust-timeouts",
26347                "wf-invalid-options",
26348                WorkflowStartOptions::new()
26349                    .execution_timeout_seconds(1)
26350                    .run_timeout_seconds(2),
26351                json!([]),
26352            )
26353            .await
26354            .expect_err("invalid deadline ordering");
26355        assert!(invalid
26356            .to_string()
26357            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
26358    }
26359
26360    #[tokio::test]
26361    async fn workflow_result_returns_each_typed_terminal_outcome() {
26362        let server = MockWorkerServer::start();
26363        let client = Client::builder(server.base_url())
26364            .timeout(Duration::from_secs(2))
26365            .build()
26366            .expect("client");
26367        let options = WorkflowResultOptions {
26368            poll_interval: Duration::ZERO,
26369            timeout: Duration::from_secs(1),
26370        };
26371
26372        let failed = WorkflowHandle {
26373            client: client.clone(),
26374            workflow_id: "wf-failed".to_string(),
26375            run_id: Some("run-failed".to_string()),
26376            workflow_type: "failure".to_string(),
26377        }
26378        .result(options)
26379        .await
26380        .expect_err("failed outcome");
26381        let Error::WorkflowFailed(failure) = failed else {
26382            panic!("expected WorkflowFailed");
26383        };
26384        assert_eq!(failure.workflow_id, "wf-failed");
26385        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
26386        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
26387        assert_eq!(failure.failure_category.as_deref(), Some("application"));
26388        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
26389        assert_eq!(
26390            failure.exception_class.as_deref(),
26391            Some("billing::PaymentError")
26392        );
26393        assert_eq!(failure.non_retryable, Some(true));
26394
26395        for (workflow_id, expected_kind, expected_reason) in [
26396            (
26397                "wf-cancelled",
26398                WorkflowTerminalKind::Cancelled,
26399                "cleanup requested",
26400            ),
26401            (
26402                "wf-terminated",
26403                WorkflowTerminalKind::Terminated,
26404                "forced stop",
26405            ),
26406            (
26407                "wf-timed-out",
26408                WorkflowTerminalKind::TimedOut,
26409                "run_timeout",
26410            ),
26411        ] {
26412            let error = WorkflowHandle {
26413                client: client.clone(),
26414                workflow_id: workflow_id.to_string(),
26415                run_id: None,
26416                workflow_type: "terminal".to_string(),
26417            }
26418            .result(options)
26419            .await
26420            .expect_err("typed terminal outcome");
26421            let outcome = match error {
26422                Error::WorkflowCancelled(outcome) => outcome,
26423                Error::WorkflowTerminated(outcome) => outcome,
26424                Error::WorkflowTimedOut(outcome) => outcome,
26425                other => panic!("unexpected terminal error: {other}"),
26426            };
26427            assert_eq!(outcome.kind, expected_kind);
26428            assert_eq!(outcome.workflow_id, workflow_id);
26429            assert_eq!(outcome.reason, expected_reason);
26430        }
26431
26432        let wait_timeout = WorkflowHandle {
26433            client,
26434            workflow_id: "wf-waiting".to_string(),
26435            run_id: Some("run-waiting".to_string()),
26436            workflow_type: "waiting".to_string(),
26437        }
26438        .result(WorkflowResultOptions {
26439            poll_interval: Duration::ZERO,
26440            timeout: Duration::ZERO,
26441        })
26442        .await
26443        .expect_err("client wait timeout");
26444        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
26445            panic!("expected typed client timeout");
26446        };
26447        assert_eq!(timeout.reason, "result_wait_timeout");
26448        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
26449        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
26450    }
26451
26452    #[tokio::test]
26453    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
26454        let server = MockWorkerServer::start();
26455        let client = Client::builder(server.base_url())
26456            .timeout(Duration::from_secs(2))
26457            .build()
26458            .expect("client");
26459
26460        let handle = WorkflowHandle {
26461            client,
26462            workflow_id: "wf-selected".to_string(),
26463            run_id: Some("run-selected".to_string()),
26464            workflow_type: "selected".to_string(),
26465        };
26466        let options = WorkflowResultOptions {
26467            poll_interval: Duration::ZERO,
26468            timeout: Duration::from_secs(1),
26469        };
26470
26471        let current = handle
26472            .result(options)
26473            .await
26474            .expect("instance result follows the current run");
26475        assert_eq!(current, json!("current run output"));
26476
26477        let error = handle
26478            .result_selected_run(options)
26479            .await
26480            .expect_err("the selected run is cancelled even though the current run completed");
26481
26482        let Error::WorkflowCancelled(outcome) = error else {
26483            panic!("expected selected run cancellation");
26484        };
26485        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
26486        assert_eq!(outcome.reason, "selected run cancelled");
26487        assert_eq!(
26488            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
26489            1
26490        );
26491        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
26492    }
26493
26494    #[tokio::test]
26495    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
26496        let server = MockWorkerServer::draining_polls();
26497        let client = Client::builder(server.base_url())
26498            .timeout(Duration::from_secs(2))
26499            .build()
26500            .expect("client");
26501
26502        let workflow = client
26503            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
26504            .await
26505            .expect("workflow drain response");
26506        let activity = client
26507            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
26508            .await
26509            .expect("activity drain response");
26510        let query = client
26511            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
26512            .await
26513            .expect("query drain response");
26514
26515        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
26516            assert_eq!(
26517                outcome,
26518                WorkerPollOutcome::Stop {
26519                    poll_status: Some("draining".to_string()),
26520                    reason: Some("worker_draining".to_string()),
26521                }
26522            );
26523        }
26524
26525        assert!(client
26526            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
26527            .await
26528            .expect("compatibility poll")
26529            .is_none());
26530    }
26531
26532    #[tokio::test]
26533    async fn managed_worker_honors_drain_stop_for_every_task_family() {
26534        let server = MockWorkerServer::draining_polls();
26535        let client = Client::builder(server.base_url())
26536            .timeout(Duration::from_secs(2))
26537            .build()
26538            .expect("client");
26539
26540        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
26541            .worker_id("draining-workflow-worker")
26542            .poll_timeout(Duration::ZERO);
26543        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
26544        workflow_worker
26545            .run()
26546            .await
26547            .expect("workflow drain is a clean stop");
26548
26549        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
26550            .worker_id("draining-activity-worker")
26551            .poll_timeout(Duration::ZERO);
26552        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
26553        activity_worker
26554            .run()
26555            .await
26556            .expect("activity drain is a clean stop");
26557
26558        let mut query_worker = Worker::new(client, "rust-workers")
26559            .worker_id("draining-query-worker")
26560            .poll_timeout(Duration::ZERO);
26561        query_worker.register_query("counter", "current", |_ctx, _args| async {
26562            Ok(Value::Null)
26563        });
26564        query_worker
26565            .run()
26566            .await
26567            .expect("query drain is a clean stop");
26568    }
26569
26570    #[tokio::test]
26571    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
26572        let server = MockWorkerServer::start();
26573        let client = Client::builder(server.base_url())
26574            .timeout(Duration::from_secs(2))
26575            .build()
26576            .expect("client");
26577
26578        let details: Value = serde_json::from_str(include_str!(
26579            "../tests/fixtures/activity-heartbeat-progress.json"
26580        ))
26581        .expect("heartbeat progress fixture");
26582        // Every individual field fits Server's progress contract, while the
26583        // obsolete encoded envelope exceeded its 191-character string limit.
26584        assert!(
26585            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
26586                .unwrap()["blob"]
26587                .as_str()
26588                .unwrap()
26589                .len()
26590                > 191
26591        );
26592        let heartbeat = client
26593            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
26594            .await
26595            .expect("cancellation heartbeat");
26596        assert!(heartbeat.cancel_requested);
26597        assert!(heartbeat.should_stop());
26598        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
26599        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
26600        let heartbeat_body =
26601            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
26602        assert_eq!(heartbeat_body["details"], details);
26603        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
26604        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
26605
26606        let error = client
26607            .complete_activity_task(
26608                "activity-cancel",
26609                "attempt-cancel",
26610                "rust-worker",
26611                json!({"late":true}),
26612                DEFAULT_CODEC,
26613            )
26614            .await
26615            .expect_err("late completion must be refused");
26616        assert!(activity_task_rejection_is_final(&error));
26617        let Error::ActivityTaskRejected(rejection) = error else {
26618            panic!("expected typed activity rejection");
26619        };
26620        assert_eq!(rejection.status, 409);
26621        assert_eq!(rejection.reason, "run_cancelled");
26622        assert!(rejection.cancel_requested);
26623        assert_eq!(rejection.can_continue, Some(false));
26624    }
26625
26626    #[tokio::test]
26627    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
26628        let server = MockWorkerServer::cancelled_activity();
26629        let client = Client::builder(server.base_url())
26630            .timeout(Duration::from_secs(2))
26631            .build()
26632            .expect("client");
26633        let cancellation_observed = Arc::new(AtomicBool::new(false));
26634        let observed = Arc::clone(&cancellation_observed);
26635        let mut worker = Worker::new(client.clone(), "rust-workers")
26636            .worker_id("rust-cancel-worker")
26637            .poll_timeout(Duration::from_millis(10));
26638        worker.register_activity("cancel-aware", move |ctx, _args| {
26639            let observed = Arc::clone(&observed);
26640            async move {
26641                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
26642                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
26643                Ok(json!({"late":"completion"}))
26644            }
26645        });
26646
26647        assert_eq!(
26648            worker.run_once().await.expect("cancelled attempt handled"),
26649            1
26650        );
26651        assert!(cancellation_observed.load(Ordering::SeqCst));
26652        assert_eq!(
26653            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
26654            1
26655        );
26656
26657        let mut restarted = Worker::new(client, "rust-workers")
26658            .worker_id("rust-cancel-worker-restarted")
26659            .poll_timeout(Duration::from_millis(10));
26660        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
26661        assert_eq!(
26662            restarted
26663                .run_once()
26664                .await
26665                .expect("replacement worker continues polling"),
26666            0
26667        );
26668    }
26669
26670    #[tokio::test]
26671    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
26672        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"}"#;
26673        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
26674        let client = Client::builder(server.base_url())
26675            .timeout(Duration::from_secs(2))
26676            .build()
26677            .expect("client");
26678
26679        let direct_error = client
26680            .complete_workflow_task(
26681                "workflow-timeout-task",
26682                "timeout-worker",
26683                3,
26684                vec![json!({
26685                    "type": "complete_workflow",
26686                    "result": fixture_envelope(Value::Null)
26687                })],
26688            )
26689            .await
26690            .expect_err("the low-level client preserves the completion rejection");
26691        let Error::Http { status, body } = direct_error else {
26692            panic!("expected the original HTTP completion rejection");
26693        };
26694        assert_eq!(status, reqwest::StatusCode::CONFLICT);
26695        assert_eq!(
26696            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
26697            "run_timed_out"
26698        );
26699
26700        let mut worker = Worker::new(client, "rust-workers")
26701            .worker_id("timeout-worker")
26702            .poll_timeout(Duration::from_millis(10));
26703        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26704            Ok(json!({"late": "result"}))
26705        });
26706
26707        assert_eq!(
26708            worker
26709                .run_once()
26710                .await
26711                .expect("authoritative selected-run timeout settles the tick"),
26712            1
26713        );
26714        assert_eq!(
26715            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
26716            2,
26717            "both the direct client proof and managed worker must see the rejection"
26718        );
26719    }
26720
26721    #[tokio::test]
26722    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
26723        for (name, status, response) in [
26724            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
26725            (
26726                "command was recorded",
26727                "409 Conflict",
26728                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26729            ),
26730            (
26731                "lease conflict",
26732                "409 Conflict",
26733                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
26734            ),
26735            (
26736                "nonterminal run",
26737                "409 Conflict",
26738                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
26739            ),
26740            (
26741                "different selected run",
26742                "409 Conflict",
26743                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"}"#,
26744            ),
26745            (
26746                "different task attempt",
26747                "409 Conflict",
26748                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26749            ),
26750            (
26751                "authentication failure",
26752                "401 Unauthorized",
26753                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26754            ),
26755            (
26756                "authorization failure",
26757                "403 Forbidden",
26758                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26759            ),
26760            (
26761                "protocol failure",
26762                "400 Bad Request",
26763                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
26764            ),
26765            (
26766                "malformed command",
26767                "422 Unprocessable Entity",
26768                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26769            ),
26770            (
26771                "transient server failure",
26772                "503 Service Unavailable",
26773                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
26774            ),
26775        ] {
26776            let server = MockWorkerServer::workflow_completion(status, response);
26777            let client = Client::builder(server.base_url())
26778                .timeout(Duration::from_secs(2))
26779                .build()
26780                .expect("client");
26781            let mut worker = Worker::new(client, "rust-workers")
26782                .worker_id("timeout-worker")
26783                .poll_timeout(Duration::from_millis(10));
26784            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
26785                Ok(json!({"late": "result"}))
26786            });
26787
26788            let error = worker
26789                .run_once()
26790                .await
26791                .expect_err(&format!("{name} must remain an error"));
26792            assert!(
26793                matches!(error, Error::Http { .. } | Error::Protocol(_)),
26794                "{name} returned an unexpected error variant: {error}"
26795            );
26796        }
26797    }
26798
26799    #[tokio::test]
26800    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
26801        let server = MockWorkerServer::start();
26802        let client = Client::builder(server.base_url())
26803            .worker_token(Some("worker-secret".to_string()))
26804            .namespace("orders")
26805            .timeout(Duration::from_secs(2))
26806            .build()
26807            .expect("client");
26808        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
26809
26810        let result = client
26811            .deregister_worker_registration("worker/α space")
26812            .await
26813            .expect("deregister worker registration");
26814
26815        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
26816        assert_eq!(
26817            server.worker_protocol_for(path).as_deref(),
26818            Some(WORKER_PROTOCOL_VERSION)
26819        );
26820        assert_eq!(server.control_protocol_for(path), None);
26821        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
26822        assert_eq!(
26823            server.authorization_for(path).as_deref(),
26824            Some("Bearer worker-secret")
26825        );
26826        assert_eq!(
26827            result,
26828            WorkerDeregistrationEnvelope {
26829                worker_id: "deregistered-worker".to_string(),
26830                outcome: "deregistered".to_string(),
26831                recovered_workflow_task_count: 2,
26832            }
26833        );
26834    }
26835
26836    #[tokio::test]
26837    async fn low_level_registration_rejects_update_validators_before_transport() {
26838        let server = MockWorkerServer::start();
26839        let client = Client::builder(server.base_url())
26840            .timeout(Duration::from_secs(2))
26841            .build()
26842            .expect("client");
26843
26844        for update_validators in [json!(["approve"]), json!("approve")] {
26845            let error = client
26846                .register_worker_with_command_contracts(
26847                    "validator-claiming-worker",
26848                    "rust-workers",
26849                    vec!["orders".to_string()],
26850                    vec![],
26851                    1,
26852                    1,
26853                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
26854                    json!({
26855                        "orders": {
26856                            "queries": ["current"],
26857                            "updates": ["approve"],
26858                            "update_validators": update_validators,
26859                        },
26860                    }),
26861                )
26862                .await
26863                .expect_err("unsupported validator claims must fail before registration");
26864
26865            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
26866                panic!("expected typed unsupported-validator failure");
26867            };
26868            assert_eq!(workflow_type, "orders");
26869        }
26870        assert_eq!(server.request_count("/api/worker/register"), 0);
26871    }
26872
26873    #[tokio::test]
26874    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
26875        let server = MockWorkerServer::start();
26876        let client = Client::builder(server.base_url())
26877            .timeout(Duration::from_secs(2))
26878            .build()
26879            .expect("client");
26880        let mut worker = Worker::new(client, "rust-workers");
26881        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
26882        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
26883        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
26884        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
26885        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
26886        worker
26887            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
26888            .expect("declare workflow signals");
26889
26890        worker.register().await.expect("register handler contracts");
26891
26892        let declaration =
26893            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
26894        let expected_contracts = json!([
26895            {
26896                "name": "a-avro",
26897                "parameters": [{
26898                    "name": "args", "position": 0, "required": false,
26899                    "variadic": true, "type": null, "allows_null": true,
26900                    "default_available": false, "default": null,
26901                }],
26902            },
26903            {
26904                "name": "z-json",
26905                "parameters": [{
26906                    "name": "args", "position": 0, "required": false,
26907                    "variadic": true, "type": null, "allows_null": true,
26908                    "default_available": false, "default": null,
26909                }],
26910            },
26911        ]);
26912        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
26913        assert_eq!(declaration["query_contracts"], expected_contracts);
26914        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
26915        assert_eq!(declaration["update_contracts"], expected_contracts);
26916        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
26917        assert_eq!(declaration["signal_contracts"], expected_contracts);
26918        assert_eq!(declaration["update_validators"], json!([]));
26919    }
26920
26921    #[tokio::test]
26922    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
26923        let server = MockWorkerServer::start();
26924        let client = Client::new(server.base_url()).expect("client");
26925        let mut worker = Worker::new(client, "rust-workers");
26926        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
26927        assert!(worker
26928            .declare_workflow_signals("missing", &["finish"])
26929            .is_err());
26930        worker
26931            .declare_workflow_signals("orders", &["finish"])
26932            .unwrap();
26933        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
26934            assert!(worker.declare_workflow_signals("orders", names).is_err());
26935        }
26936        worker.register().await.unwrap();
26937        assert_eq!(
26938            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
26939                ["signals"],
26940            json!(["finish"])
26941        );
26942        worker.declare_workflow_signals("orders", &[]).unwrap();
26943        worker.register().await.unwrap();
26944        let registrations = server.request_bodies("/api/worker/register");
26945        assert_eq!(
26946            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
26947            json!([])
26948        );
26949        assert_eq!(
26950            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
26951            json!([])
26952        );
26953    }
26954
26955    #[tokio::test]
26956    async fn low_level_registration_preserves_query_and_update_contracts() {
26957        let server = MockWorkerServer::start();
26958        let client = Client::builder(server.base_url())
26959            .timeout(Duration::from_secs(2))
26960            .build()
26961            .expect("client");
26962        let contracts = json!({
26963            "orders": {
26964                "queries": ["current"],
26965                "updates": ["approve"],
26966                "update_validators": [],
26967            },
26968            "payments": {
26969                "queries": ["status"],
26970                "updates": ["capture"],
26971            },
26972        });
26973
26974        client
26975            .register_worker_with_command_contracts(
26976                "command-worker",
26977                "rust-workers",
26978                vec!["orders".to_string(), "payments".to_string()],
26979                vec![],
26980                1,
26981                1,
26982                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
26983                contracts.clone(),
26984            )
26985            .await
26986            .expect("query and update contracts must remain supported");
26987
26988        assert_eq!(
26989            server.request_body("/api/worker/register")["workflow_command_contracts"],
26990            contracts
26991        );
26992        assert!(server
26993            .request_body("/api/worker/register")
26994            .get("workflow_definition_fingerprints")
26995            .is_none());
26996    }
26997
26998    #[tokio::test]
26999    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
27000        let server = MockWorkerServer::start();
27001        let client = Client::builder(server.base_url())
27002            .timeout(Duration::from_secs(2))
27003            .build()
27004            .expect("client");
27005        let mut worker = Worker::new(client.clone(), "rust-workers");
27006        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27007
27008        assert!(worker
27009            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
27010            .is_err());
27011        assert!(worker
27012            .set_workflow_definition_sources("orders", &[])
27013            .is_err());
27014        worker
27015            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
27016            .expect("embed workflow source");
27017        worker.register().await.expect("register worker");
27018        let first = server.request_bodies("/api/worker/register")[0]
27019            ["workflow_definition_fingerprints"]["orders"]
27020            .as_str()
27021            .expect("source-backed fingerprint")
27022            .to_string();
27023        assert!(first.starts_with("sha256:"));
27024
27025        worker
27026            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
27027            .expect("change embedded helper source");
27028        worker.register().await.expect("register changed source");
27029        let changed = server.request_bodies("/api/worker/register")[1]
27030            ["workflow_definition_fingerprints"]["orders"]
27031            .as_str()
27032            .expect("changed fingerprint")
27033            .to_string();
27034        assert_ne!(first, changed);
27035
27036        let mut replacement =
27037            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
27038        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
27039        replacement
27040            .register()
27041            .await
27042            .expect("register replacement handler");
27043        assert_eq!(
27044            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
27045            json!({})
27046        );
27047    }
27048
27049    #[tokio::test]
27050    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
27051        let server = MockWorkerServer::start();
27052        let control_only = Client::builder(server.base_url())
27053            .control_token(Some("control-secret".to_string()))
27054            .build()
27055            .expect("control client");
27056
27057        let error = control_only
27058            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27059            .await
27060            .expect_err("control token must not authorize a worker request");
27061        assert!(matches!(
27062            error,
27063            Error::MissingRoleCredentials { role: "worker", .. }
27064        ));
27065        assert_eq!(server.request_count("/api/worker/register"), 0);
27066
27067        let worker_only = Client::builder(server.base_url())
27068            .worker_token(Some("worker-secret".to_string()))
27069            .build()
27070            .expect("worker client");
27071        let error = worker_only
27072            .health()
27073            .await
27074            .expect_err("worker token must not authorize a control request");
27075        assert!(matches!(
27076            error,
27077            Error::MissingRoleCredentials {
27078                role: "control",
27079                ..
27080            }
27081        ));
27082        assert_eq!(server.request_count("/api/health"), 0);
27083    }
27084
27085    #[tokio::test]
27086    async fn shared_token_supports_worker_and_control_planes() {
27087        let server = MockWorkerServer::start();
27088        let client = Client::builder(server.base_url())
27089            .token(Some("shared-secret".to_string()))
27090            .build()
27091            .expect("client");
27092
27093        client.health().await.expect("control request");
27094        client
27095            .register_worker("worker", "queue", vec![], vec![], 1, 1)
27096            .await
27097            .expect("worker request");
27098
27099        assert_eq!(
27100            server.authorization_for("/api/health").as_deref(),
27101            Some("Bearer shared-secret")
27102        );
27103        assert_eq!(
27104            server.control_protocol_for("/api/health").as_deref(),
27105            Some(CONTROL_PLANE_VERSION)
27106        );
27107        assert_eq!(
27108            server.authorization_for("/api/worker/register").as_deref(),
27109            Some("Bearer shared-secret")
27110        );
27111        assert_eq!(
27112            server
27113                .worker_protocol_for("/api/worker/register")
27114                .as_deref(),
27115            Some(WORKER_PROTOCOL_VERSION)
27116        );
27117    }
27118
27119    #[tokio::test]
27120    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
27121        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
27122        let server = MockWorkerServer::start();
27123        let client = Client::builder(server.base_url())
27124            .timeout(Duration::from_secs(2))
27125            .build()
27126            .expect("client");
27127
27128        client
27129            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
27130            .await
27131            .expect("register");
27132        client
27133            .heartbeat_worker("capture-worker", 1, 1)
27134            .await
27135            .expect("heartbeat");
27136        client
27137            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27138            .await
27139            .expect("workflow poll");
27140        client
27141            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27142            .await
27143            .expect("activity poll");
27144
27145        for path in [
27146            "/api/worker/register",
27147            "/api/worker/heartbeat",
27148            "/api/worker/workflow-tasks/poll",
27149            "/api/worker/activity-tasks/poll",
27150        ] {
27151            assert_eq!(
27152                server.worker_protocol_for(path).as_deref(),
27153                Some(WORKER_PROTOCOL_VERSION),
27154                "unexpected protocol for {path}"
27155            );
27156        }
27157
27158        assert_eq!(
27159            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
27160            1
27161        );
27162        assert_eq!(
27163            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
27164            500
27165        );
27166        assert_eq!(
27167            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
27168            1
27169        );
27170        assert!(
27171            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
27172                .as_str()
27173                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
27174        );
27175        assert!(
27176            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
27177                .as_str()
27178                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
27179        );
27180        let registration = server.request_body("/api/worker/register");
27181        for optional in [
27182            "cooperative_cancellation",
27183            "local_activities",
27184            "worker_sessions",
27185            "sticky_execution",
27186        ] {
27187            assert!(!registration["capabilities"]
27188                .as_array()
27189                .is_some_and(|capabilities| capabilities
27190                    .iter()
27191                    .any(|capability| capability.as_str() == Some(optional))));
27192        }
27193    }
27194
27195    #[tokio::test]
27196    async fn explicit_previous_worker_protocol_preserves_headers() {
27197        let server = MockWorkerServer::start();
27198        let client = Client::builder(server.base_url())
27199            .worker_protocol_version(WorkerProtocolVersion::V119)
27200            .timeout(Duration::from_secs(2))
27201            .build()
27202            .expect("client");
27203        client
27204            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
27205            .await
27206            .expect("register");
27207        client
27208            .heartbeat_worker("legacy-worker", 1, 1)
27209            .await
27210            .expect("heartbeat");
27211        client
27212            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
27213            .await
27214            .expect("workflow poll");
27215        client
27216            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
27217            .await
27218            .expect("activity poll");
27219        client
27220            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
27221            .await
27222            .expect("query poll");
27223        client
27224            .deregister_worker_registration("legacy-worker")
27225            .await
27226            .expect("deregister");
27227        for path in [
27228            "/api/worker/register",
27229            "/api/worker/heartbeat",
27230            "/api/worker/workflow-tasks/poll",
27231            "/api/worker/activity-tasks/poll",
27232            "/api/worker/query-tasks/poll",
27233            "/api/worker/registrations/legacy-worker",
27234        ] {
27235            assert_eq!(
27236                server.worker_protocol_for(path).as_deref(),
27237                Some("1.19"),
27238                "{path}"
27239            );
27240            assert_eq!(server.control_protocol_for(path), None, "{path}");
27241        }
27242    }
27243
27244    #[tokio::test]
27245    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
27246        let server = MockWorkerServer::start();
27247        let client = Client::builder(server.base_url())
27248            .worker_protocol_version(WorkerProtocolVersion::V119)
27249            .timeout(Duration::from_secs(2))
27250            .build()
27251            .expect("client");
27252        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
27253        let error = worker
27254            .register()
27255            .await
27256            .expect_err("legacy cooperation must be refused");
27257        assert!(matches!(
27258            error,
27259            Error::CooperativeCancellationUnavailable(_)
27260        ));
27261        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
27262    }
27263
27264    #[tokio::test]
27265    async fn query_task_endpoints_send_the_selected_worker_protocol() {
27266        let server = MockWorkerServer::start();
27267        let client = Client::builder(server.base_url())
27268            .timeout(Duration::from_secs(2))
27269            .build()
27270            .expect("client");
27271
27272        client
27273            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27274            .await
27275            .expect("query poll");
27276        client
27277            .complete_query_task(
27278                "query-capture",
27279                "capture-worker",
27280                1,
27281                json!(8),
27282                DEFAULT_CODEC,
27283            )
27284            .await
27285            .expect("query complete");
27286        client
27287            .fail_query_task(
27288                "query-capture",
27289                "capture-worker",
27290                1,
27291                "failed",
27292                "query_rejected",
27293                "QueryFailed",
27294            )
27295            .await
27296            .expect("query fail");
27297
27298        for path in [
27299            "/api/worker/query-tasks/poll",
27300            "/api/worker/query-tasks/query-capture/complete",
27301            "/api/worker/query-tasks/query-capture/fail",
27302        ] {
27303            assert_eq!(
27304                server.worker_protocol_for(path).as_deref(),
27305                Some(WORKER_PROTOCOL_VERSION),
27306                "unexpected protocol for {path}"
27307            );
27308        }
27309
27310        assert_eq!(
27311            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
27312            1
27313        );
27314        assert!(
27315            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
27316                .as_str()
27317                .is_some_and(|id| id.starts_with("rust-query-poll-"))
27318        );
27319    }
27320
27321    #[tokio::test]
27322    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
27323        let server = MockWorkerServer::transient_worker_failures();
27324        let client = Client::builder(server.base_url())
27325            .timeout(Duration::from_secs(2))
27326            .build()
27327            .expect("client");
27328
27329        client
27330            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
27331            .await
27332            .expect("workflow poll retry");
27333        client
27334            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
27335            .await
27336            .expect("activity poll retry");
27337        client
27338            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
27339            .await
27340            .expect("query poll retry");
27341
27342        for path in [
27343            "/api/worker/workflow-tasks/poll",
27344            "/api/worker/activity-tasks/poll",
27345            "/api/worker/query-tasks/poll",
27346        ] {
27347            let bodies = server.request_bodies(path);
27348            assert_eq!(bodies.len(), 2, "{path} must be retried once");
27349            assert_eq!(
27350                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
27351                "{path} must preserve the request binding across retry"
27352            );
27353        }
27354    }
27355
27356    #[tokio::test]
27357    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
27358        let server = MockWorkerServer::consecutive_poll_failures(2);
27359        let client = Client::builder(server.base_url())
27360            .timeout(Duration::from_secs(2))
27361            .build()
27362            .expect("client");
27363        let mut worker = Worker::new(client, "capture")
27364            .worker_id("capture-worker")
27365            .poll_timeout(Duration::from_millis(10))
27366            .retry_policy(WorkerRetryPolicy {
27367                max_retries: 2,
27368                initial_backoff: Duration::from_millis(1),
27369                max_backoff: Duration::from_millis(1),
27370            });
27371        worker.register_workflow(
27372            "capture.workflow",
27373            |_ctx, _input| async move { Ok(Value::Null) },
27374        );
27375        worker.register_activity(
27376            "capture.activity",
27377            |_ctx, _input| async move { Ok(Value::Null) },
27378        );
27379        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
27380            Ok(Value::Null)
27381        });
27382
27383        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
27384
27385        for path in [
27386            "/api/worker/workflow-tasks/poll",
27387            "/api/worker/activity-tasks/poll",
27388            "/api/worker/query-tasks/poll",
27389        ] {
27390            let bodies = server.request_bodies(path);
27391            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
27392            assert!(
27393                bodies
27394                    .iter()
27395                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
27396                "{path} must preserve one request binding across every retry"
27397            );
27398        }
27399    }
27400
27401    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
27402        let reason = if unavailable {
27403            "storage_admission_unavailable"
27404        } else {
27405            "storage_pressure"
27406        };
27407        let mut body = json!({
27408            "reason": reason,
27409            "storage_state": if unavailable { "fenced" } else { "draining" },
27410            "retryable": true,
27411            "retry_after_seconds": 1,
27412        });
27413        if !mid_poll {
27414            body["request_admitted"] = json!(false);
27415        }
27416        if let Some(id) = poll_id {
27417            body["task"] = Value::Null;
27418            body["poll_status"] = json!(reason);
27419            body["poll_request_id"] = json!(id);
27420            body["retry_same_poll_request_id"] = json!(true);
27421            body["claim_admitted"] = json!(false);
27422        }
27423        body
27424    }
27425
27426    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
27427        let operation = match path {
27428            "/api/worker/register" => "register_worker",
27429            "/api/worker/heartbeat" => "heartbeat_worker",
27430            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
27431            "/api/worker/activity-tasks/poll" => "poll_activity_task",
27432            "/api/worker/query-tasks/poll" => "poll_query_task",
27433            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
27434            _ => return None,
27435        };
27436        let request: Value = serde_json::from_str(request).ok()?;
27437        let mut response = json!({
27438            "reason": "backend_unavailable",
27439            "operation": operation,
27440            "outcome": "unknown",
27441            "retryable": true,
27442            "retry_after_seconds": 1,
27443            "worker_id": request["worker_id"],
27444            "task_queue": request.get("task_queue"),
27445        });
27446        if path.ends_with("/poll") {
27447            response["task"] = Value::Null;
27448            response["poll_status"] = json!("backend_unavailable");
27449            response["poll_request_id"] = request["poll_request_id"].clone();
27450            response["retry_same_poll_request_id"] = json!(true);
27451        }
27452        Some(response)
27453    }
27454
27455    fn backend_retry_override(
27456        path: &str,
27457        request: &str,
27458        number: usize,
27459    ) -> Option<(&'static str, String)> {
27460        if number > 8 {
27461            return None;
27462        }
27463        Some((
27464            "503 Service Unavailable",
27465            backend_refusal(path, request)?.to_string(),
27466        ))
27467    }
27468
27469    fn backend_unavailable_override(
27470        path: &str,
27471        request: &str,
27472        _number: usize,
27473    ) -> Option<(&'static str, String)> {
27474        Some((
27475            "503 Service Unavailable",
27476            backend_refusal(path, request)?.to_string(),
27477        ))
27478    }
27479
27480    fn storage_worker(server: &MockWorkerServer) -> Worker {
27481        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
27482            .worker_id("storage-worker")
27483            .retry_policy(WorkerRetryPolicy {
27484                max_retries: 1,
27485                initial_backoff: Duration::from_millis(1),
27486                max_backoff: Duration::from_millis(1),
27487            })
27488    }
27489
27490    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
27491        let requests = server.requests.lock().expect("requests");
27492        let bodies: Vec<_> = requests
27493            .iter()
27494            .filter(|request| request.path == path)
27495            .map(|request| &request.body)
27496            .collect();
27497        assert_eq!(bodies.len(), count, "{path}");
27498        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
27499    }
27500
27501    #[test]
27502    fn backend_recovery_requires_the_explicit_worker_contract() {
27503        for (path, operation) in [
27504            ("/worker/register", "register_worker"),
27505            ("/worker/heartbeat", "heartbeat_worker"),
27506            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
27507            ("/worker/activity-tasks/poll", "poll_activity_task"),
27508            ("/worker/query-tasks/poll", "poll_query_task"),
27509            (
27510                "/worker/update-validation-tasks/poll",
27511                "poll_update_validation_task",
27512            ),
27513        ] {
27514            let poll_id = path.ends_with("/poll").then_some("same-poll");
27515            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
27516            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
27517                .expect("worker operation");
27518            assert_eq!(body["operation"], operation);
27519            let error = Error::Http {
27520                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27521                body: body.to_string(),
27522            };
27523            assert_eq!(
27524                worker_backend_unavailable_retry_after(&error, path, poll_id),
27525                Some(Duration::from_secs(1))
27526            );
27527            assert!(!worker_operation_is_retryable(&error));
27528            for (field, value) in [
27529                ("operation", json!("wrong_operation")),
27530                ("outcome", json!("completed")),
27531                ("retryable", json!(false)),
27532                ("retry_after_seconds", json!(0)),
27533                ("worker_id", json!("")),
27534            ] {
27535                let mut invalid = body.clone();
27536                invalid[field] = value;
27537                let error = Error::Http {
27538                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27539                    body: invalid.to_string(),
27540                };
27541                assert!(
27542                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
27543                    "{path}: {field}"
27544                );
27545                assert!(!worker_operation_is_retryable(&error));
27546            }
27547            if let Some(poll_id) = poll_id {
27548                for (field, value) in [
27549                    ("poll_request_id", json!("wrong-poll")),
27550                    ("poll_status", json!("empty")),
27551                    ("task", json!({"task_id":"claimed"})),
27552                    ("retry_same_poll_request_id", json!(false)),
27553                ] {
27554                    let mut invalid = body.clone();
27555                    invalid[field] = value;
27556                    let error = Error::Http {
27557                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27558                        body: invalid.to_string(),
27559                    };
27560                    assert!(
27561                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
27562                            .is_none(),
27563                        "{path}: {field}"
27564                    );
27565                }
27566            }
27567            let error = Error::Http {
27568                status: reqwest::StatusCode::UNAUTHORIZED,
27569                body: body.to_string(),
27570            };
27571            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
27572            assert!(!worker_operation_is_retryable(&error));
27573        }
27574    }
27575
27576    #[tokio::test]
27577    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
27578        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27579            request_override: Some(backend_retry_override),
27580            ..MockWorkerBehavior::default()
27581        });
27582        let mut worker =
27583            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27584        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27585        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
27586        worker.register_query("backend.workflow", "state", |_, _| async {
27587            Ok(Value::Null)
27588        });
27589        worker.register().await.expect("registration recovery");
27590        worker
27591            .client
27592            .heartbeat_worker("storage-worker", 1, 1)
27593            .await
27594            .expect("heartbeat recovery");
27595        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
27596        for path in [
27597            "/api/worker/register",
27598            "/api/worker/heartbeat",
27599            "/api/worker/workflow-tasks/poll",
27600            "/api/worker/activity-tasks/poll",
27601            "/api/worker/query-tasks/poll",
27602        ] {
27603            assert_identical_requests(&server, path, 9);
27604        }
27605    }
27606
27607    #[tokio::test]
27608    async fn backend_recovery_wait_stops_with_worker() {
27609        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27610            request_override: Some(backend_unavailable_override),
27611            ..MockWorkerBehavior::default()
27612        });
27613        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
27614            max_retries: 1,
27615            initial_backoff: Duration::from_secs(2),
27616            max_backoff: Duration::from_secs(2),
27617        });
27618        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
27619        let started = tokio::time::Instant::now();
27620        let _ = tokio::time::timeout(
27621            Duration::from_secs(1),
27622            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
27623        )
27624        .await
27625        .expect("shutdown interrupts backend wait");
27626        assert!(started.elapsed() < Duration::from_secs(1));
27627        assert!(server.request_count("/api/worker/register") >= 1);
27628    }
27629
27630    #[test]
27631    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
27632        for unavailable in [false, true] {
27633            for mid_poll in [false, true] {
27634                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
27635                let error = Error::Http {
27636                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27637                    body: body.to_string(),
27638                };
27639                assert_eq!(
27640                    worker_storage_admission_retry_after(&error, Some("same-poll")),
27641                    Some(Duration::from_secs(1))
27642                );
27643                assert!(
27644                    !worker_operation_is_retryable(&error),
27645                    "storage is not a bounded generic retry"
27646                );
27647                for (field, value) in [
27648                    ("poll_request_id", json!("wrong-poll")),
27649                    ("task", json!({"task_id":"claimed"})),
27650                    ("retryable", json!(false)),
27651                    ("retry_after_seconds", json!(0)),
27652                    ("retry_after_seconds", json!(true)),
27653                    ("retry_after_seconds", json!(1.0)),
27654                    ("storage_state", json!("normal")),
27655                    ("poll_status", json!("empty")),
27656                    ("claim_admitted", json!(true)),
27657                    ("retry_same_poll_request_id", json!(false)),
27658                    ("request_admitted", json!(true)),
27659                ] {
27660                    let mut invalid = body.clone();
27661                    invalid[field] = value;
27662                    let error = Error::Http {
27663                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27664                        body: invalid.to_string(),
27665                    };
27666                    assert!(
27667                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
27668                        "{field}"
27669                    );
27670                }
27671            }
27672        }
27673        let body = storage_refusal(None, false, false);
27674        let error = Error::Http {
27675            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27676            body: body.to_string(),
27677        };
27678        assert!(worker_storage_admission_retry_after(&error, None).is_some());
27679        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
27680        let error = Error::Http {
27681            status: reqwest::StatusCode::FORBIDDEN,
27682            body: body.to_string(),
27683        };
27684        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27685        let body = storage_refusal(None, false, true);
27686        let error = Error::Http {
27687            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
27688            body: body.to_string(),
27689        };
27690        assert!(worker_storage_admission_retry_after(&error, None).is_none());
27691    }
27692
27693    #[tokio::test]
27694    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
27695        for unavailable in [false, true] {
27696            for mid_poll in [false, true] {
27697                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27698                    poll_failures_per_path: 1,
27699                    storage_refusals: 7,
27700                    storage_path: Some("/poll"),
27701                    storage_unavailable: unavailable,
27702                    storage_mid_poll: mid_poll,
27703                    ..MockWorkerBehavior::default()
27704                });
27705                let mut worker = storage_worker(&server);
27706                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
27707                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
27708                for path in [
27709                    "/api/worker/workflow-tasks/poll",
27710                    "/api/worker/activity-tasks/poll",
27711                    "/api/worker/query-tasks/poll",
27712                ] {
27713                    assert_identical_requests(&server, path, 9);
27714                }
27715            }
27716        }
27717    }
27718
27719    #[tokio::test]
27720    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
27721        struct CountedBody(Arc<AtomicUsize>);
27722        impl Serialize for CountedBody {
27723            fn serialize<S: Serializer>(
27724                &self,
27725                serializer: S,
27726            ) -> std::result::Result<S::Ok, S::Error> {
27727                let count = self.0.fetch_add(1, Ordering::SeqCst);
27728                json!({"serialization":count,"lease_owner":"worker","attempt":7})
27729                    .serialize(serializer)
27730            }
27731        }
27732        for path in [
27733            "/api/worker/register",
27734            "/api/worker/heartbeat",
27735            "/api/worker/workflow-tasks/storage-task/complete",
27736            "/api/worker/workflow-tasks/storage-task/fail",
27737            "/api/worker/activity-tasks/storage-task/complete",
27738            "/api/worker/activity-tasks/storage-task/fail",
27739            "/api/worker/activity-tasks/storage-task/heartbeat",
27740            "/api/worker/query-tasks/storage-task/complete",
27741            "/api/worker/query-tasks/storage-task/fail",
27742        ] {
27743            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27744                storage_refusals: 7,
27745                storage_path: Some(path),
27746                ..MockWorkerBehavior::default()
27747            });
27748            let worker =
27749                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27750            let calls = Arc::new(AtomicUsize::new(0));
27751            let _: Value = worker
27752                .client
27753                .request_json(
27754                    reqwest::Method::POST,
27755                    &path[4..],
27756                    RequestProtocol::DefaultWorker,
27757                    Some(&CountedBody(Arc::clone(&calls))),
27758                )
27759                .await
27760                .expect("prepared request recovery");
27761            assert_eq!(calls.load(Ordering::SeqCst), 1);
27762            assert_identical_requests(&server, path, 8);
27763        }
27764        for worker_scope in [false, true] {
27765            let path = if worker_scope {
27766                "/api/health"
27767            } else {
27768                "/api/worker/register"
27769            };
27770            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27771                storage_refusals: usize::MAX,
27772                storage_path: Some(path),
27773                ..MockWorkerBehavior::default()
27774            });
27775            let worker = storage_worker(&server);
27776            let client = worker.client.clone();
27777            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
27778            let error = if worker_scope {
27779                worker
27780                    .client
27781                    .health()
27782                    .await
27783                    .expect_err("control plane is not retried")
27784            } else {
27785                client
27786                    .request_json::<Value, Value>(
27787                        reqwest::Method::POST,
27788                        "/worker/register",
27789                        RequestProtocol::DefaultWorker,
27790                        Some(&json!({})),
27791                    )
27792                    .await
27793                    .expect_err("direct client is not retried")
27794            };
27795            assert!(worker_storage_admission_body(&error).is_some());
27796            assert_eq!(server.request_count(path), 1);
27797        }
27798    }
27799
27800    #[tokio::test]
27801    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
27802        for fail in [false, true] {
27803            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27804                storage_activity: true,
27805                storage_refusals: 7,
27806                storage_path: Some("/storage-activity/"),
27807                ..MockWorkerBehavior::default()
27808            });
27809            let mut worker = storage_worker(&server);
27810            let calls = Arc::new(AtomicUsize::new(0));
27811            let observed = Arc::clone(&calls);
27812            worker.register_activity("storage.activity", move |ctx, _| {
27813                let calls = Arc::clone(&observed);
27814                async move {
27815                    calls.fetch_add(1, Ordering::SeqCst);
27816                    ctx.heartbeat(json!({"step":2})).await?;
27817                    if fail {
27818                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
27819                    } else {
27820                        Ok(json!({"receipt":true}))
27821                    }
27822                }
27823            });
27824            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
27825            assert_eq!(calls.load(Ordering::SeqCst), 1);
27826            assert_identical_requests(
27827                &server,
27828                "/api/worker/activity-tasks/storage-activity/heartbeat",
27829                8,
27830            );
27831            let suffix = if fail { "fail" } else { "complete" };
27832            assert_identical_requests(
27833                &server,
27834                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
27835                8,
27836            );
27837            let other = if fail { "complete" } else { "fail" };
27838            assert_eq!(
27839                server.request_count(&format!(
27840                    "/api/worker/activity-tasks/storage-activity/{other}"
27841                )),
27842                0
27843            );
27844        }
27845    }
27846
27847    #[tokio::test]
27848    async fn storage_waits_are_interruptible_without_false_activity_failure() {
27849        for path in [
27850            "/api/worker/register",
27851            "/api/worker/heartbeat",
27852            "/api/worker/activity-tasks/poll",
27853            "/api/worker/activity-tasks/storage-activity/heartbeat",
27854            "/api/worker/activity-tasks/storage-activity/complete",
27855        ] {
27856            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27857                storage_activity: true,
27858                storage_refusals: usize::MAX,
27859                storage_path: Some(path),
27860                ..MockWorkerBehavior::default()
27861            });
27862            let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
27863            worker.register_activity("storage.activity", |ctx, _| async move {
27864                ctx.heartbeat(json!({"step":2})).await?;
27865                Ok(json!({"receipt":true}))
27866            });
27867            let shutdown = async {
27868                while server.request_count(path) == 0 {
27869                    tokio::time::sleep(Duration::from_millis(1)).await;
27870                }
27871            };
27872            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
27873                .await
27874                .expect("shutdown interrupts admission");
27875            assert!(
27876                result.is_err(),
27877                "a refused operation must not appear acknowledged: {path}, {result:?}"
27878            );
27879            assert_eq!(server.request_count(path), 1);
27880            assert_eq!(
27881                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
27882                0
27883            );
27884            assert_eq!(
27885                server.request_count("/api/worker/registrations/mock-worker"),
27886                usize::from(!path.ends_with("/register"))
27887            );
27888        }
27889    }
27890
27891    #[tokio::test]
27892    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
27893        for fail in [false, true] {
27894            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27895                storage_query: true,
27896                storage_refusals: 7,
27897                storage_path: Some("/storage-query/"),
27898                ..MockWorkerBehavior::default()
27899            });
27900            let mut worker = storage_worker(&server);
27901            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
27902            let calls = Arc::new(AtomicUsize::new(0));
27903            let observed = Arc::clone(&calls);
27904            worker.register_query("storage.workflow", "state", move |_, _| {
27905                let calls = Arc::clone(&observed);
27906                async move {
27907                    calls.fetch_add(1, Ordering::SeqCst);
27908                    if fail {
27909                        Err(Error::WorkerLoop("intentional query failure".to_string()))
27910                    } else {
27911                        Ok(json!({"state":"waiting"}))
27912                    }
27913                }
27914            });
27915            assert_eq!(worker.run_once().await.expect("query settled"), 1);
27916            assert_eq!(calls.load(Ordering::SeqCst), 1);
27917            let suffix = if fail { "fail" } else { "complete" };
27918            assert_identical_requests(
27919                &server,
27920                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
27921                8,
27922            );
27923            let other = if fail { "complete" } else { "fail" };
27924            assert_eq!(
27925                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
27926                0
27927            );
27928        }
27929    }
27930
27931    #[tokio::test]
27932    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
27933        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27934            storage_refusals: 7,
27935            storage_path: Some("/poll"),
27936            unauthorized_polls: true,
27937            ..MockWorkerBehavior::default()
27938        });
27939        let error = storage_worker(&server)
27940            .run_once()
27941            .await
27942            .expect_err("auth remains terminal");
27943        assert!(matches!(
27944            error,
27945            Error::Http {
27946                status: reqwest::StatusCode::UNAUTHORIZED,
27947                ..
27948            }
27949        ));
27950        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
27951
27952        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27953            storage_refusals: 7,
27954            storage_path: Some("/activity-cancel/complete"),
27955            ..MockWorkerBehavior::default()
27956        });
27957        let worker =
27958            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
27959        let error = worker
27960            .client
27961            .complete_activity_task(
27962                "activity-cancel",
27963                "attempt-cancel",
27964                "worker",
27965                json!({}),
27966                DEFAULT_CODEC,
27967            )
27968            .await
27969            .expect_err("cancellation remains terminal");
27970        assert!(activity_task_rejection_is_final(&error));
27971        assert_identical_requests(
27972            &server,
27973            "/api/worker/activity-tasks/activity-cancel/complete",
27974            8,
27975        );
27976
27977        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27978            storage_refusals: usize::MAX,
27979            storage_path: Some("/poll"),
27980            storage_wrong_poll_id: true,
27981            ..MockWorkerBehavior::default()
27982        });
27983        assert!(storage_worker(&server).run_once().await.is_err());
27984        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
27985    }
27986
27987    #[tokio::test]
27988    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
27989        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27990            storage_refusals: usize::MAX,
27991            storage_path: Some("/poll"),
27992            ..MockWorkerBehavior::default()
27993        });
27994        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy::default());
27995        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
27996        let run = tokio::spawn(async move { worker.run().await });
27997        tokio::time::timeout(Duration::from_secs(2), async {
27998            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
27999                tokio::time::sleep(Duration::from_millis(1)).await;
28000            }
28001        })
28002        .await
28003        .expect("poll started");
28004        run.abort();
28005        assert!(run.await.expect_err("cancelled run").is_cancelled());
28006        tokio::time::sleep(Duration::from_millis(250)).await;
28007        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
28008    }
28009
28010    #[tokio::test]
28011    async fn query_protocol_rejection_from_older_server_is_typed() {
28012        let server = MockWorkerServer::reject_query_protocol();
28013        let client = Client::builder(server.base_url())
28014            .timeout(Duration::from_secs(2))
28015            .build()
28016            .expect("client");
28017
28018        let error = client
28019            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
28020            .await
28021            .expect_err("server below query protocol floor must reject");
28022        let Error::Protocol(failure) = error else {
28023            panic!("expected typed protocol failure");
28024        };
28025
28026        assert_eq!(failure.status, 400);
28027        assert_eq!(failure.reason, "unsupported_protocol_version");
28028        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
28029        assert_eq!(
28030            failure.requested_version.as_deref(),
28031            Some(WORKER_PROTOCOL_VERSION)
28032        );
28033        assert_eq!(
28034            server
28035                .worker_protocol_for("/api/worker/query-tasks/poll")
28036                .as_deref(),
28037            Some(WORKER_PROTOCOL_VERSION)
28038        );
28039    }
28040
28041    #[tokio::test]
28042    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
28043        let server = MockWorkerServer::reject_query_protocol();
28044        let client = Client::builder(server.base_url())
28045            .timeout(Duration::from_secs(2))
28046            .build()
28047            .expect("client");
28048        let mut worker = Worker::new(client, "rust-workers")
28049            .worker_id("baseline-worker")
28050            .poll_timeout(Duration::from_millis(10));
28051
28052        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
28053            Ok(Value::Null)
28054        });
28055
28056        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
28057        assert_eq!(
28058            server
28059                .worker_protocol_for("/api/worker/workflow-tasks/poll")
28060                .as_deref(),
28061            Some(WORKER_PROTOCOL_VERSION)
28062        );
28063        assert_eq!(
28064            server.worker_protocol_for("/api/worker/query-tasks/poll"),
28065            None,
28066            "a worker without query handlers must not use the query-task endpoint"
28067        );
28068    }
28069
28070    #[tokio::test]
28071    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
28072        let server = MockWorkerServer::reject_query_completion();
28073        let client = Client::builder(server.base_url())
28074            .timeout(Duration::from_secs(2))
28075            .build()
28076            .expect("client");
28077
28078        let error = client
28079            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
28080            .await
28081            .expect_err("expired completion must be rejected");
28082        let Error::QueryFailed(failure) = error else {
28083            panic!("expected typed query failure");
28084        };
28085        assert_eq!(failure.status, 409);
28086        assert_eq!(failure.reason, "query_task_timed_out");
28087
28088        let mut worker = Worker::new(client, "rust-workers")
28089            .worker_id("late-worker")
28090            .poll_timeout(Duration::from_millis(10));
28091        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28092        worker.register_query(
28093            "counter",
28094            "current",
28095            |_ctx, _args| async move { Ok(json!(8)) },
28096        );
28097
28098        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
28099        assert_eq!(
28100            worker
28101                .run_once()
28102                .await
28103                .expect("worker continues after late completion"),
28104            0
28105        );
28106        assert_eq!(
28107            server.request_count("/api/worker/query-tasks/query-late/complete"),
28108            2
28109        );
28110        assert_eq!(
28111            server.request_count("/api/worker/query-tasks/query-late/fail"),
28112            0,
28113            "a server completion rejection must not be reported as an encoding failure"
28114        );
28115    }
28116
28117    #[tokio::test]
28118    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
28119        let server = MockWorkerServer::start();
28120        let client = Client::builder(server.base_url())
28121            .timeout(Duration::from_secs(2))
28122            .build()
28123            .expect("client");
28124        let mut worker = Worker::new(client, "rust-workers")
28125            .worker_id("joined-worker")
28126            .poll_timeout(Duration::from_millis(10));
28127        worker.register_workflow(
28128            "joined.workflow",
28129            |_ctx, _input| async move { Ok(Value::Null) },
28130        );
28131        worker.register_activity(
28132            "joined.activity",
28133            |_ctx, _input| async move { Ok(Value::Null) },
28134        );
28135        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
28136            Ok(Value::Null)
28137        });
28138
28139        worker
28140            .run_until(tokio::time::sleep(Duration::from_millis(20)))
28141            .await
28142            .expect("normal shutdown");
28143
28144        let deregistration_path = "/api/worker/registrations/mock-worker";
28145        assert_eq!(server.request_count(deregistration_path), 1);
28146        for poll_path in [
28147            "/api/worker/workflow-tasks/poll",
28148            "/api/worker/activity-tasks/poll",
28149            "/api/worker/query-tasks/poll",
28150        ] {
28151            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
28152        }
28153        assert_eq!(
28154            server.captured_paths().last().map(String::as_str),
28155            Some(deregistration_path),
28156            "deregistration must start only after every poller has joined"
28157        );
28158    }
28159
28160    #[tokio::test]
28161    async fn registration_failure_does_not_deregister() {
28162        let server = MockWorkerServer::rejected_registration();
28163        let client = Client::builder(server.base_url())
28164            .timeout(Duration::from_secs(2))
28165            .build()
28166            .expect("client");
28167        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
28168
28169        let error = worker
28170            .run_until(async {})
28171            .await
28172            .expect_err("registration must fail");
28173        assert!(matches!(
28174            error,
28175            Error::Http {
28176                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
28177                ..
28178            }
28179        ));
28180        assert!(server
28181            .captured_paths()
28182            .iter()
28183            .all(|path| !path.starts_with("/api/worker/registrations/")));
28184    }
28185
28186    #[tokio::test]
28187    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
28188        let server = MockWorkerServer::rejected_registration_protocol();
28189        let client = Client::builder(server.base_url())
28190            .timeout(Duration::from_secs(2))
28191            .build()
28192            .expect("client");
28193        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
28194
28195        let error = worker
28196            .run_until(async {})
28197            .await
28198            .expect_err("a protocol 1.16 server must reject this worker");
28199        let Error::Protocol(failure) = error else {
28200            panic!("expected typed protocol rejection");
28201        };
28202        assert_eq!(failure.reason, "unsupported_protocol_version");
28203        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
28204        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
28205        assert_eq!(
28206            server
28207                .worker_protocol_for("/api/worker/register")
28208                .as_deref(),
28209            Some(WORKER_PROTOCOL_VERSION)
28210        );
28211    }
28212
28213    #[tokio::test]
28214    async fn declined_registration_does_not_deregister() {
28215        let server = MockWorkerServer::declined_registration();
28216        let client = Client::builder(server.base_url())
28217            .timeout(Duration::from_secs(2))
28218            .build()
28219            .expect("client");
28220        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
28221
28222        let error = worker
28223            .run_until(async {})
28224            .await
28225            .expect_err("declined registration must fail");
28226        assert!(matches!(error, Error::WorkerLoop(_)));
28227        assert!(error.to_string().contains("was not accepted"));
28228        assert!(server
28229            .captured_paths()
28230            .iter()
28231            .all(|path| !path.starts_with("/api/worker/registrations/")));
28232    }
28233
28234    #[tokio::test]
28235    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
28236        let server = MockWorkerServer::rejected_deregistration();
28237        let client = Client::builder(server.base_url())
28238            .timeout(Duration::from_secs(2))
28239            .build()
28240            .expect("client");
28241        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
28242
28243        let error = worker
28244            .run_until(async {})
28245            .await
28246            .expect_err("deregistration must fail");
28247        assert!(matches!(
28248            error,
28249            Error::Http {
28250                status: reqwest::StatusCode::FORBIDDEN,
28251                ..
28252            }
28253        ));
28254        assert_eq!(
28255            server.request_count("/api/worker/registrations/mock-worker"),
28256            1
28257        );
28258    }
28259
28260    #[tokio::test]
28261    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
28262        let server = MockWorkerServer::rejected_deregistration_protocol();
28263        let client = Client::builder(server.base_url())
28264            .timeout(Duration::from_secs(2))
28265            .build()
28266            .expect("client");
28267        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
28268
28269        let error = worker
28270            .run_until(async {})
28271            .await
28272            .expect_err("protocol rejection must fail shutdown");
28273        let Error::Protocol(failure) = error else {
28274            panic!("expected typed protocol failure");
28275        };
28276        assert_eq!(failure.reason, "unsupported_protocol_version");
28277        assert_eq!(
28278            failure.requested_version.as_deref(),
28279            Some(WORKER_PROTOCOL_VERSION)
28280        );
28281        assert_eq!(
28282            server.request_count("/api/worker/registrations/mock-worker"),
28283            1
28284        );
28285    }
28286
28287    #[tokio::test]
28288    async fn primary_poller_error_retains_deregistration_failure_context() {
28289        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
28290        let client = Client::builder(server.base_url())
28291            .timeout(Duration::from_secs(2))
28292            .build()
28293            .expect("client");
28294        let mut worker = Worker::new(client, "rust-workers")
28295            .worker_id("combined-failure")
28296            .poll_timeout(Duration::from_millis(10));
28297        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
28298            Ok(Value::Null)
28299        });
28300
28301        let error = worker
28302            .run()
28303            .await
28304            .expect_err("worker and cleanup must fail");
28305        let summary = error.to_string();
28306        assert!(summary.contains("authentication_failed"));
28307        assert!(summary.contains("worker cannot deregister"));
28308        let Error::WorkerShutdown {
28309            primary,
28310            deregistration,
28311        } = error
28312        else {
28313            panic!("expected combined worker shutdown error");
28314        };
28315        assert!(matches!(
28316            *primary,
28317            Error::Http {
28318                status: reqwest::StatusCode::UNAUTHORIZED,
28319                ..
28320            }
28321        ));
28322        assert!(matches!(
28323            *deregistration,
28324            Error::Http {
28325                status: reqwest::StatusCode::FORBIDDEN,
28326                ..
28327            }
28328        ));
28329        assert_eq!(
28330            server.request_count("/api/worker/registrations/mock-worker"),
28331            1
28332        );
28333    }
28334
28335    #[tokio::test]
28336    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
28337        let server = MockWorkerServer::start();
28338        let client = Client::builder(server.base_url())
28339            .timeout(Duration::from_secs(2))
28340            .build()
28341            .expect("client");
28342        let mut worker = Worker::new(client, "rust-workers")
28343            .worker_id("activity-only-worker")
28344            .poll_timeout(Duration::from_millis(10));
28345
28346        worker.register_activity(
28347            "activity.only",
28348            |_ctx, _args| async move { Ok(Value::Null) },
28349        );
28350
28351        worker.run_until(async {}).await.expect("run worker");
28352    }
28353
28354    #[tokio::test]
28355    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
28356        let server = MockWorkerServer::start();
28357        let client = Client::builder(server.base_url())
28358            .timeout(Duration::from_secs(2))
28359            .build()
28360            .expect("client");
28361        let mut worker = Worker::new(client, "rust-workers")
28362            .worker_id("workflow-only-worker")
28363            .poll_timeout(Duration::from_millis(10));
28364
28365        worker.register_workflow(
28366            "workflow.only",
28367            |_ctx, _input| async move { Ok(Value::Null) },
28368        );
28369
28370        worker.run_until(async {}).await.expect("run worker");
28371    }
28372
28373    #[tokio::test]
28374    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
28375        let server = MockWorkerServer::start();
28376        let client = Client::builder(server.base_url())
28377            .timeout(Duration::from_secs(2))
28378            .build()
28379            .expect("client");
28380        let observations = Arc::new(Mutex::new(Vec::new()));
28381        let observed = Arc::clone(&observations);
28382        let mut worker = Worker::new(client, "rust-workers")
28383            .worker_id("observed-heartbeat-worker")
28384            .poll_timeout(Duration::from_millis(10))
28385            .on_worker_heartbeat(move |observation| {
28386                observed
28387                    .lock()
28388                    .expect("heartbeat observations")
28389                    .push(observation.clone());
28390            });
28391
28392        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
28393            Ok(Value::Null)
28394        });
28395        let acknowledged = Arc::clone(&observations);
28396        worker
28397            .run_until(async move {
28398                tokio::time::timeout(Duration::from_secs(2), async move {
28399                    loop {
28400                        if !acknowledged
28401                            .lock()
28402                            .expect("heartbeat observations")
28403                            .is_empty()
28404                        {
28405                            break;
28406                        }
28407                        tokio::time::sleep(Duration::from_millis(1)).await;
28408                    }
28409                })
28410                .await
28411                .expect("heartbeat acknowledgement within timeout");
28412            })
28413            .await
28414            .expect("run worker");
28415
28416        let observations = observations.lock().expect("heartbeat observations");
28417        let first = observations.first().expect("heartbeat acknowledgement");
28418        assert_eq!(first.worker_id, "observed-heartbeat-worker");
28419        assert_eq!(first.task_queue, "rust-workers");
28420        assert!(first.acknowledged_at_unix_millis > 0);
28421        assert_eq!(first.acknowledgement, json!({}));
28422    }
28423
28424    #[tokio::test]
28425    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
28426        let server = MockWorkerServer::delayed_heartbeat_worker();
28427        let client = Client::builder(server.base_url())
28428            .timeout(Duration::from_secs(3))
28429            .build()
28430            .expect("client");
28431        let observations = Arc::new(Mutex::new(Vec::new()));
28432        let observed = Arc::clone(&observations);
28433        let mut worker = Worker::new(client, "rust-snapshot-workers")
28434            .worker_id("rust-snapshot-worker")
28435            .poll_timeout(Duration::from_millis(10))
28436            .on_worker_heartbeat(move |observation| {
28437                observed
28438                    .lock()
28439                    .expect("heartbeat observations")
28440                    .push(observation.clone());
28441            });
28442
28443        worker.register_workflow("snapshot", |ctx, _input| async move {
28444            ctx.wait_signal("finish").await?;
28445            Ok(json!({"status": "finished"}))
28446        });
28447        worker.register_query("snapshot", "current", |ctx, _args| async move {
28448            Ok(json!(ctx
28449                .signals("increment")
28450                .iter()
28451                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28452                .sum::<i64>()))
28453        });
28454        worker.register_activity("cancel-aware", |_ctx, _args| async move {
28455            Ok(json!({"late": "completion"}))
28456        });
28457
28458        worker
28459            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
28460            .await
28461            .expect("delayed heartbeat must allow a clean worker shutdown");
28462
28463        let observations = observations.lock().expect("heartbeat observations");
28464        assert!(
28465            observations.len() >= 3,
28466            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
28467        );
28468        assert!(
28469            observations.windows(2).all(|pair| {
28470                pair[1].acknowledged_at_unix_millis
28471                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28472                    >= 850
28473            }),
28474            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
28475        );
28476        drop(observations);
28477
28478        let heartbeat_times = server.request_times("/api/worker/heartbeat");
28479        let delayed_request_at = *heartbeat_times
28480            .get(1)
28481            .expect("intentionally delayed heartbeat request");
28482        let delay_window_start = delayed_request_at + Duration::from_millis(100);
28483        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
28484        for path in [
28485            "/api/worker/workflow-tasks/poll",
28486            "/api/worker/activity-tasks/poll",
28487            "/api/worker/query-tasks/poll",
28488        ] {
28489            assert!(
28490                server
28491                    .request_times(path)
28492                    .iter()
28493                    .any(|received_at| *received_at >= delay_window_start
28494                        && *received_at <= delay_window_end),
28495                "{path} must keep polling while a heartbeat acknowledgement is delayed"
28496            );
28497        }
28498        assert!(
28499            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
28500            "workflow work must be settled"
28501        );
28502        assert!(
28503            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
28504            "activity work must be settled"
28505        );
28506        assert!(
28507            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
28508            "query work must be settled"
28509        );
28510    }
28511
28512    #[tokio::test]
28513    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
28514        let server = MockWorkerServer::heartbeat_retry_worker();
28515        let client = Client::builder(server.base_url())
28516            .timeout(Duration::from_secs(2))
28517            .build()
28518            .expect("client");
28519        let observations = Arc::new(Mutex::new(Vec::new()));
28520        let observed = Arc::clone(&observations);
28521        let worker = Worker::new(client, "rust-workers")
28522            .worker_id("heartbeat-retry-worker")
28523            .retry_policy(WorkerRetryPolicy {
28524                max_retries: 1,
28525                initial_backoff: Duration::from_millis(300),
28526                max_backoff: Duration::from_millis(300),
28527            })
28528            .on_worker_heartbeat(move |observation| {
28529                observed
28530                    .lock()
28531                    .expect("heartbeat observations")
28532                    .push(observation.clone());
28533            });
28534
28535        worker
28536            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
28537            .await
28538            .expect("retryable heartbeat failure must remain bounded and recover");
28539
28540        let observations = observations.lock().expect("heartbeat observations");
28541        assert!(observations.len() >= 3, "heartbeat retry must recover");
28542        assert!(
28543            observations.windows(2).all(|pair| {
28544                pair[1]
28545                    .acknowledged_at_unix_millis
28546                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
28547                    >= 850
28548            }),
28549            "a successful retry must start a fresh advertised cadence: {observations:?}"
28550        );
28551        assert_eq!(
28552            server.request_count("/api/worker/heartbeat"),
28553            observations.len() + 1,
28554            "one retryable failure must add exactly one bounded request"
28555        );
28556    }
28557
28558    #[tokio::test]
28559    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
28560        let server = MockWorkerServer::waiting_query_worker();
28561        let client = Client::builder(server.base_url())
28562            .timeout(Duration::from_secs(2))
28563            .build()
28564            .expect("client");
28565        let observations = Arc::new(Mutex::new(Vec::new()));
28566        let observed = Arc::clone(&observations);
28567        let mut worker = Worker::new(client, "rust-snapshot-workers")
28568            .worker_id("rust-snapshot-worker")
28569            .poll_timeout(Duration::from_millis(10))
28570            .on_worker_heartbeat(move |observation| {
28571                observed
28572                    .lock()
28573                    .expect("heartbeat observations")
28574                    .push(observation.clone());
28575            });
28576
28577        worker.register_workflow("snapshot", |ctx, _input| async move {
28578            ctx.wait_signal("finish").await?;
28579            Ok(json!({"status": "finished"}))
28580        });
28581        worker.register_query("snapshot", "current", |ctx, _args| async move {
28582            let current = ctx
28583                .signals("increment")
28584                .iter()
28585                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
28586                .sum::<i64>();
28587            Ok(json!(current))
28588        });
28589        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
28590        worker
28591            .declare_workflow_signals("snapshot", &["finish"])
28592            .expect("declare finish signal");
28593
28594        worker
28595            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
28596            .await
28597            .expect("pending workflow and query poller must remain live until shutdown");
28598
28599        assert!(
28600            observations.lock().expect("heartbeat observations").len() >= 4,
28601            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
28602        );
28603        assert!(
28604            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
28605            "workflow polling must continue after empty replay acknowledgements"
28606        );
28607        assert!(
28608            server.request_count("/api/worker/query-tasks/poll") >= 2,
28609            "query polling must continue after serving the current query"
28610        );
28611        assert_eq!(
28612            server.request_body("/api/worker/register")["capabilities"],
28613            json!([
28614                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
28615                DURABLE_SELECTION_CAPABILITY,
28616                MEMO_UPSERTS_CAPABILITY,
28617                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
28618                QUERY_TASKS_CAPABILITY,
28619                WORKFLOW_UPDATES_CAPABILITY,
28620                MESSAGE_STREAMS_CAPABILITY
28621            ])
28622        );
28623        assert_eq!(
28624            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
28625            json!({
28626                "queries": ["current"],
28627                "query_contracts": [{
28628                    "name": "current",
28629                    "parameters": [{
28630                        "name": "args", "position": 0, "required": false,
28631                        "variadic": true, "type": null, "allows_null": true,
28632                        "default_available": false, "default": null,
28633                    }],
28634                }],
28635                "signals": ["finish"],
28636                "signal_contracts": [{
28637                    "name": "finish",
28638                    "parameters": [{
28639                        "name": "args", "position": 0, "required": false,
28640                        "variadic": true, "type": null, "allows_null": true,
28641                        "default_available": false, "default": null,
28642                    }],
28643                }],
28644                "updates": ["replace"],
28645                "update_contracts": [{
28646                    "name": "replace",
28647                    "parameters": [{
28648                        "name": "args", "position": 0, "required": false,
28649                        "variadic": true, "type": null, "allows_null": true,
28650                        "default_available": false, "default": null,
28651                    }],
28652                }],
28653                "update_validators": [],
28654            })
28655        );
28656
28657        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
28658        assert_eq!(
28659            opened["commands"],
28660            json!([{
28661                "type": "open_signal_wait",
28662                "signal_name": "finish",
28663            }])
28664        );
28665
28666        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
28667            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
28668            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
28669            let failure = server.request_body(&fail_path);
28670            assert_eq!(
28671                failure["failure"]["type"],
28672                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
28673            );
28674            assert_eq!(server.request_count(&completion_path), 0);
28675        }
28676
28677        let query_completion =
28678            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
28679        assert_eq!(query_completion["result"], json!(8));
28680
28681        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
28682        assert_eq!(
28683            server.request_count(terminal_path),
28684            1,
28685            "the matching signal must settle the workflow exactly once"
28686        );
28687        let terminal = server.request_body(terminal_path);
28688        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
28689        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
28690        assert_eq!(
28691            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
28692                .expect("terminal workflow result"),
28693            json!({"status": "finished"})
28694        );
28695    }
28696
28697    #[tokio::test]
28698    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
28699        let server = MockWorkerServer::transient_worker_failures();
28700        let client = Client::builder(server.base_url())
28701            .timeout(Duration::from_secs(2))
28702            .build()
28703            .expect("client");
28704        let mut worker = Worker::new(client, "rust-workers")
28705            .worker_id("retry-worker")
28706            .poll_timeout(Duration::from_millis(10))
28707            .retry_policy(WorkerRetryPolicy {
28708                max_retries: 2,
28709                initial_backoff: Duration::from_millis(1),
28710                max_backoff: Duration::from_millis(1),
28711            });
28712        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28713        worker.register_activity(
28714            "counter.activity",
28715            |_ctx, _input| async move { Ok(Value::Null) },
28716        );
28717        worker.register_query(
28718            "counter",
28719            "current",
28720            |_ctx, _args| async move { Ok(json!(8)) },
28721        );
28722
28723        worker
28724            .run_until(tokio::time::sleep(Duration::from_millis(75)))
28725            .await
28726            .expect("transient failures must not stop the worker");
28727
28728        for path in [
28729            "/api/worker/heartbeat",
28730            "/api/worker/workflow-tasks/poll",
28731            "/api/worker/activity-tasks/poll",
28732            "/api/worker/query-tasks/poll",
28733        ] {
28734            assert!(
28735                server.request_count(path) >= 2,
28736                "{path} must continue after its transient failure"
28737            );
28738        }
28739    }
28740
28741    #[tokio::test]
28742    async fn worker_continues_after_long_poll_capacity_backpressure() {
28743        let server = MockWorkerServer::capacity_limited_activity_poll();
28744        let client = Client::builder(server.base_url())
28745            .timeout(Duration::from_secs(2))
28746            .build()
28747            .expect("client");
28748        let mut worker = Worker::new(client, "rust-workers")
28749            .worker_id("capacity-worker")
28750            .poll_timeout(Duration::from_millis(10))
28751            .retry_policy(WorkerRetryPolicy {
28752                max_retries: 0,
28753                initial_backoff: Duration::from_millis(1),
28754                max_backoff: Duration::from_millis(1),
28755            });
28756        worker.register_activity("capacity.activity", |_ctx, _input| async move {
28757            Ok(json!({"handled": true}))
28758        });
28759
28760        worker
28761            .run_until(tokio::time::sleep(Duration::from_millis(50)))
28762            .await
28763            .expect("capacity backpressure must not stop the worker");
28764
28765        assert!(
28766            server.request_count("/api/worker/activity-tasks/poll") >= 2,
28767            "the activity poller must continue after capacity backpressure"
28768        );
28769        assert_eq!(
28770            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
28771            1,
28772            "the worker must complete work returned after capacity recovers"
28773        );
28774    }
28775
28776    #[test]
28777    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
28778        let capacity = Error::Http {
28779            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28780            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
28781        };
28782        assert_eq!(
28783            worker_poll_capacity_retry_after(&capacity),
28784            Some(Duration::from_secs(3))
28785        );
28786
28787        let rejected_capacity = Error::Http {
28788            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28789            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
28790        };
28791        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
28792        assert!(!worker_operation_is_retryable(&rejected_capacity));
28793
28794        let ordinary_rate_limit = Error::Http {
28795            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
28796            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
28797                .to_string(),
28798        };
28799        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
28800        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
28801    }
28802
28803    #[tokio::test]
28804    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
28805        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28806            poll_failures_per_path: 8,
28807            heartbeat_failures: 8,
28808            ..MockWorkerBehavior::default()
28809        });
28810        let client = Client::builder(server.base_url())
28811            .timeout(Duration::from_secs(2))
28812            .build()
28813            .expect("client");
28814        let acknowledgements = Arc::new(AtomicUsize::new(0));
28815        let observed = Arc::clone(&acknowledgements);
28816        let mut worker = Worker::new(client, "rust-workers")
28817            .recover_transient_outages(true)
28818            .poll_timeout(Duration::from_millis(10))
28819            .retry_policy(WorkerRetryPolicy {
28820                max_retries: 2,
28821                initial_backoff: Duration::from_millis(2),
28822                max_backoff: Duration::from_millis(5),
28823            })
28824            .on_worker_heartbeat(move |_| {
28825                observed.fetch_add(1, Ordering::SeqCst);
28826            });
28827        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28828        worker.register_activity(
28829            "counter.activity",
28830            |_ctx, _input| async move { Ok(Value::Null) },
28831        );
28832        worker.register_query("counter", "current", |_ctx, _args| async move {
28833            Ok(Value::Null)
28834        });
28835
28836        worker
28837            .run_until(tokio::time::sleep(Duration::from_millis(500)))
28838            .await
28839            .expect("a recoverable outage must not stop the service worker");
28840
28841        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
28842        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
28843        for path in [
28844            "/api/worker/workflow-tasks/poll",
28845            "/api/worker/activity-tasks/poll",
28846            "/api/worker/query-tasks/poll",
28847        ] {
28848            let bodies = server.request_bodies(path);
28849            assert!(bodies.len() >= 10, "{path} must resume after recovery");
28850            let first = &bodies[0]["poll_request_id"];
28851            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
28852            for body in &bodies[..9] {
28853                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
28854            }
28855            assert_ne!(&bodies[9]["poll_request_id"], first);
28856            let times = server.request_times(path);
28857            for pair in times[..9].windows(2) {
28858                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
28859            }
28860        }
28861    }
28862
28863    #[tokio::test]
28864    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
28865        for heartbeat_outage in [false, true] {
28866            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28867                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
28868                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
28869                ..MockWorkerBehavior::default()
28870            });
28871            let client = Client::builder(server.base_url()).build().expect("client");
28872            let mut worker = Worker::new(client, "rust-workers")
28873                .recover_transient_outages(true)
28874                .retry_policy(WorkerRetryPolicy {
28875                    max_retries: 1,
28876                    initial_backoff: Duration::from_secs(5),
28877                    max_backoff: Duration::from_secs(5),
28878                });
28879            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28880            let started = Instant::now();
28881            worker
28882                .run_until(tokio::time::sleep(Duration::from_millis(200)))
28883                .await
28884                .expect("shutdown during an outage is a normal stop");
28885            assert!(started.elapsed() < Duration::from_secs(1));
28886            let path = if heartbeat_outage {
28887                "/api/worker/heartbeat"
28888            } else {
28889                "/api/worker/workflow-tasks/poll"
28890            };
28891            assert_eq!(server.request_count(path), 1);
28892            assert_eq!(
28893                server.request_count("/api/worker/registrations/mock-worker"),
28894                1
28895            );
28896        }
28897    }
28898
28899    #[tokio::test]
28900    async fn worker_outage_recovery_keeps_run_once_bounded() {
28901        let server = MockWorkerServer::unavailable_polls();
28902        let client = Client::builder(server.base_url()).build().expect("client");
28903        let mut worker = Worker::new(client, "rust-workers")
28904            .recover_transient_outages(true)
28905            .retry_policy(WorkerRetryPolicy {
28906                max_retries: 2,
28907                initial_backoff: Duration::from_millis(1),
28908                max_backoff: Duration::from_millis(1),
28909            });
28910        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28911        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
28912        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
28913    }
28914
28915    #[tokio::test]
28916    async fn worker_outage_recovery_respects_disabled_retries() {
28917        let server = MockWorkerServer::unavailable_polls();
28918        let client = Client::builder(server.base_url()).build().expect("client");
28919        let mut worker = Worker::new(client, "rust-workers")
28920            .recover_transient_outages(true)
28921            .retry_policy(WorkerRetryPolicy {
28922                max_retries: 0,
28923                ..WorkerRetryPolicy::default()
28924            });
28925        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28926        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
28927        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28928    }
28929
28930    #[tokio::test]
28931    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
28932        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28933            heartbeat_failures: usize::MAX,
28934            unauthorized_polls: true,
28935            ..MockWorkerBehavior::default()
28936        });
28937        let client = Client::builder(server.base_url()).build().expect("client");
28938        let mut worker = Worker::new(client, "rust-workers")
28939            .recover_transient_outages(true)
28940            .retry_policy(WorkerRetryPolicy {
28941                max_retries: 1,
28942                initial_backoff: Duration::from_secs(5),
28943                max_backoff: Duration::from_secs(5),
28944            });
28945        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28946        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
28947            .await
28948            .expect("fatal poll errors must interrupt heartbeat recovery")
28949            .expect_err("authentication failure is terminal");
28950        assert!(
28951            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
28952        );
28953        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
28954    }
28955
28956    #[tokio::test]
28957    async fn worker_bounds_transport_retries() {
28958        let server = MockWorkerServer::unavailable_polls();
28959        let client = Client::builder(server.base_url())
28960            .timeout(Duration::from_secs(2))
28961            .build()
28962            .expect("client");
28963        let mut worker = Worker::new(client, "rust-workers")
28964            .worker_id("bounded-retry-worker")
28965            .poll_timeout(Duration::from_millis(10))
28966            .retry_policy(WorkerRetryPolicy {
28967                max_retries: 2,
28968                initial_backoff: Duration::from_millis(1),
28969                max_backoff: Duration::from_millis(1),
28970            });
28971        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28972
28973        let error = worker.run().await.expect_err("retry bound must terminate");
28974        assert!(matches!(error, Error::Transport(_)));
28975        assert_eq!(
28976            server.request_count("/api/worker/workflow-tasks/poll"),
28977            3,
28978            "one initial request plus exactly two retries"
28979        );
28980    }
28981
28982    #[tokio::test]
28983    async fn worker_retry_policy_can_disable_poll_retries() {
28984        let server = MockWorkerServer::unavailable_polls();
28985        let client = Client::builder(server.base_url())
28986            .timeout(Duration::from_secs(2))
28987            .build()
28988            .expect("client");
28989        let mut worker = Worker::new(client, "rust-workers")
28990            .worker_id("no-retry-worker")
28991            .poll_timeout(Duration::from_millis(10))
28992            .retry_policy(WorkerRetryPolicy {
28993                max_retries: 0,
28994                initial_backoff: Duration::from_millis(1),
28995                max_backoff: Duration::from_millis(1),
28996            });
28997        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
28998
28999        let error = worker
29000            .run_once()
29001            .await
29002            .expect_err("disabled retries must return the first transport failure");
29003        assert!(matches!(error, Error::Transport(_)));
29004        assert_eq!(
29005            server.request_count("/api/worker/workflow-tasks/poll"),
29006            1,
29007            "max_retries=0 must send only the initial request"
29008        );
29009    }
29010
29011    #[tokio::test]
29012    async fn worker_does_not_retry_authentication_failures() {
29013        let server = MockWorkerServer::unauthorized_polls();
29014        let client = Client::builder(server.base_url())
29015            .timeout(Duration::from_secs(2))
29016            .build()
29017            .expect("client");
29018        let mut worker = Worker::new(client, "rust-workers")
29019            .worker_id("unauthorized-worker")
29020            .recover_transient_outages(true)
29021            .poll_timeout(Duration::from_millis(10));
29022        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29023
29024        let error = worker
29025            .run()
29026            .await
29027            .expect_err("authentication must terminate");
29028        let Error::Http { status, body } = error else {
29029            panic!("expected stable HTTP authentication error");
29030        };
29031        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
29032        assert!(body.contains("authentication_failed"));
29033        assert_eq!(
29034            server.request_count("/api/worker/workflow-tasks/poll"),
29035            1,
29036            "authentication failures must not be retried"
29037        );
29038    }
29039
29040    #[test]
29041    fn duplicate_registration_keeps_the_original_workflow() {
29042        let client = Client::new("http://127.0.0.1:9").expect("client");
29043        let mut worker = Worker::new(client, "registration-tests");
29044        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29045        let original = Arc::clone(&worker.workflows["same"].execute);
29046        worker
29047            .set_workflow_definition_sources("same", &["first workflow source"])
29048            .expect("source identity");
29049        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
29050        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
29051        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
29052        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
29053    }
29054
29055    #[test]
29056    fn duplicate_registration_keeps_the_original_activity() {
29057        let client = Client::new("http://127.0.0.1:9").expect("client");
29058        let mut worker = Worker::new(client, "registration-tests");
29059        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
29060        let original = Arc::clone(&worker.activities["same"]);
29061        worker.register_activity_avro_value("same", |_ctx, _input| async {
29062            Ok(AvroValue::String("second".into()))
29063        });
29064        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
29065    }
29066
29067    #[test]
29068    fn duplicate_registration_keeps_original_query_and_update_handlers() {
29069        let client = Client::new("http://127.0.0.1:9").expect("client");
29070        let mut worker = Worker::new(client, "registration-tests");
29071        worker.register_query("orders", "same", |_ctx, _input| async {
29072            Ok(json!("first"))
29073        });
29074        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
29075            panic!("snapshot query");
29076        };
29077        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
29078            Ok(json!("second"))
29079        });
29080        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
29081            panic!("duplicate replaced the query adapter");
29082        };
29083        assert!(Arc::ptr_eq(&original, retained));
29084        worker.register_update("orders", "same", |_ctx, _input| async {
29085            Ok(json!("first"))
29086        });
29087        let original = Arc::clone(&worker.updates["orders"]["same"]);
29088        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
29089            Ok(AvroValue::Null)
29090        });
29091        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
29092    }
29093
29094    #[tokio::test]
29095    async fn duplicate_registration_fails_before_server_contact() {
29096        let server = MockWorkerServer::start();
29097        let client = Client::builder(server.base_url()).build().expect("client");
29098        let mut worker =
29099            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
29100        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
29101        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
29102        let error = worker
29103            .run_once()
29104            .await
29105            .expect_err("ambiguous worker must not poll");
29106        assert!(
29107            error.to_string().contains("duplicate_registration"),
29108            "{error}"
29109        );
29110        assert!(server.requests.lock().expect("requests").is_empty());
29111    }
29112
29113    #[derive(Clone, Debug)]
29114    struct CapturedRequest {
29115        headers: String,
29116        method: String,
29117        path: String,
29118        authorization: Option<String>,
29119        namespace: Option<String>,
29120        worker_protocol: Option<String>,
29121        control_protocol: Option<String>,
29122        body: String,
29123        received_at: Instant,
29124    }
29125
29126    struct MockWorkerServer {
29127        addr: SocketAddr,
29128        stop: Arc<AtomicBool>,
29129        requests: Arc<Mutex<Vec<CapturedRequest>>>,
29130        thread: Option<thread::JoinHandle<()>>,
29131    }
29132
29133    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
29134
29135    #[derive(Clone, Copy, Default)]
29136    struct MockWorkerBehavior {
29137        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
29138        request_override: Option<RequestOverride>,
29139        storage_refusals: usize,
29140        storage_path: Option<&'static str>,
29141        storage_unavailable: bool,
29142        storage_mid_poll: bool,
29143        storage_activity: bool,
29144        storage_query: bool,
29145        storage_wrong_poll_id: bool,
29146        reject_query_protocol: bool,
29147        reject_query_completion: bool,
29148        waiting_query_worker: bool,
29149        decline_registration: bool,
29150        complete_named_signal: bool,
29151        poll_failures_per_path: usize,
29152        long_poll_capacity_responses_per_path: usize,
29153        heartbeat_failures: usize,
29154        heartbeat_failure_request: Option<usize>,
29155        delayed_heartbeat_request: Option<usize>,
29156        heartbeat_response_delay: Duration,
29157        concurrent_requests: bool,
29158        unauthorized_polls: bool,
29159        reject_registration: bool,
29160        reject_registration_protocol: bool,
29161        reject_deregistration: bool,
29162        reject_deregistration_protocol: bool,
29163        cancelled_activity: bool,
29164        draining_polls: bool,
29165        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
29166        workflow_completion_status: Option<&'static str>,
29167        workflow_completion_body: Option<&'static str>,
29168    }
29169
29170    impl MockWorkerServer {
29171        fn start() -> Self {
29172            Self::start_with_behavior(MockWorkerBehavior::default())
29173        }
29174
29175        fn reject_query_protocol() -> Self {
29176            Self::start_with_behavior(MockWorkerBehavior {
29177                reject_query_protocol: true,
29178                ..MockWorkerBehavior::default()
29179            })
29180        }
29181
29182        fn reject_query_completion() -> Self {
29183            Self::start_with_behavior(MockWorkerBehavior {
29184                reject_query_completion: true,
29185                ..MockWorkerBehavior::default()
29186            })
29187        }
29188
29189        fn waiting_query_worker() -> Self {
29190            Self::start_with_behavior(MockWorkerBehavior {
29191                waiting_query_worker: true,
29192                complete_named_signal: true,
29193                ..MockWorkerBehavior::default()
29194            })
29195        }
29196
29197        fn transient_worker_failures() -> Self {
29198            Self::start_with_behavior(MockWorkerBehavior {
29199                poll_failures_per_path: 1,
29200                heartbeat_failures: 1,
29201                ..MockWorkerBehavior::default()
29202            })
29203        }
29204
29205        fn consecutive_poll_failures(count: usize) -> Self {
29206            Self::start_with_behavior(MockWorkerBehavior {
29207                poll_failures_per_path: count,
29208                ..MockWorkerBehavior::default()
29209            })
29210        }
29211
29212        fn capacity_limited_activity_poll() -> Self {
29213            Self::start_with_behavior(MockWorkerBehavior {
29214                long_poll_capacity_responses_per_path: 1,
29215                ..MockWorkerBehavior::default()
29216            })
29217        }
29218
29219        fn delayed_heartbeat_worker() -> Self {
29220            Self::start_with_behavior(MockWorkerBehavior {
29221                waiting_query_worker: true,
29222                delayed_heartbeat_request: Some(2),
29223                heartbeat_response_delay: Duration::from_millis(1_500),
29224                concurrent_requests: true,
29225                cancelled_activity: true,
29226                ..MockWorkerBehavior::default()
29227            })
29228        }
29229
29230        fn heartbeat_retry_worker() -> Self {
29231            Self::start_with_behavior(MockWorkerBehavior {
29232                waiting_query_worker: true,
29233                heartbeat_failure_request: Some(2),
29234                concurrent_requests: true,
29235                ..MockWorkerBehavior::default()
29236            })
29237        }
29238
29239        fn unavailable_polls() -> Self {
29240            Self::start_with_behavior(MockWorkerBehavior {
29241                poll_failures_per_path: usize::MAX,
29242                ..MockWorkerBehavior::default()
29243            })
29244        }
29245
29246        fn unauthorized_polls() -> Self {
29247            Self::start_with_behavior(MockWorkerBehavior {
29248                unauthorized_polls: true,
29249                ..MockWorkerBehavior::default()
29250            })
29251        }
29252
29253        fn rejected_registration() -> Self {
29254            Self::start_with_behavior(MockWorkerBehavior {
29255                reject_registration: true,
29256                ..MockWorkerBehavior::default()
29257            })
29258        }
29259
29260        fn rejected_registration_protocol() -> Self {
29261            Self::start_with_behavior(MockWorkerBehavior {
29262                reject_registration_protocol: true,
29263                ..MockWorkerBehavior::default()
29264            })
29265        }
29266
29267        fn declined_registration() -> Self {
29268            Self::start_with_behavior(MockWorkerBehavior {
29269                decline_registration: true,
29270                ..MockWorkerBehavior::default()
29271            })
29272        }
29273
29274        fn rejected_deregistration() -> Self {
29275            Self::start_with_behavior(MockWorkerBehavior {
29276                reject_deregistration: true,
29277                ..MockWorkerBehavior::default()
29278            })
29279        }
29280
29281        fn rejected_deregistration_protocol() -> Self {
29282            Self::start_with_behavior(MockWorkerBehavior {
29283                reject_deregistration_protocol: true,
29284                ..MockWorkerBehavior::default()
29285            })
29286        }
29287
29288        fn unauthorized_polls_and_rejected_deregistration() -> Self {
29289            Self::start_with_behavior(MockWorkerBehavior {
29290                unauthorized_polls: true,
29291                reject_deregistration: true,
29292                ..MockWorkerBehavior::default()
29293            })
29294        }
29295
29296        fn cancelled_activity() -> Self {
29297            Self::start_with_behavior(MockWorkerBehavior {
29298                cancelled_activity: true,
29299                ..MockWorkerBehavior::default()
29300            })
29301        }
29302
29303        fn draining_polls() -> Self {
29304            Self::start_with_behavior(MockWorkerBehavior {
29305                draining_polls: true,
29306                ..MockWorkerBehavior::default()
29307            })
29308        }
29309
29310        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
29311            Self::start_with_behavior(MockWorkerBehavior {
29312                invalid_task_payload_codec: Some(codec),
29313                ..MockWorkerBehavior::default()
29314            })
29315        }
29316
29317        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
29318            Self::start_with_behavior(MockWorkerBehavior {
29319                workflow_completion_status: Some(status),
29320                workflow_completion_body: Some(body),
29321                ..MockWorkerBehavior::default()
29322            })
29323        }
29324
29325        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
29326            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
29327            listener
29328                .set_nonblocking(true)
29329                .expect("configure mock listener");
29330            let addr = listener.local_addr().expect("mock server address");
29331            let stop = Arc::new(AtomicBool::new(false));
29332            let server_stop = Arc::clone(&stop);
29333            let requests = Arc::new(Mutex::new(Vec::new()));
29334            let server_requests = Arc::clone(&requests);
29335            let thread = thread::spawn(move || {
29336                let mut request_threads = Vec::new();
29337                while !server_stop.load(Ordering::SeqCst) {
29338                    match listener.accept() {
29339                        Ok((mut stream, _)) => {
29340                            if behavior.concurrent_requests {
29341                                let requests = Arc::clone(&server_requests);
29342                                request_threads.push(thread::spawn(move || {
29343                                    handle_mock_worker_request(&mut stream, &requests, behavior)
29344                                }));
29345                            } else {
29346                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
29347                            }
29348                        }
29349                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
29350                            let mut index = 0;
29351                            while index < request_threads.len() {
29352                                if request_threads[index].is_finished() {
29353                                    request_threads
29354                                        .swap_remove(index)
29355                                        .join()
29356                                        .expect("join mock request");
29357                                } else {
29358                                    index += 1;
29359                                }
29360                            }
29361                            thread::sleep(Duration::from_millis(5));
29362                        }
29363                        Err(_) => break,
29364                    }
29365                }
29366                for request_thread in request_threads {
29367                    request_thread.join().expect("join mock request");
29368                }
29369            });
29370
29371            Self {
29372                addr,
29373                stop,
29374                requests,
29375                thread: Some(thread),
29376            }
29377        }
29378
29379        fn base_url(&self) -> String {
29380            format!("http://{}", self.addr)
29381        }
29382
29383        fn worker_protocol_for(&self, path: &str) -> Option<String> {
29384            self.requests
29385                .lock()
29386                .expect("captured requests")
29387                .iter()
29388                .find(|request| request.path == path)
29389                .and_then(|request| request.worker_protocol.clone())
29390        }
29391
29392        fn control_protocol_for(&self, path: &str) -> Option<String> {
29393            self.requests
29394                .lock()
29395                .expect("captured requests")
29396                .iter()
29397                .find(|request| request.path == path)
29398                .and_then(|request| request.control_protocol.clone())
29399        }
29400
29401        fn method_for(&self, path: &str) -> Option<String> {
29402            self.requests
29403                .lock()
29404                .expect("captured requests")
29405                .iter()
29406                .find(|request| request.path == path)
29407                .map(|request| request.method.clone())
29408        }
29409
29410        fn authorization_for(&self, path: &str) -> Option<String> {
29411            self.requests
29412                .lock()
29413                .expect("captured requests")
29414                .iter()
29415                .find(|request| request.path == path)
29416                .and_then(|request| request.authorization.clone())
29417        }
29418
29419        fn namespace_for(&self, path: &str) -> Option<String> {
29420            self.requests
29421                .lock()
29422                .expect("captured requests")
29423                .iter()
29424                .find(|request| request.path == path)
29425                .and_then(|request| request.namespace.clone())
29426        }
29427
29428        fn request_count(&self, path: &str) -> usize {
29429            self.requests
29430                .lock()
29431                .expect("captured requests")
29432                .iter()
29433                .filter(|request| request.path == path)
29434                .count()
29435        }
29436
29437        fn captured_paths(&self) -> Vec<String> {
29438            self.requests
29439                .lock()
29440                .expect("captured requests")
29441                .iter()
29442                .map(|request| request.path.clone())
29443                .collect()
29444        }
29445
29446        fn request_times(&self, path: &str) -> Vec<Instant> {
29447            self.requests
29448                .lock()
29449                .expect("captured requests")
29450                .iter()
29451                .filter(|request| request.path == path)
29452                .map(|request| request.received_at)
29453                .collect()
29454        }
29455
29456        fn request_body(&self, path: &str) -> Value {
29457            let requests = self.requests.lock().expect("captured requests");
29458            let body = &requests
29459                .iter()
29460                .find(|request| request.path == path)
29461                .unwrap_or_else(|| panic!("missing request for {path}"))
29462                .body;
29463            serde_json::from_str(body).unwrap_or_else(|error| {
29464                panic!("invalid JSON request body for {path}: {error}: {body:?}")
29465            })
29466        }
29467
29468        fn request_bodies(&self, path: &str) -> Vec<Value> {
29469            self.requests
29470                .lock()
29471                .expect("captured requests")
29472                .iter()
29473                .filter(|request| request.path == path)
29474                .map(|request| {
29475                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
29476                        panic!(
29477                            "invalid JSON request body for {path}: {error}: {:?}",
29478                            request.body
29479                        )
29480                    })
29481                })
29482                .collect()
29483        }
29484    }
29485
29486    impl Drop for MockWorkerServer {
29487        fn drop(&mut self) {
29488            self.stop.store(true, Ordering::SeqCst);
29489            let _ = TcpStream::connect(self.addr);
29490
29491            if let Some(thread) = self.thread.take() {
29492                thread.join().expect("join mock server");
29493            }
29494        }
29495    }
29496
29497    fn handle_mock_worker_request(
29498        stream: &mut TcpStream,
29499        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
29500        behavior: MockWorkerBehavior,
29501    ) {
29502        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
29503        let mut buffer = [0_u8; 8192];
29504        let mut request = Vec::new();
29505
29506        loop {
29507            match stream.read(&mut buffer) {
29508                Ok(0) => break,
29509                Ok(read) => {
29510                    request.extend_from_slice(&buffer[..read]);
29511                    if mock_request_is_complete(&request) {
29512                        break;
29513                    }
29514                }
29515                Err(error)
29516                    if matches!(
29517                        error.kind(),
29518                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
29519                    ) =>
29520                {
29521                    break;
29522                }
29523                Err(_) => return,
29524            }
29525        }
29526
29527        let request = String::from_utf8_lossy(&request);
29528        let body = request
29529            .split_once("\r\n\r\n")
29530            .map(|(_, body)| body)
29531            .unwrap_or_default();
29532        let path = request
29533            .lines()
29534            .next()
29535            .and_then(|line| line.split_whitespace().nth(1))
29536            .unwrap_or_default();
29537        let method = request
29538            .lines()
29539            .next()
29540            .and_then(|line| line.split_whitespace().next())
29541            .unwrap_or_default();
29542        let authorization = request.lines().find_map(|line| {
29543            let (name, value) = line.split_once(':')?;
29544            name.eq_ignore_ascii_case("Authorization")
29545                .then(|| value.trim().to_string())
29546        });
29547        let namespace = request.lines().find_map(|line| {
29548            let (name, value) = line.split_once(':')?;
29549            name.eq_ignore_ascii_case("X-Namespace")
29550                .then(|| value.trim().to_string())
29551        });
29552        let worker_protocol = request.lines().find_map(|line| {
29553            let (name, value) = line.split_once(':')?;
29554            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
29555                .then(|| value.trim().to_string())
29556        });
29557        let control_protocol = request.lines().find_map(|line| {
29558            let (name, value) = line.split_once(':')?;
29559            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
29560                .then(|| value.trim().to_string())
29561        });
29562        let request_number = {
29563            let mut requests = requests.lock().expect("captured requests");
29564            requests.push(CapturedRequest {
29565                headers: request
29566                    .split_once("\r\n\r\n")
29567                    .map_or("", |(headers, _)| headers)
29568                    .to_owned(),
29569                method: method.to_string(),
29570                path: path.to_string(),
29571                authorization,
29572                namespace,
29573                worker_protocol: worker_protocol.clone(),
29574                control_protocol,
29575                body: body.to_string(),
29576                received_at: Instant::now(),
29577            });
29578            requests
29579                .iter()
29580                .filter(|request| request.path == path)
29581                .count()
29582        };
29583
29584        if let Some(response) = behavior
29585            .request_override
29586            .and_then(|handler| handler(path, body, request_number))
29587        {
29588            write_mock_response(stream, response.0, &response.1);
29589            return;
29590        }
29591        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
29592            write_mock_response(stream, response.0, &response.1);
29593            return;
29594        }
29595        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
29596            return;
29597        }
29598        let pressure_path = behavior
29599            .storage_path
29600            .is_some_and(|part| path.contains(part));
29601        let prior_failures = if path.ends_with("/poll") {
29602            behavior.poll_failures_per_path
29603        } else {
29604            0
29605        };
29606        if pressure_path
29607            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
29608        {
29609            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
29610            let poll_id = path
29611                .ends_with("/poll")
29612                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
29613            let mut refusal = storage_refusal(
29614                poll_id,
29615                behavior.storage_unavailable,
29616                behavior.storage_mid_poll,
29617            );
29618            if behavior.storage_wrong_poll_id {
29619                refusal["poll_request_id"] = json!("wrong-poll");
29620            }
29621            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
29622            return;
29623        }
29624        if path.contains("/storage-task/")
29625            || path.contains("/storage-activity/")
29626            || path.contains("/storage-query/")
29627        {
29628            write_mock_response(stream, "200 OK", "{}");
29629            return;
29630        }
29631        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
29632            write_mock_response(stream, "200 OK", &json!({"task":{
29633                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
29634                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
29635                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29636                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29637                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
29638            }}).to_string());
29639            return;
29640        }
29641        if behavior.storage_activity
29642            && path == "/api/worker/activity-tasks/poll"
29643            && request_number == 1
29644        {
29645            write_mock_response(stream, "200 OK", &json!({"task":{
29646                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
29647                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
29648                "attempt_number":7, "lease_owner":"storage-worker"
29649            }}).to_string());
29650            return;
29651        }
29652
29653        if path == "/api/worker/register" {
29654            if behavior.reject_registration_protocol {
29655                write_mock_response(
29656                    stream,
29657                    "400 Bad Request",
29658                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
29659                );
29660                return;
29661            }
29662            if behavior.reject_registration {
29663                write_mock_response(
29664                    stream,
29665                    "503 Service Unavailable",
29666                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
29667                );
29668                return;
29669            }
29670        }
29671
29672        if path.starts_with("/api/worker/registrations/") {
29673            if behavior.reject_deregistration_protocol {
29674                write_mock_response(
29675                    stream,
29676                    "400 Bad Request",
29677                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
29678                );
29679            } else if behavior.reject_deregistration {
29680                write_mock_response(
29681                    stream,
29682                    "403 Forbidden",
29683                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
29684                );
29685            } else {
29686                write_mock_response(
29687                    stream,
29688                    "200 OK",
29689                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
29690                );
29691            }
29692            return;
29693        }
29694
29695        let is_poll = matches!(
29696            path,
29697            "/api/worker/workflow-tasks/poll"
29698                | "/api/worker/activity-tasks/poll"
29699                | "/api/worker/query-tasks/poll"
29700        );
29701        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
29702            write_mock_response(
29703                stream,
29704                "429 Too Many Requests",
29705                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
29706            );
29707            return;
29708        }
29709        if is_poll && request_number <= behavior.poll_failures_per_path {
29710            return;
29711        }
29712        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
29713            return;
29714        }
29715        if path == "/api/worker/heartbeat"
29716            && behavior.heartbeat_failure_request == Some(request_number)
29717        {
29718            return;
29719        }
29720        if path == "/api/worker/heartbeat"
29721            && behavior.delayed_heartbeat_request == Some(request_number)
29722        {
29723            thread::sleep(behavior.heartbeat_response_delay);
29724        }
29725        if behavior.unauthorized_polls && is_poll {
29726            write_mock_response(
29727                stream,
29728                "401 Unauthorized",
29729                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
29730            );
29731            return;
29732        }
29733        if behavior.draining_polls && is_poll {
29734            write_mock_response(
29735                stream,
29736                "409 Conflict",
29737                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
29738            );
29739            return;
29740        }
29741
29742        if let Some(codec_case) = behavior.invalid_task_payload_codec {
29743            if is_poll && request_number == 1 {
29744                let mut task = match path {
29745                    "/api/worker/workflow-tasks/poll" => json!({
29746                        "task_id": "codec-workflow",
29747                        "workflow_type": "codec.workflow",
29748                        "payload_codec": DEFAULT_CODEC,
29749                        "workflow_task_attempt": 1,
29750                        "lease_owner": "codec-worker"
29751                    }),
29752                    "/api/worker/activity-tasks/poll" => json!({
29753                        "task_id": "codec-activity",
29754                        "activity_attempt_id": "codec-activity-attempt",
29755                        "activity_type": "codec.activity",
29756                        "payload_codec": DEFAULT_CODEC,
29757                        "attempt_number": 1,
29758                        "lease_owner": "codec-worker"
29759                    }),
29760                    "/api/worker/query-tasks/poll" => json!({
29761                        "query_task_id": "codec-query",
29762                        "query_task_attempt": 1,
29763                        "workflow_type": "codec.workflow",
29764                        "query_name": "known",
29765                        "payload_codec": DEFAULT_CODEC,
29766                        "lease_owner": "codec-worker"
29767                    }),
29768                    _ => unreachable!("is_poll limits task codec probe paths"),
29769                };
29770                codec_case.apply(&mut task);
29771                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
29772                return;
29773            }
29774
29775            if matches!(
29776                path,
29777                "/api/worker/workflow-tasks/codec-workflow/fail"
29778                    | "/api/worker/activity-tasks/codec-activity/fail"
29779                    | "/api/worker/query-tasks/codec-query/fail"
29780            ) {
29781                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
29782                return;
29783            }
29784        }
29785
29786        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
29787            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
29788            let body = format!(
29789                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
29790            );
29791            write_mock_response(stream, "400 Bad Request", &body);
29792            return;
29793        }
29794
29795        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
29796        {
29797            write_mock_response(
29798                stream,
29799                "409 Conflict",
29800                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
29801            );
29802            return;
29803        }
29804
29805        if behavior.workflow_completion_status.is_some()
29806            && path == "/api/worker/workflow-tasks/poll"
29807            && request_number == 1
29808        {
29809            write_mock_response(
29810                stream,
29811                "200 OK",
29812                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"}}"#,
29813            );
29814            return;
29815        }
29816
29817        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
29818            if let (Some(status), Some(body)) = (
29819                behavior.workflow_completion_status,
29820                behavior.workflow_completion_body,
29821            ) {
29822                write_mock_response(stream, status, body);
29823                return;
29824            }
29825        }
29826
29827        if behavior.waiting_query_worker {
29828            if behavior.complete_named_signal
29829                && path == "/api/worker/workflow-tasks/poll"
29830                && request_number == 1
29831            {
29832                let body = json!({
29833                    "task": {
29834                        "task_id": "snapshot-open",
29835                        "workflow_id": "snapshot-1",
29836                        "run_id": "snapshot-run-1",
29837                        "workflow_type": "snapshot",
29838                        "payload_codec": DEFAULT_CODEC,
29839                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29840                            .expect("Avro workflow arguments"),
29841                        "history_events": [],
29842                        "workflow_task_attempt": 1,
29843                        "lease_owner": "rust-snapshot-worker"
29844                    }
29845                })
29846                .to_string();
29847                write_mock_response(stream, "200 OK", &body);
29848                return;
29849            }
29850
29851            let signal_request = request_number - usize::from(behavior.complete_named_signal);
29852            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
29853            if path == "/api/worker/workflow-tasks/poll"
29854                && signal_request >= 1
29855                && signal_request <= signal_request_limit
29856            {
29857                let finish = behavior.complete_named_signal && signal_request == 3;
29858                let amounts = if signal_request == 1 {
29859                    vec![3]
29860                } else {
29861                    vec![3, 5]
29862                };
29863                let task_id = if signal_request == 1 {
29864                    "snapshot-wait-3"
29865                } else if finish {
29866                    "snapshot-finish"
29867                } else {
29868                    "snapshot-wait-5"
29869                };
29870                let mut history_events = std::iter::once(json!({
29871                    "event_type": "SignalWaitOpened",
29872                    "payload": {"sequence": 1, "signal_name": "finish"}
29873                }))
29874                .chain(amounts.iter().enumerate().map(|(index, amount)| {
29875                    json!({
29876                        "event_type": "SignalReceived",
29877                        "payload": {
29878                            "signal_id": format!("increment-{amount}"),
29879                            "signal_name": "increment",
29880                            "workflow_sequence": index + 2,
29881                            "payload_codec": DEFAULT_CODEC,
29882                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29883                                .expect("Avro signal envelope")
29884                        }
29885                    })
29886                }))
29887                .collect::<Vec<_>>();
29888                let (resume_id, resume_name, resume_arguments) = if finish {
29889                    history_events.push(json!({
29890                        "event_type": "SignalReceived",
29891                        "payload": {
29892                            "signal_id": "finish",
29893                            "signal_name": "finish",
29894                            "workflow_sequence": 4,
29895                            "payload_codec": DEFAULT_CODEC,
29896                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29897                                .expect("Avro finish signal envelope")
29898                        }
29899                    }));
29900                    (
29901                        "finish".to_string(),
29902                        "finish".to_string(),
29903                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
29904                            .expect("Avro finish resume signal"),
29905                    )
29906                } else {
29907                    let amount = amounts.last().expect("amount");
29908                    (
29909                        format!("increment-{amount}"),
29910                        "increment".to_string(),
29911                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29912                            .expect("Avro increment resume signal"),
29913                    )
29914                };
29915                let body = json!({
29916                    "task": {
29917                        "task_id": task_id,
29918                        "workflow_id": "snapshot-1",
29919                        "run_id": "snapshot-run-1",
29920                        "workflow_type": "snapshot",
29921                        "payload_codec": DEFAULT_CODEC,
29922                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29923                            .expect("Avro workflow arguments"),
29924                        "history_events": history_events,
29925                        "workflow_task_attempt": 1,
29926                        "workflow_signal_id": resume_id,
29927                        "signal_name": resume_name,
29928                        "signal_arguments": resume_arguments,
29929                        "lease_owner": "rust-snapshot-worker"
29930                    }
29931                })
29932                .to_string();
29933                write_mock_response(stream, "200 OK", &body);
29934                return;
29935            }
29936
29937            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
29938                let history_events = [3, 5]
29939                    .into_iter()
29940                    .enumerate()
29941                    .map(|(index, amount)| {
29942                        json!({
29943                            "event_type": "SignalReceived",
29944                            "payload": {
29945                                "signal_id": format!("increment-{amount}"),
29946                                "signal_name": "increment",
29947                                "workflow_sequence": index + 2,
29948                                "payload_codec": DEFAULT_CODEC,
29949                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
29950                                    .expect("Avro query signal envelope")
29951                            }
29952                        })
29953                    })
29954                    .collect::<Vec<_>>();
29955                let body = json!({
29956                    "task": {
29957                        "query_task_id": "snapshot-current",
29958                        "query_task_attempt": 1,
29959                        "lease_owner": "rust-snapshot-worker",
29960                        "workflow_id": "snapshot-1",
29961                        "run_id": "snapshot-run-1",
29962                        "workflow_type": "snapshot",
29963                        "query_name": "current",
29964                        "payload_codec": DEFAULT_CODEC,
29965                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29966                            .expect("Avro workflow arguments"),
29967                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
29968                            .expect("Avro query arguments"),
29969                        "history_events": history_events,
29970                        "run_status": "waiting"
29971                    }
29972                })
29973                .to_string();
29974                write_mock_response(stream, "200 OK", &body);
29975                return;
29976            }
29977
29978            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
29979                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
29980            {
29981                write_mock_response(
29982                    stream,
29983                    "200 OK",
29984                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
29985                );
29986                return;
29987            }
29988
29989            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
29990                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
29991                return;
29992            }
29993
29994            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
29995                write_mock_response(
29996                    stream,
29997                    "200 OK",
29998                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
29999                );
30000                return;
30001            }
30002
30003            if path == "/api/worker/query-tasks/snapshot-current/complete" {
30004                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
30005                return;
30006            }
30007        }
30008
30009        if matches!(
30010            path,
30011            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
30012        ) {
30013            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30014                .expect("typed mock result");
30015            let body = json!({
30016                "result": typed_fidelity_probe().into_json().expect("result projection"),
30017                "result_envelope": result,
30018            })
30019            .to_string();
30020            write_mock_response(stream, "200 OK", &body);
30021            return;
30022        }
30023
30024        if path == "/api/workflows/typed-1" {
30025            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30026                .expect("typed mock result");
30027            let body = json!({
30028                "workflow_id": "typed-1",
30029                "run_id": "run-typed-1",
30030                "workflow_type": "typed.echo",
30031                "status": "completed",
30032                "output": typed_fidelity_probe().into_json().expect("output projection"),
30033                "output_envelope": result,
30034            })
30035            .to_string();
30036            write_mock_response(stream, "200 OK", &body);
30037            return;
30038        }
30039
30040        let (status, body) = match path {
30041            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
30042            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
30043            "/api/workflows" => (
30044                "201 Created",
30045                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
30046            ),
30047            "/api/worker/register" if behavior.decline_registration => (
30048                "200 OK",
30049                r#"{"worker_id":"declined-worker","registered":false}"#,
30050            ),
30051            "/api/worker/register" if behavior.waiting_query_worker => (
30052                "200 OK",
30053                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
30054            ),
30055            "/api/worker/register" => (
30056                "200 OK",
30057                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
30058            ),
30059            "/api/worker/heartbeat" => ("200 OK", "{}"),
30060            "/api/worker/activity-tasks/poll"
30061                if behavior.cancelled_activity && request_number == 1 =>
30062            {
30063                (
30064                    "200 OK",
30065                    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"}}"#,
30066                )
30067            }
30068            "/api/worker/activity-tasks/poll"
30069                if behavior.long_poll_capacity_responses_per_path > 0
30070                    && request_number
30071                        == behavior
30072                            .long_poll_capacity_responses_per_path
30073                            .saturating_add(1) =>
30074            {
30075                (
30076                    "200 OK",
30077                    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"}}"#,
30078                )
30079            }
30080            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
30081                ("200 OK", r#"{"task":null}"#)
30082            }
30083            "/api/worker/query-tasks/poll"
30084                if behavior.reject_query_completion && request_number == 1 =>
30085            {
30086                (
30087                    "200 OK",
30088                    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"}}"#,
30089                )
30090            }
30091            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
30092            "/api/worker/query-tasks/query-capture/complete"
30093            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
30094            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
30095                "200 OK",
30096                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
30097            ),
30098            "/api/worker/activity-tasks/activity-cancel/complete" => (
30099                "409 Conflict",
30100                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
30101            ),
30102            "/api/worker/activity-tasks/activity-typed/complete"
30103            | "/api/worker/activity-tasks/activity-typed/fail"
30104            | "/api/worker/activity-tasks/capacity-activity/complete"
30105            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
30106            "/api/workflows/counter-1/query/current" => (
30107                "200 OK",
30108                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
30109            ),
30110            "/api/workflows/counter-1/query/missing" => (
30111                "404 Not Found",
30112                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
30113            ),
30114            "/api/workflows/wf-lifecycle/cancel" => (
30115                "200 OK",
30116                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
30117            ),
30118            "/api/workflows/wf-lifecycle/terminate" => (
30119                "200 OK",
30120                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
30121            ),
30122            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
30123                "200 OK",
30124                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
30125            ),
30126            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
30127                "200 OK",
30128                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
30129            ),
30130            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
30131                "202 Accepted",
30132                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
30133            ),
30134            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
30135                "200 OK",
30136                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}"#,
30137            ),
30138            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
30139                "409 Conflict",
30140                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
30141            ),
30142            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
30143            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
30144                "409 Conflict",
30145                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
30146            ),
30147            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
30148                "200 OK",
30149                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"}]}}"#,
30150            ),
30151            "/api/workflows/wf-cancelled" => (
30152                "200 OK",
30153                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
30154            ),
30155            "/api/workflows/wf-terminated" => (
30156                "200 OK",
30157                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
30158            ),
30159            "/api/workflows/wf-timed-out" => (
30160                "200 OK",
30161                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
30162            ),
30163            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
30164                "200 OK",
30165                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
30166            ),
30167            "/api/workflows/wf-selected" => (
30168                "200 OK",
30169                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
30170            ),
30171            "/api/workflows/wf-selected/runs/run-selected" => (
30172                "200 OK",
30173                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
30174            ),
30175            _ => ("404 Not Found", r#"{"message":"not found"}"#),
30176        };
30177        write_mock_response(stream, status, body);
30178    }
30179
30180    fn mock_request_is_complete(request: &[u8]) -> bool {
30181        let Some(header_end) = request
30182            .windows(4)
30183            .position(|window| window == b"\r\n\r\n")
30184            .map(|position| position + 4)
30185        else {
30186            return false;
30187        };
30188        let headers = String::from_utf8_lossy(&request[..header_end]);
30189        let content_length = headers.lines().find_map(|line| {
30190            let (name, value) = line.split_once(':')?;
30191            name.eq_ignore_ascii_case("content-length")
30192                .then(|| value.trim().parse::<usize>().ok())
30193                .flatten()
30194        });
30195
30196        request.len() >= header_end + content_length.unwrap_or(0)
30197    }
30198
30199    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
30200        let response = format!(
30201            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
30202            body.len()
30203        );
30204
30205        let _ = stream.write_all(response.as_bytes());
30206        let _ = stream.flush();
30207    }
30208
30209    fn activity_completion_backend_recovery(
30210        path: &str,
30211        _body: &str,
30212        request_number: usize,
30213    ) -> Option<(&'static str, String)> {
30214        match path {
30215            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
30216                "200 OK",
30217                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(),
30218            )),
30219            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
30220                "503 Service Unavailable",
30221                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(),
30222            )),
30223            "/api/worker/activity-tasks/recover-activity/complete" => Some((
30224                "200 OK",
30225                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30226            )),
30227            _ => None,
30228        }
30229    }
30230
30231    fn workflow_completion_backend_recovery(
30232        path: &str,
30233        _body: &str,
30234        request_number: usize,
30235    ) -> Option<(&'static str, String)> {
30236        match path {
30237            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
30238                "200 OK",
30239                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
30240            )),
30241            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
30242                "503 Service Unavailable",
30243                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(),
30244            )),
30245            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
30246                "200 OK",
30247                r#"{"outcome":"completed","recorded":true}"#.to_string(),
30248            )),
30249            _ => None,
30250        }
30251    }
30252
30253    fn activity_completion_stale_after_backend_recovery(
30254        path: &str,
30255        body: &str,
30256        request_number: usize,
30257    ) -> Option<(&'static str, String)> {
30258        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
30259            return Some((
30260                "409 Conflict",
30261                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(),
30262            ));
30263        }
30264        activity_completion_backend_recovery(path, body, request_number)
30265    }
30266
30267    fn activity_completion_remains_unavailable(
30268        path: &str,
30269        body: &str,
30270        request_number: usize,
30271    ) -> Option<(&'static str, String)> {
30272        if path == "/api/worker/activity-tasks/recover-activity/complete" {
30273            return activity_completion_backend_recovery(path, body, 1);
30274        }
30275        activity_completion_backend_recovery(path, body, request_number)
30276    }
30277
30278    #[tokio::test]
30279    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
30280        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30281            request_override: Some(activity_completion_backend_recovery),
30282            ..MockWorkerBehavior::default()
30283        });
30284        let client = Client::builder(server.base_url())
30285            .timeout(Duration::from_secs(2))
30286            .build()
30287            .expect("client");
30288        let handler_calls = Arc::new(AtomicUsize::new(0));
30289        let mut worker = Worker::new(client, "recover-queue")
30290            .worker_id("recover-worker")
30291            .poll_timeout(Duration::from_millis(10));
30292        worker.register_activity("recover.activity", {
30293            let handler_calls = Arc::clone(&handler_calls);
30294            move |_ctx, _args| {
30295                let handler_calls = Arc::clone(&handler_calls);
30296                async move {
30297                    handler_calls.fetch_add(1, Ordering::SeqCst);
30298                    Ok(json!("done"))
30299                }
30300            }
30301        });
30302
30303        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30304        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30305        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
30306        assert_eq!(bodies.len(), 2);
30307        assert_eq!(bodies[0], bodies[1]);
30308    }
30309
30310    #[tokio::test]
30311    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
30312        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30313            request_override: Some(workflow_completion_backend_recovery),
30314            ..MockWorkerBehavior::default()
30315        });
30316        let client = Client::builder(server.base_url())
30317            .timeout(Duration::from_secs(2))
30318            .build()
30319            .expect("client");
30320        let handler_calls = Arc::new(AtomicUsize::new(0));
30321        let mut worker = Worker::new(client, "recover-queue")
30322            .worker_id("recover-worker")
30323            .poll_timeout(Duration::from_millis(10));
30324        worker.register_workflow("recover.workflow", {
30325            let handler_calls = Arc::clone(&handler_calls);
30326            move |_ctx, _args| {
30327                let handler_calls = Arc::clone(&handler_calls);
30328                async move {
30329                    handler_calls.fetch_add(1, Ordering::SeqCst);
30330                    Ok(json!("done"))
30331                }
30332            }
30333        });
30334
30335        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
30336        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30337        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
30338        assert_eq!(bodies.len(), 2);
30339        assert_eq!(bodies[0], bodies[1]);
30340    }
30341
30342    #[tokio::test]
30343    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
30344        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30345            request_override: Some(activity_completion_stale_after_backend_recovery),
30346            ..MockWorkerBehavior::default()
30347        });
30348        let client = Client::builder(server.base_url())
30349            .timeout(Duration::from_secs(2))
30350            .build()
30351            .expect("client");
30352        let handler_calls = Arc::new(AtomicUsize::new(0));
30353        let mut worker = Worker::new(client, "recover-queue")
30354            .worker_id("recover-worker")
30355            .poll_timeout(Duration::from_millis(10));
30356        worker.register_activity("recover.activity", {
30357            let handler_calls = Arc::clone(&handler_calls);
30358            move |_ctx, _args| {
30359                let handler_calls = Arc::clone(&handler_calls);
30360                async move {
30361                    handler_calls.fetch_add(1, Ordering::SeqCst);
30362                    Ok(json!("done"))
30363                }
30364            }
30365        });
30366
30367        assert_eq!(
30368            worker
30369                .run_once()
30370                .await
30371                .expect("authoritative stale outcome"),
30372            1
30373        );
30374        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
30375        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
30376        assert_eq!(bodies.len(), 2);
30377        assert_eq!(bodies[0], bodies[1]);
30378    }
30379
30380    #[test]
30381    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
30382        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
30383        let response = json!({
30384            "reason":"backend_unavailable", "operation":"complete_activity_task",
30385            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
30386            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
30387            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
30388        });
30389        let path = "/worker/activity-tasks/recover-activity/complete";
30390        let error = |body: Value| Error::Http {
30391            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30392            body: body.to_string(),
30393        };
30394        assert_eq!(
30395            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
30396            Some(Duration::from_secs(1))
30397        );
30398
30399        for (field, invalid) in [
30400            ("operation", json!("poll_activity_task")),
30401            ("outcome", json!("rejected")),
30402            ("worker_id", json!("another-worker")),
30403            ("task_queue", json!("recover-queue")),
30404            ("retryable", json!(false)),
30405            ("retry_after_seconds", json!(0)),
30406            ("task_id", json!("another-task")),
30407            ("lease_owner", json!("another-worker")),
30408            ("activity_attempt_id", json!("another-attempt")),
30409        ] {
30410            let mut invalid_response = response.clone();
30411            invalid_response[field] = invalid;
30412            assert_eq!(
30413                worker_fenced_completion_retry_after(
30414                    &error(invalid_response),
30415                    path,
30416                    Some(&request)
30417                ),
30418                None,
30419                "must not retry mismatched {field}"
30420            );
30421        }
30422        assert_eq!(
30423            worker_fenced_completion_retry_after(&error(response), path, None),
30424            None
30425        );
30426    }
30427
30428    #[tokio::test]
30429    async fn shutdown_interrupts_fenced_completion_backend_wait() {
30430        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30431            request_override: Some(activity_completion_remains_unavailable),
30432            ..MockWorkerBehavior::default()
30433        });
30434        let client = Client::builder(server.base_url())
30435            .timeout(Duration::from_secs(2))
30436            .build()
30437            .expect("client");
30438        let stop = Arc::new(AtomicBool::new(false));
30439        let worker = Worker::new(client, "recover-queue")
30440            .worker_id("recover-worker")
30441            .with_storage_admission(Arc::clone(&stop));
30442        let completion = tokio::spawn(async move {
30443            worker
30444                .client
30445                .complete_activity_task(
30446                    "recover-activity",
30447                    "recover-attempt",
30448                    "recover-worker",
30449                    json!("done"),
30450                    DEFAULT_CODEC,
30451                )
30452                .await
30453        });
30454        let path = "/api/worker/activity-tasks/recover-activity/complete";
30455        tokio::time::timeout(Duration::from_secs(2), async {
30456            while server.request_count(path) == 0 {
30457                tokio::time::sleep(Duration::from_millis(10)).await;
30458            }
30459        })
30460        .await
30461        .expect("first completion request");
30462        stop.store(true, Ordering::SeqCst);
30463        let error = tokio::time::timeout(Duration::from_secs(1), completion)
30464            .await
30465            .expect("shutdown must interrupt retry wait")
30466            .expect("completion task")
30467            .expect_err("backend is still unavailable");
30468        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
30469        assert_eq!(server.request_count(path), 1);
30470    }
30471}